Possibility of clean the code? Good night! Based on stuff I get a bit here and there, came up with a program for an Arduino Audio Selector with shift registers and some features. Working as expected, only missing connecting the relay boads, but that's for future. Since I have a few devices, instead of having to write all, is there anyway of I change for instance a line and then on display show that line?

Thanks. Here's my code, realy big, try to short the part of the shift registers but seems to me it was unstable.

Arduino selector 4x20

I see a lot of 'almost' repetitions like :

  if (RelaySourceDigi == 7) {
    shifter.setPin(16, LOW);
    shifter.setPin(17, LOW);
    shifter.setPin(18, LOW);
    shifter.setPin(19, LOW);
    shifter.setPin(20, LOW);
    shifter.setPin(21, LOW);
    shifter.setPin(22, HIGH);
    shifter.setPin(23, LOW);
    shifter.write();
    lcd.setCursor(0, 2);
    lcd.write(8);
    lcd.setCursor(2, 2);
    lcd.print("Coaxial 3");
  }

Move this to a separate function, and make an argument (or more) of items that vary.
This will greatly reduce your code, making it more managable/maintainable.

Below I changed the entire program. Note I didn't check for runtime errors, and it is highly possible I made some copy/paste errors, but it will give you a clue what you can change. As you can see, the program is radically shortened (and more maintainable).

What you need to do is:

Check each change
Check for copy/paste errors
Read a little bit about pointers (e.g. the &RelaySource and *t constructs)
Also I highly suggest not to use so many constants, but use enums, to denote the value for each different mode you have. So instead of case 1, you can write case TAPE_1.
Split loop in smaller functions (e.g. one function per mode).
I didn't install your libraries but used e.g. #include "LiquidCrystal_I2C.h" and stubbed all functions (meaning I can call them but they don't do anything, just to check for compiler errors in the main program).
Also instead of Aux, use a boolean (true, false).
You see I use a lot of (state - 1) constructs. It's common practice to start counting at 0, not at 1, it will make your life easier. Only when displaying a value for a user, add +1.
Below the program.

//Libraries
#include "LCD.h"
#include "LiquidCrystal_I2C.h"
#include "Shifter.h"

#define SER_Pin 8 //SER_IN 14 on 74HC595
#define RCLK_Pin 9 //L_CLOCK 12 on 74HC595
#define SRCLK_Pin 10 //CLOCK 11 on 74HC595
#define NUM_REGISTERS 3 //how many registers are in the chain
//initaize shifter using the Shifter library
Shifter shifter(SER_Pin, RCLK_Pin, SRCLK_Pin, NUM_REGISTERS);

LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // Set the LCD I2C address

const int ButtonPinUp = 2;
int ButtonPinUpState = 0;
const int ButtonPinDn = 3;
int ButtonPinDnState = 0;
const int MuteButtonPin = 5;
int MuteButtonPinState = 0;
const int AuxButtonPin = 4;
int AuxButtonPinState = 0;
const int fbutton = 6;
int RelaySource = 1;
int RelaySourceDigi = 1;
int RelayRec = 1;
int RecDigi = 1;
int Mute = 0;
int Mode = 0;
int Aux = 1;
int state = 0;
int old = 0;
int ButtonPoll = 0;

byte opt[8] = {
  0b00000,
  0b01110,
  0b11011,
  0b10001,
  0b10001,
  0b10001,
  0b11111,
  0b00000
};

byte coax[8] = {
  0b00100,
  0b01110,
  0b11111,
  0b10001,
  0b10001,
  0b01110,
  0b00100,
  0b00100
};

byte mut[8] = {
  0b00001,
  0b00011,
  0b00111,
  0b11111,
  0b11111,
  0b00111,
  0b00011,
  0b00001
};

byte outp[8] = {
  B00000,
  B00100,
  B00110,
  B11111,
  B11111,
  B00110,
  B00100,
  B00000
};

byte upp[8] = {
  0b11111,
  0b11111,
  0b11111,
  0b11111,
  0b11111,
  0b11111,
  0b11111,
  0b11111
};

byte inpp[8] {
  0b10000,
  0b10000,
  0b10100,
  0b10110,
  0b11111,
  0b00110,
  0b00100,
  0b00000
};

byte ann[8] {

  0b11111,
  0b10001,
  0b10101,
  0b10101,
  0b10001,
  0b10101,
  0b10101,
  0b11111
};

byte dnn[8] = {
  0b11111,
  0b10011,
  0b10101,
  0b10101,
  0b10101,
  0b10101,
  0b10011,
  0b11111
};

byte too[8] = {
  0b00000,
  0b00100,
  0b00110,
  0b11111,
  0b00110,
  0b00100,
  0b00000,
  0b00000
};

void printAtCursor(int a, int b, const char* c)
{
  lcd.setCursor(a, b);
  lcd.print(c);
}

void setup() {
  lcd.begin(20, 4);
  lcd.backlight();

  byte* list[] = {outp, coax, mut, opt, upp, inpp, ann, dnn, too };
  for (int n = 0; n < 9; n++)
  {
    lcd.createChar(n + 1, list[n]);
  }

  pinMode(fbutton, INPUT);
  pinMode(ButtonPinUp, INPUT);
  pinMode(MuteButtonPin, INPUT);
  pinMode(ButtonPinDn, INPUT);
  pinMode(AuxButtonPin, INPUT);

  for (int n = 11; n < 14; n++)
  {
    pinMode(n, OUTPUT);
  }

  printAtCursor(3, 0, "Digital/Analog");
  printAtCursor(3, 1, "Audio Selector");
  printAtCursor(4, 2, "Built-In DAC");
  printAtCursor(2, 3, "V2.0f (23052020)");
  delay(4000);
  lcd.clear();
}

void setPin(int first, int last, int pin)
{
  for (int n = first; n < last + 1; n++)
  {
    shifter.setPin(n, pin == n ? HIGH : LOW);
  }

  shifter.write();
}

void setLines(int a, int b, const char* t, int x = -1, const char* u = "")
{
    lcd.setCursor(0, a);
    lcd.write(b);
    lcd.setCursor(2, a);
    lcd.print(t);
    if (x != -1)
    {
      lcd.write(x);
      lcd.print(u);
    }
}

void loop()
{
  // shifter.clear(); //set all pins on the shift register chain to LOW
  shifter.write(); //send changes to the chain and display them
  //check button states
  ButtonPinUpState = digitalRead(ButtonPinUp);
  ButtonPinDnState = digitalRead(ButtonPinDn);
  MuteButtonPinState = digitalRead(MuteButtonPin);
  AuxButtonPinState = digitalRead(AuxButtonPin);
  ButtonPoll = digitalRead(fbutton);

  if (AuxButtonPinState == HIGH && RelaySource == 1 && state == 1) {
    lcd.clear();
    Aux           = ~Aux;
    digitalWrite(13, Aux == 0 ? LOW : HIGH);
  }

  if (ButtonPoll == HIGH) {
    state = old + 1;
  }

  lcd.clear(); // Happens in all cases
  switch (state) {
    case 1: // Fall through
    case 2: // Fall through
    case 3: // Fall through
    case 4:
      lcd.setCursor(1, state - 1);
      lcd.write(5);
      old = state;
      break;

    default:
      old = 0;
      break;
  }

  // Assuming state = 1..4
  if (ButtonPinUpState == HIGH)
  {
    lcd.clear();
    int* t = NULL;
    int maxValue = -1;

    switch (state)
    {
      case 1: t = &RelaySource;     maxValue = 8; break;
      case 2: t = &RelayRec;        maxValue = 5; break;
      case 3: t = &RelaySourceDigi; maxValue = 8; break;
      case 4: t = &RecDigi;         maxValue = 4; break;
      default: break;
    }

    *t = min(1, max(maxValue, *t + (ButtonPinUpState == HIGH ? 1 : 0) + (ButtonPinDnState == HIGH ? -1 : 0)));
  }

  if (MuteButtonPinState == HIGH) {
    lcd.clear();
    Mute = (Mute == 0 ? 1 : 0);
    digitalWrite(12, Mute == 0 ? HIGH : LOW);
  }

  // RelaySource
  setPin(0, 7, RelaySource - 1);
  if (RelaySource == 1 && Aux == 0)
  {
    setLines(0, 7, "D", 9, "A:");
  }
  else
  {
    const char* rs1[] = { "Line 1", "Line 2", "CD 1", "CD 2", "Tape 1", "Tape 2/DCC", "Tape 3/DAT", "MD", "MD" };
    setLines(0, 7, rs1[RelaySource - 1]);
  }

  if (RelaySource == 8)
  {
    shifter.setPin(0, LOW); //set pin 1 in the chain(second pin) HIGH
  }

  // RelayRec
  int         rr1[] = { 8      , -1   , 9       , 10      , 11       };
  const char* rr2[] = {"Source", "OFF", "Tape 1", "Tape 2", "Tape 3" };
  const int   rr3[] = { -1     , -1   , 9       , 9       , 9        };
  const char* rr4[] = { ""     , ""   , "2,3"   , "1,3"   , "1,2"    };

  setPin(8, 11, rr1[RelayRec - 1]);
  setLines(1, 6, rr2[RelayRec - 1], rr3[RelayRec - 1], rr4[RelayRec - 1]);

  // RelaySourceDigi
  setPin(16, 23, 17 - RelaySourceDigi);
  if (RelaySource == 1 && Aux == 0)
  {
    lcd.setCursor(7, 0);
    const char* t[] = { "Optical 1", "Optical 2", "Optical 3", "Optical 4", "Coaxial 1", "Coaxial 2", "Coaxial 3", "Coaxial 4" };
    lcd.print(t[RelaySource - 1]);
  }

  const char* t1[] = { "Sony 5-CD", "Sony MD[", "Optical 3", "Optical 4", "Philips CD-R [", "Coaxial 2", "Coaxial 3", "Coaxial 4" };
  const int   t2[] = { 4          , 4         , -1         , -1         , 2               , -1        , -1         , -1          };
  const char* t3[] = { "]"        , "]"       , ""         , ""         , "]"             , ""        , ""         , ""          };
  setLines(2, 8, t1[RelaySourceDigi - 1], t2[RelaySourceDigi - 1], t3[RelaySourceDigi - 2]);

  // RecDigi
  const char* t[] = { "Optical Out1", "Optical Out 2", "Coaxial Out 1", "Coaxial Out2" };
  setPin(12, 15, 11 + RecDigi);
  setLines(3, 6, t[RecDigi - 1]);

  delay(150);
}

Update

I wanted for myself to see how to clean it fully, so I tried below.

Still check for copy/paste problems, as I didn't execute the sketch (but it compiles without warnings).

Original sketch: 2746 bytes (8%) program storage space, 142 bytes (6%) of dynamic memory
Sketch below   : 1546 bytes (4%) program storage space,  40 bytes (2%) of dynamic memory.

Conclusion:

25% less program storage space used
67% less dynamic memory used
Less lines of code
Better readability
Better maintainability
No (or less) code duplication
Smaller function complexity
Less statements (added more to initialization)

Code:

//Libraries
#include "LCD.h"
#include "LiquidCrystal_I2C.h"
#include "Shifter.h"

const uint8_t SER_Pin = 8; //SER_IN 14 on 74HC595
const uint8_t RCLK_Pin = 9; //L_CLOCK 12 on 74HC595
const uint8_t SRCLK_Pin = 10; //CLOCK 11 on 74HC595
const uint8_t NUM_REGISTERS = 3; //how many registers are in the chain

Shifter _shifter(SER_Pin, RCLK_Pin, SRCLK_Pin, NUM_REGISTERS);
LiquidCrystal_I2C _lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // Set the LCD I2C address

enum EMode
{
  RELAY_SOURCE,
  RELAY_REC,
  RELAY_SOURCE_DIGI,
  REC_DIGI,
  LAST_MODE
};

static const uint8_t _buttonPinUp = 2;
bool _buttonPinUpState = false;
static const uint8_t _buttonPinDown = 3;
bool _buttonPinDownState = false;
static const uint8_t _muteButtonPin = 5;
bool _muteButtonPinState = false;
static const uint8_t _auxButtonPin = 4;
bool _auxButtonPinState = false;
static const uint8_t _forwardButton = 6;
uint8_t _relaySource = 0;
uint8_t _relaySourceDigi = 0;
uint8_t _relayRec = 0;
uint8_t _recDigi = 0;
bool _mute = false;
bool _aux = true;
EMode _mode = RELAY_SOURCE;
bool _buttonPoll = false;

static const byte OPT[8]  PROGMEM = {  0b00000,  0b01110,  0b11011,  0b10001,  0b10001,  0b10001,  0b11111,  0b00000 };
static const byte COAX[8] PROGMEM = {  0b00100,  0b01110,  0b11111,  0b10001,  0b10001,  0b01110,  0b00100,  0b00100 };
static const byte MUT[8]  PROGMEM = {  0b00001,  0b00011,  0b00111,  0b11111,  0b11111,  0b00111,  0b00011,  0b00001 };
static const byte OUTP[8] PROGMEM = {  B00000 ,  B00100 ,  B00110 ,  B11111 ,  B11111 ,  B00110 ,  B00100 ,  B00000  };
static const byte UPP[8]  PROGMEM = {  0b11111,  0b11111,  0b11111,  0b11111,  0b11111,  0b11111,  0b11111,  0b11111 };
static const byte INPP[8] PROGMEM = {  0b10000,  0b10000,  0b10100,  0b10110,  0b11111,  0b00110,  0b00100,  0b00000 };
static const byte ANN[8]  PROGMEM = {  0b11111,  0b10001,  0b10101,  0b10101,  0b10001,  0b10101,  0b10101,  0b11111 };
static const byte DNN[8]  PROGMEM = {  0b11111,  0b10011,  0b10101,  0b10101,  0b10101,  0b10101,  0b10011,  0b11111 };
static const byte TOO[8]  PROGMEM = {  0b00000,  0b00100,  0b00110,  0b11111,  0b00110,  0b00100,  0b00000,  0b00000 };

static const byte* const CHAR_LIST[] PROGMEM = {OUTP, COAX, MUT, OPT, UPP, INPP, ANN, DNN, TOO };
static const uint8_t PINS[] PROGMEM = { _forwardButton, _buttonPinUp, _muteButtonPin, _buttonPinDown, _auxButtonPin };

static uint8_t* const    MODE_VALUES[] PROGMEM = { &_relaySource, &_relayRec, &_relaySourceDigi, &_recDigi };
static const uint8_t     MAX_VALUES[] PROGMEM = { 7             , 4         , 7                , 3         };

static const char* const RELAY_SOURCES[] PROGMEM = { "Line 1", "Line 2", "CD 1", "CD 2", "Tape 1", "Tape 2/DCC", "Tape 3/DAT", "MD", "MD" };

static const char* const RELAY_SOURCE_DIGI_1[] PROGMEM = { "Sony 5-CD", "Sony MD[", "Optical 3", "Optical 4", "Philips CD-R [", "Coaxial 2", "Coaxial 3", "Coaxial 4" };
static const int         RELAY_SOURCE_DIGI_2[]         = { 4          , 4         , -1         , -1         , 2               , -1        , -1         , -1          };
static const char* const RELAY_SOURCE_DIGI_3[] PROGMEM = { "]"        , "]"       , ""         , ""         , "]"             , ""        , ""         , ""          };

static const int         RELAY_REC_1[] PROGMEM = { 8      , -1   , 9       , 10      , 11       };
static const char* const RELAY_REC_2[] PROGMEM = {"Source", "OFF", "Tape 1", "Tape 2", "Tape 3" };
static const int         RELAY_REC_3[] PROGMEM = { -1     , -1   , 9       , 9       , 9        };
static const char* const RELAY_REC_4[] PROGMEM = { ""     , ""   , "2,3"   , "1,3"   , "1,2"    };

static const char* const DIGI_RELAY_SOURCES[] PROGMEM = { "Optical 1", "Optical 2", "Optical 3", "Optical 4", "Coaxial 1", "Coaxial 2", "Coaxial 3", "Coaxial 4" };

void printAtCursor(int a, int b, const char* c)
{
  _lcd.setCursor(a, b);
  _lcd.print(c);
}

void setup()
{
  _lcd.begin(20, 4);
  _lcd.backlight();

  for (int n = 0; n < 9; n++)
  {
    _lcd.createChar(n + 1, (byte*) CHAR_LIST[n]);
  }

  for (int n = 0; n < sizeof(PINS) / sizeof(uint8_t); n++)
  {
    pinMode(PINS[n], INPUT);
  }

  for (int n = 11; n < 14; n++)
  {
    pinMode(n, OUTPUT);
  }

  printAtCursor(3, 0, "Digital/Analog");
  printAtCursor(3, 1, "Audio Selector");
  printAtCursor(4, 2, "Built-In DAC");
  printAtCursor(2, 3, "V2.0f (23052020)");
  delay(4000);
}

void setPin(int first, int last, int pin)
{
  for (int n = first; n < last + 1; n++)
  {
    _shifter.setPin(n, pin == n ? HIGH : LOW);
  }

  _shifter.write();
}

void setLines(int a, int b, const char* t, int x = -1, const char* u = "")
{
    _lcd.setCursor(0, a);
    _lcd.write(b);
    _lcd.setCursor(2, a);
    _lcd.print(t);

    if (x != -1)
    {
      _lcd.write(x);
      _lcd.print(u);
    }
}

void ResetShifter()
{
  // _shifter.clear(); //set all pins on the shift register chain to LOW
  _shifter.write(); //send changes to the chain and display them
}

void ReadButtons()
{
  _buttonPinUpState = digitalRead(_buttonPinUp) == HIGH;
  _buttonPinDownState = digitalRead(_buttonPinDown) == HIGH;
  _muteButtonPinState = digitalRead(_muteButtonPin) == HIGH;
  _auxButtonPinState = digitalRead(_auxButtonPin) == HIGH;
  _buttonPoll = digitalRead(_forwardButton) == HIGH;
}

void HandleAuxButton()
{
  if (_auxButtonPinState && (_relaySource == 0) && (_mode == EMode::RELAY_SOURCE))
  {
    _aux = !_aux;
    digitalWrite(13, _aux ? HIGH : LOW);
  }
}

void HandlePollButton()
{
  if (_buttonPoll)
  {
    _mode = (EMode) ((_mode + 1) % EMode::LAST_MODE);
  }
}

void StartLcd()
{
  _lcd.clear(); // Happens in all cases
  _lcd.setCursor(1, (int) _mode);
  _lcd.write(5);
}

void HandleButtonPinUp()
{
  if (_buttonPinUpState)
  {
    static uint8_t* const modeValue = MODE_VALUES[_mode];
    static uint8_t maxValue = MAX_VALUES[_mode];
    *modeValue = min(0, max(maxValue, *modeValue + (_buttonPinUpState ? 1 : 0) + (_buttonPinDownState ? -1 : 0)));
  }
}

void HandleMuteButton()
{
  if (_muteButtonPinState)
  {
    _mute = !_mute;
    digitalWrite(12, _mute ? HIGH : LOW);
  }
}

void ProcessRelaySource()
{
  // RelaySource
  setPin(0, 7, _relaySource);
  if (_relaySource == 0 && !_aux)
  {
    setLines(0, 7, "D", 9, "A:");
  }
  else
  {
    setLines(0, 7, RELAY_SOURCES[_relaySource]);
  }

  if (_relaySource == 7)
  {
    _shifter.setPin(0, LOW); //set pin 1 in the chain(second pin) HIGH
  }
}

void ProcessRelayRec()
{
  setPin(8, 11, RELAY_REC_1[_relayRec]);
  setLines(1, 6, RELAY_REC_2[_relayRec], RELAY_REC_3[_relayRec], RELAY_REC_4[_relayRec]);
}

void ProcessRelaySourceDigi()
{
  setPin(16, 23, 17 - _relaySourceDigi);
  if (_relaySource == 0 && !_aux)
  {
    _lcd.setCursor(7, 0);
    _lcd.print(DIGI_RELAY_SOURCES[_relaySource]);
  }
  setLines(2, 8, RELAY_SOURCE_DIGI_1[_relaySourceDigi - 1], RELAY_SOURCE_DIGI_2[_relaySourceDigi - 1], RELAY_SOURCE_DIGI_3[_relaySourceDigi - 2]);
}

void ProcessRecDigi()
{
  static const char* const t[] PROGMEM = { "Optical Out1", "Optical Out 2", "Coaxial Out 1", "Coaxial Out2" };
  setPin(12, 15, 12 + _recDigi);
  setLines(3, 6, t[_recDigi]);
  delay(150);
}

void loop()
{
  ResetShifter();
  ReadButtons();

  HandleAuxButton();
  HandlePollButton();
  StartLcd();
  HandleButtonPinUp();
  HandleMuteButton();

  ProcessRelaySource();
  ProcessRelayRec();
  ProcessRelaySourceDigi();
  ProcessRecDigi();
}


Better way to remap 16-Key Touch keypad I have written a code that remaps the buttons of TTP229 touch keypad which works as it is. Is there any way to optimize this code:

#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>

#define SCL_PIN 11
#define SDO_PIN 12
#define I2C_ADDR    0x3F
#define BACKLIGHT_PIN     3
#define En_pin  2
#define Rw_pin  1
#define Rs_pin  0
#define D4_pin  4
#define D5_pin  5
#define D6_pin  6
#define D7_pin  7

byte Key;
String keyRemap[12][2] = {
    {"1","1"},{"2","2"},
    {"3","3"},{"5","4"},
    {"6","5"},{"7","6"},
    {"9","7"},{"10","8"},
    {"11","9"},{"14","0"},
    {"13","Clear"},{"15","Enter"}
};

LiquidCrystal_I2C  lcd(I2C_ADDR,En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin);

void setup()
{
    lcd.begin (16,2);
    lcd.setBacklightPin(BACKLIGHT_PIN,POSITIVE);
    lcd.setBacklight(HIGH);
    lcd.home ();

    pinMode(SCL_PIN, OUTPUT);
    pinMode(SDO_PIN, INPUT);
}
void loop()
{
    Key = Read_Keypad();
    if (Key != 0) {
        lcd.clear();
        lcd.setCursor (0,0);
        for (int x = 0; x < 12; x++) {
            if (Key == keyRemap[x][0].toInt()) {
                lcd.print(keyRemap[x][1]);
            }
        }
        delay(160);
    }
}
byte Read_Keypad(void)
{
    byte Count;
    byte Key_State = 0;

    for (Count = 1; Count <= 16; Count++)
    {
        digitalWrite(SCL_PIN, LOW);
        if (!digitalRead(SDO_PIN))
            Key_State = Count;
        digitalWrite(SCL_PIN, HIGH);
    }
    return Key_State;
}

Is there any way to optimize this code:

Absolutely, yes. Don't use String for this, you are seriously wasting memory. Instead you can use a struct:

struct keymap {
    uint8_t code;
    const __FlashStringHelper *value;
};

const struct keymap keyRemap[] = {
    { 1, F("1") },
    { 2, F("2") },
    { 3, F("3") },
    { 5, F("4") },
    { 6, F("5") },
    { 7, F("6") },
    { 9, F("7") },
    { 10, F("8") },
    { 11, F("9") },
    { 14, F("0") },
    { 13, F("Clear") },
    { 15, F("Enter") },
    { 0, 0 }
};

void loop() {
    int Key = Read_Keypad();

    if (Key != 0) {
        lcd.clear();
        lcd.setCursor(0, 0);

        for (int x = 0; keyRemap[x].code != 0; x++) {
            if (Key == keyRemap[x].code) {
                lcd.print(keyRemap[x].value);
            }
        }

        delay(160);
    }
}


(Arduino Uno) Is my code for a follow the sun project valid? We want the motor to stop when both photoresistors have the same amount of light int RlightPin=0;  //pin for right Photoresistor
int LlightPin=1;  //pin for left Photoresistor
int TranslateAnalogR=0;
int TranslateAnalogL= 1;
#include <Servo.h> //Servo library.
int pos=90; //Declare and initialize the variable pos.
int servoPin=9; //Servo connected to pin 9
int servoDelay=10; //Time motor waits before working again.
Servo myArms; //Servo object called myArms

void setup() {
Serial.begin(9600); //Start serial communication.
pinMode(7,OUTPUT);
pinMode(servoPin,OUTPUT);
myArms.attach(servoPin);

}

void loop() {

Serial.println(analogRead(RlightPin));   //Write the value of the right photoresistor to the serial monitor.
TranslateAnalogR=analogRead(RlightPin); //Read the right photoresistor value

Serial.println(analogRead(LlightPin));    //Write the value of the left photoresistor to the serial monitor.
TranslateAnalogL=analogRead(LlightPin);  //Read the left photoresistor value

if(TranslateAnalogR=TranslateAnalogL){        //If Photoresistor Value is above 355 the motor will stop
myArms.write(pos); // sets the servo position according to the scaled value
delay(servoDelay);// waits for it to get to the position

}

if(TranslateAnalogR=!TranslateAnalogL && TranslateAnalogR>TranslateAnalogL) { //If Photoreistor R is not equal to L and higher than L move until equal
for (pos=0; pos>=40; pos=pos+1)  {
  myArms.attach(servoPin);
  myArms.write(pos); //send servo to pos
  if(TranslateAnalogR=TranslateAnalogL){
  myArms.detach();}
}
}

if(TranslateAnalogL=!TranslateAnalogR && TranslateAnalogL>TranslateAnalogR){    //If Photoresistor L is not equal to R and higher than R move until equal
for (pos=0; pos>=40; pos=pos-1){
   myArms.attach(servoPin);
   myArms.write(pos); //send sevo to pos
   if(TranslateAnalogL=TranslateAnalogR){
   myArms.detach(); }

}
}

}

There are many issues with this code:

pinMode(7,OUTPUT);

What is this pin for? Why do you set it to OUTPUT and then never
actually output anything? If the pin is in use, you should declare a
constant for it, like

const int fooPin = 7;

and then use the constant instead of the bare number 7.

Serial.println(analogRead(RlightPin));   //Write the value of the right photoresistor to the serial monitor.
TranslateAnalogR=analogRead(RlightPin); //Read the right photoresistor value

analogRead() is a slow function, and it is quite inefficient to do the
analog to digital conversion twice. You can instead

TranslateAnalogR = analogRead(RlightPin);
Serial.println(TranslateAnalogR);

As a matter of style, I would remove the comments. Commenting code is
generally considered a good practice, as long as the comments tell
something non obvious, like giving the “big picture” or the rationale
for doing something in a particular way. Paraphrasing in English what
the code already says in C++ is useless.

Serial.println(analogRead(RlightPin));   //Write the value of the right photoresistor to the serial monitor.
//...
Serial.println(analogRead(LlightPin));    //Write the value of the left photoresistor to the serial monitor.

You won't know what value corresponds to the left and what value
corresponds to the right. I would instead do something like:

Serial.print("L: ");
Serial.print(TranslateAnalogL);
Serial.print(", R: ");
Serial.println(TranslateAnalogR);

Then:

if(TranslateAnalogR=TranslateAnalogL){        //If Photoresistor Value is above 355 the motor will stop

You mean ==.

if(TranslateAnalogR=!TranslateAnalogL && TranslateAnalogR>TranslateAnalogL) { //If Photoreistor R is not equal to L and higher than L move until equal

The first test is redundant. If R>L, then obviously R≠L.

    for (pos=0; pos>=40; pos=pos+1)  {
        myArms.attach(servoPin);
        myArms.write(pos); //send servo to pos
        if(TranslateAnalogR=TranslateAnalogL){
            myArms.detach();
        }
    }

This is a very contrived way of searching the optimum. Normally you
attach the servo once and keep it attached all the time. Then you adjust
the position until you see the same illumination on both LDRs. This way
you keep track of the correct position and you need not redo the whole
angle scan every time. Also, this will not work for three reasons:

You mean TranslateAnalogR==TranslateAnalogL rather than
TranslateAnalogR=TranslateAnalogL
TranslateAnalogR and TranslateAnalogL are not updated within the
loop, you need to explicitly perform an analog read.
The loop will run too fast for the servos to follow the requested
positions.

Later:

    for (pos=0; pos>=40; pos=pos-1){

The loop is backwards. You probably mean

    for (pos=40; pos>=0; pos=pos-1){

Here is my take at this, completely untested:

#include <Servo.h>

// Pinout.
const int PIN_LDR_R = 0;  // right photoresistor
const int PIN_LDR_L = 1;  // left photoresistor
const int PIN_SERVO = 9;  // servo

const int SERVO_DELAY = 20; // time motor waits before working again

int pos = 90; // servo position in degrees
Servo servo;  // servo object

void setup() {
    Serial.begin(9600);
    pinMode(PIN_SERVO, OUTPUT);
    servo.attach(PIN_SERVO);
}

void loop() {
    // Read and report light levels.
    int level_L = analogRead(PIN_LDR_L);
    int level_R = analogRead(PIN_LDR_R);
    Serial.print("L: ");
    Serial.print(level_L);
    Serial.print(", R: ");
    Serial.println(level_R);

    // Adjust the servo position.
    if (level_R > level_L && pos < 180)
        ++pos;
    if (level_R < level_L && pos > 0)
        --pos;

    // Update the servo.
    servo.write(pos);
    delay(SERVO_DELAY);
}

A few things worth noting:

Constants are qualified as const (it helps the compiler optimize and
catch bugs) and spelled in full caps (a common stylistic convention).
The servo position is adjusted step by step, one degree per loop
iteration. No need to perform a full scan every time.
The program does not do anything special when the light levels are
equal, because in that case there isn't actually much to do.
I increased the delay between servo updates to 20 ms, as
the serial communication alone can take close to 19 ms per
iteration.
You may want to add some hysteresis in order to avoid the servo
jitter when it has found the optimum.


What does the term "9g" in servo's rating mean? I frequently see 9g mentioned in servos. I searched the web but couldn't find any worthwhile answers. At first I thought it meant 9grams but the weight of the servo isn't 9 grams, so have to be something else.

According to Flite Test web site, the 9g reference is the weight without the wire lead. They measured one model at 8 grams rounded down. I suspect the weight also ignores the horn as well as the wire.

The article referenced on the web site calls the weight reference as a standard, which means that it more likely allows for heavier or lighter servos as long as the size of the servo matches.

If you purchase a servo for a model known to use a 9g servo, you know the hole you have to build for it to fit. If you purchase a 5g servo, it will be a different hole and you may have a 6 or 7 gram weight, but the servo fits as it should.


Best way to determine if a 5 gallon water jug is getting empty I have an espresso machine that gets its water from one of those 5 gallon blue water bottles (I would plumb it, but our water here is WAAAAY too hard).

If I ever accidentally let the bottle run out of water, the rotary pump in the espresso machine will be ruined, which would be a costly mistake.

I know that I can install some sort of magnetic float sensor inside the water bottle, but since I have to change it out once every few weeks, having another thing inside the bottle would make changing it out harder, and microbial contamination more likely.  The pump that pumps water out of the bottle forms a tight seal at the lid, and anything running under it or through it would compromise that seal.

Is there something I could use to detect if the water level is low from the outside of the bottle?  Like a laser sensor?

Using a Force Sensor to Measure a Quantity of Water

To satisfy your requirement of having the sensor on the exterior of the water container, I would recommend using a force sensor to weigh the bottle at set intervals. A force sensor, such as the FlexiForce A401, is a type of resistor that changes resistance in response to the amount of force applied. While not as accurate as a scale, it should provide enough accuracy (+-3% according to the datasheet) for the application described.

The basic procedure would be to hook up the force sensor to the Arduino and first measure the resistance with an empty bottle, then measure again with a full bottle. This will give you an idea of the force that your specific platform is actually applying to the sensor, and you can then fine tune the voltage (as per the datasheet) for your installation.

A basic tutorial using a similar force sensor with an Arduino can be found here.

Other Possibilities

Optical Liquid Level Sensors
Ultrasonic Level Monitoring
Thermistors and Heating Coils at various levels to Measure the Thermal Mass (i.e. water) near the Sensor


What is a flag in programming Arduino? I have seen many tutorials on programming an Arduino to control a HC-05 bluetooth module. In that I did not understand the term called 'flag'. What does that mean?

I've always used flag to indicate a boolean logic value. I would also suggest this is an archaic term.

Was going to come up with my own explanation but found the following at In C language, what does flag mean?:

  A 'flag' is a variable that is supposed to signalize something. Think
  about the word itself - flags are used in sending signals. In our
  world of programming a basic boolean flag can either be "up" or
  "down", either true or false.


Motor with sinusoidal motion I need to run a  motor to have a harmonic motion with specified amplitude and frequency ( harmonic motion mean that the angular position of the motor is a sine function of the time). I’m Looking to do a specified number of sinusoidal oscillations.
I don't know how to tell the motor that I want the speed to be a sine function of the time. Any ideas?
Also, I’m still beginning of the project?  Hence I’m pretty flexible to choose any motors (DC/servo/stepper/ brushless motor) or any controller but the system has to be precise.
If you guys know what controllers that allow that kind of motion, please let me know! Thank you :)

EDIT:
so what I'm trying to do is making rheometer which measures the rheological properties of a material. Basically, there are two measuring methods available: Rotational tests and oscillatory tests. With rotational measurements, the measuring bob turns in one direction. In an oscillatory test, the measuring bob "oscillates" around the axis.

what my focus is to with oscillatory tests with set sinusoidal oscillation.
The basic principle of an oscillatory rheometer is to induce a sinusoidal shear deformation in the sample and measure the resultant stress response; the time scale probed is determined by the frequency of oscillation, ω, of the shear deformation. In a typical experiment, the sample is placed between two plates, as shown in the below image While the top plate remains stationary, a motor rotates the bottom plate, thereby imposing a time-dependent strain γ(t)=γ ·sin(ωt) on the sample. Simultaneously, the time-dependent stress σ (t) is quantified by measuring the torque that the sample imposes on the top plate.

So to able to do above testing I need to run the motor with sinusoidal oscillation with exact angle.Hope you get it what im trying to say? does anyone know any  motor controllers that allow that kind of motion ? or any hints how do i wet my feet? cheers!!

Your best option would be:

To have a DC motor with a reduction box so that it spins at lower speeds (Lets say 300 rpm) and have an encoder to count the steps. Either put the encoder before the reduction box (here it can be used a low resolution encoder, like 16 positions) or after the reduction (here you would like a more precise one, such as those 1024 positions).
To have a Stepper motor, which will give a good angular control as long as it doesn't misses steps (if there is too much torque it will halt its movement, and you will lose count of the angle you have already displaced).

Now, to get the motor to move in a way that its angular position is of the form theta(t) = A*sin(ωt) you would have to write some code that moves the motor to each position you want. And the difficulty of it will depend a lot on the amplitude (A) and angular speed (ω) you require.

Obs: feel free to alter/add info here


Server checkbox not working properly I am trying to make an arduino alarm clock to which you can send alarm clock times over the web.
This is the HTML code

 <input type="checkbox" name="alarm1" id="alarm1">1</button>

It's sending the HTTP correctly but the rest of the code insists that the alarms are always on.

      if (_server.arg("alarm1") = "on") {
      alarm1 = true;
      Serial.println("Alarm 1 is set");
  }
  else {
      alarm1 = false;
      Serial.println("Alarm 1 is inactive");
  }

The alarm is always on because you are setting it to be always on.  You code should say:

 if (_server.arg("alarm1") == "on") {


Output pin low used to complete 12V LED circuit? I have a project that (in part) will drive 3 LEDs where the LED
anodes are at 12V.  The thought is to drive each LED by connecting
each cathode to a 650 ohm resistor, and connect that to an Arduino DIO pin which, when needed, is set to output LOW.  Arduino VIN = same 12V with
common ground.  Am I going to have an Arduino problem of any sort?

No, what you propose will not work. And it risks damaging your Arduino.

Normally you would include a single transistor which the Arduino uses to control the power through the LEDs. This removes the 12V from the Arduino and turns the output into an actual switch.

The problem is that the Arduino's GPIO isn't just a single transistor.  It is (amomgst other things):

Two complimentary transistors (that's the C in CMOS) for HIGH and LOW switches
ESD Diodes
Input buffer

By just adding the one transistor like this:

simulate this circuit – Schematic created using CircuitLab

the 12V is kept well away from the Arduino. Setting the output HIGH will turn on the transistor, allowing the current to flow to ground. Setting it LOW with turn it off, blocking the flow of current and switching the LEDs off.

Further: the Arduino's GPIO has a maximum sustained current of 25mA. Ideally you don't want to even come anywhere near this. By adding the transistor it acts as a buffer and allows you to deal with much higher currents - and hence more, and brighter, LEDs.

Incidentally, R1 in that schematic is there solely to keep the transistor off when the Arduino is not actively driving the output - e.g., when it's either unpowered or is running the bootloader - or you happen to have the GPIO in INPUT mode (as it defaults to).


using an ESP8266 shield on my Arduino Uno R3 with an unofficial library I'm using the following Makefile: https://github.com/sudar/Arduino-Makefile
It works very well and I was able to get my LED to blink.

Now I bought a WiFi Shield which is NOT supported officially by the Arduino WiFi library.
It is the following one I bought: ESP8266 ESP-12E CC3000 UART WIFI Wireless Shield Board Modul für Arduino UNO R3 - you can find this on ebay: http://www.ebay.de/itm/262525969091?_trksid=p2060353.m2749.l2649&ssPageName=STRK%3AMEBIDX%3AIT

What I now am about to do is to include the open source library for the ESP8266 which you can find here: https://github.com/esp8266/Arduino#documentation

Now when I try to upload my sketch it tells me that certain dependencies are not resolved. Like this one here #include <functional> which I was not able to include manually. My main problem here is that the github page of the ESP8266 library isn't providing enough information for me how I can get the working lib to use in my sketch.
I need to know how I can get this library to work in my sketch!

That is not a library for the Arduino. That is a core for programming the ESP8266 directly as if it were an Arduino itself.


Can someone help me decipher the code for the arduino? I am totally lost The code is as follows:

void loop(){

    light = analogRead(5);
    Serial.println(light);
    analogWrite(3,light/4);

}

Not really a physics question, but I will answer anyway.

loop() is the standard Arduino function which contains code that the microprocessor runs repeatedly (as opposed to code in setup() which is only run once).

light = analogRead(5); takes an analogue voltage reading from pin 5, encodes it as an integer value (either 10 or 12 bits depending on the Arduino model) and stores the result in the variable light.

Serial.println(light); outputs the value of the variable light to the Arduino's serial port. This is a standard way of outputting data from the Arduino so that it can be displayed on a connected computer.

analogWrite(3, light/4); outputs the value of light/4 as a phase-width modulated (PWM) signal to pin 3. Although Arduino output pins are either on (5 volts) or off (ground) at any point in time, PWM signals allow the Arduino to switch an output pin on and off rapidly so that the average voltage seen on that pin is an intermediate value. The duty cycle of the PWM signal which determines the average voltage on the pin is encoded as an 8 bit integer, so light is probably divided by 4 here to convert it from 10 bits to 8 bits.

So the Arduino will repeatedly read an input voltage from pin 5, output an integer representing this voltage to the serial port, and create a PWM signal on pin 3 that has an average voltage the same as that of the input voltage.

See the Arduino language reference page for more information.


I'm looking for a way to serially communicate with a multi mesh Arduino slave network I have one PC running Visual Studio and a program that will be sending commands to Arduinos via serial COM Ports. So, in 11 Nano MCUs, I will have motor drivers L293D/L298N ICs, while in other Nanos I will have sensors.

What I would like to do is have a program in Visual Studio which sends commands via serial to actuate motors to each and every MCU on board. This is a robotic application and everything I mentioned above will be enclosed within the Humanoid.

Here are some examples of what I'm thinking of doing:

char data = Serial.read();
if (data == 'A')
{
  digitalWrite(13, HIGH);
}

Or something like this:

servodata = Serial.read();
if (servodata == '1') // Single Quote! This is a character.
{
  SERVO.write(pos);
}

As you can see, Arduinos will have something like this running and waiting for Visual Studio to send commands via serial to one or multiple MCUs simultaneously. I'm thinking 30 char dividing/spiting that number across each Rx Arduino.

It's not obvious what the exact query is but answering the subject line question:

You can easily multidrop connect multiple serial / RS232 COM ports by having all slave RX inputs and the master TX output on one line, and all slave TX outputs connected by an OR network to a single line to the master's RX input.   The master 'talks' to all slaves at once. Each slave talks to only the master. Only one slave can usefully talk at once. Message destination assignment and slave-talking arbitration is carried out in software.

As shown below, the OR network at each slave can be as simple as a diode with cathode (bar side) to TX line and anode to common line to master RX.  A single pullup resistor (or an internal pullup in the master on the RX line) pulls the line high when all slave TX lines are high.

This diagram shows how simple multidrop communications can be.
NB - As shown the diodes polarity is for true RS232 with logical 1 = low = negative.
When connecting directly between UART TTL lvel (5V/0V) outputs reverse the diodes.

Also, add a pullup from +5V to the Blue RX line to the master - 10k to 5V is probably OK.

From here - Multidrop network for RS232.

When a slave TX pin is high its diode is "blocked" and it does not affect the common slave to master level. When any slave TX line goes low the common line is pulled low via its diode and the master sees the low. Normal RS232 COMs can occur between slave and master.

When the master sends all slaves see the transmission at once. A basic protocol must be established to allow messages to be handled by the intended recipient. This could consist of, e.g. sending an address word + command word or words. You can have a single slave act on a message or all slaves or a sunset, based on your addressing system.

The slave to master direction allows only one slave to send at one and you must ensure either that only one slave ever sends at a time and/or that collisions are able to be resolved.

Despite the obvious limitations of such a system it can work very well and is cheap and simple to implement. If there are many slaves the loadings should be checked so that e.g. the master TX is able to drive all slave RXs at once. As the circuit is unidirectional it is easy to add a basic buffer.


Programming Arduino Uno R3 to trigger a relay once every 24 hours I programmed Arduino UNO R3 to trigger a relay once every 24 hours from the moment it is powered on
I calculated milliseconds and used the function delay()
24 hours * 60 minutes each hour * 60 second every minute * 1000 milliseconds every second
so i used :
delay(86400000)

86 million and 400 thousands milliseconds
and currently i'm still testing it...
Will this work?
If not Is there a better built-in function/library or even external library to do it?
the relay trigger doesn't have to be very accurate at the very exact time each day
I don't need it to be very accurate, It can shift few minutes every few months or so, thats okay with me
But how about after few months or years of use ?
Will it shift the timing much ?
I read somewhere about using millis() function
and others use RTC (Real Time Clock) module
I don't want to use RTC module
Looking for a programmatical solution...
OR if my previous method using the delay() will work for such a very high number of millisecond ?
Thank you

Yes, the delay() will work, as will other methods based on the millis() counter. However, delay() will make it impossible to do something else in the meantime.
Look up Blink without delay for an example of how to accomplish such a delay while being able to do other things in your code while waiting.
Casting
When dealing with large numbers such as your 24-hour delay, make sure to explicitly cast those numbers as unsigned long, or expressing them with the "UL" extension (like for example 86400000UL). This explicitly tells C++ to expect an "unsigned long" (which in Arduino Uno terms is a 32-bit unsigned number).
In your case (with such an obviously large number), the compiler will automatically choose the right type. In other cases (for example, if you change the expression to 24*60*60*1000), the compiler will not automatically generate an unsigned long and you need to force it by changing the first part of the expression to an unsigned long: 24UL*60*60*1000 or, alternatively (unsigned long) 24*60*60*1000.
Accuracy
The accuracy of the timing will be dependent on the type of oscillator on your particular Arduino board. Many Arduinos or their clones use a Ceramic Oscillator that generally have an accuracy of about 0.1 to 0.5%, meaning a possible deviation of 43 seconds per day and as such maybe too inaccurate for your purposes. If your Arduino has a Crystal oscillator, it will be much more accurate (to something like 150ppm, meaning a maximum deviation of about 1 second per day under normal conditions).


How to read RC receiver channels without using pulsein() command with arduino I am building a quad-copter, the problem is of stability and for better stability lesser sampling time is required. For lesser sampling time I need to have faster loop() function. But the Pulsein() command takes very large time which in turn expands the sampling time. Is there any method to read the rc channels in background and read them from an integer.

The keyword you are looking for here is interrupt.  What is a pulse but a signal that goes from low to high followed by going from high to low, with some period of time between them?

Instead of sitting there waiting for the pulse to arrive then measuring how long it is, which is essentially what pulseIn() does, you need to attach the signal to an interrupt pin.  Then you write an interrupt routine that triggers when the signal changes from one level to another which looks to see what the level actually is.

If the signal has risen from low to high then you record the time it happened.  If the signal has fallen from high to low then you look what the time is, and subtract the time you remembered from when the signal rose.  That difference is then the width of the pulse, which you can store in an integer to read in your main loop.

If you have a number of signals you want to monitor you might want to look into using the pin change interrupt which allows you to use any pin as an interrupt source.


What does the line "while (! Serial);" do in an Arduino program? I'm new to Arduino, and I am trying a couple of tutorials. What does this line do in a program?

while (! Serial);

On boards with an FT232 chip or other USB->Serial bridge chip (Uno, Mega, etc) it does absolutely nothing.

On boards with a direct USB connection, such as the Leonardo or the Yùn it waits for an active serial connection to be established by the PC (i.e., for the serial port to be opened by a piece of software).

When you open the serial port of a board like the Uno or Mega the whole board usually resets*, so opening the serial port allows you to see the first bits of the serial data.  On the Leonardo etc it doesn't reset when you open the serial, so any serial output during the setup() function would be missed.  Adding that line makes the board pause until you open the serial port, so you get to see that initial bit of data.

*) Unless you specifically write some software that doesn't assert DTR when you open the port


How can I get a unique ID for all my Arduino boards? Once you have uploaded a sketch to one of your Arduino boards, it is hard to know exactly what source code led to that sketch.

Indeed, you may change the source code of your sketch on your PC without updating it (in binary format) to your board.

I had the idea of setting up a kind of "sketch repository" that would be populated as soon as I upload a sketch to one of my boards. Then I could retrieve, later on, the source code for a sketch running on any of my boards.

For such a repository, I would first need to have an "index" that would enable me to know which board the sketch source code is linked to.

Typically, such an index should be unique for every single arduino board.

Hence my question: how can I get a unique ID for an Arduino board?

Edit:

This is my current list of boards (the miniumum list to be supported by a single unique ID approach):

UNO R3
Mega 2560
Yun
Arduino Robot (that must be 2 Leonardo equivalent boards)

In the future, I may also build my own boards (Uno equivalent but barebones, without FTDI), hence if an approach also supports these that would be better.

There are a number of techniques you could use here to get a unique ID.

FTDI chips have a unique serial number programmed onto them. This can only be accessed from the PC side of the connection as far as I am aware.
Some of the chips with built in USB (e.g. ATmega8U2/16U2/32U2) have a unique ID in the signature data, normally used for USB. Can easily be accessed from both sides of the connection. This includes the ATmega16U2 that is used as the USB->Serial bridge Arduino Uno R3.
Some of the chips with built in USB but no unique ID in the signature will still have a unique ID programmed into the USB stack (e.g. LUFA) used for the bootloader or DFU (Device Firmware Upgrade).
There are many chips with globally unique serial IDs in them e.g. the Microchip 11AA02E48, all of the Dallas 1-Wire sensors (including the common DS18B20 temperature sensor), and other serial EEPROMS. I've used these in production hardware that must have a unique MAC address.
You could modify the standard Optiboot bootloader (or whichever boat loader you use) so that it can hold and respond with a unique ID.

The problem with these is that there is no option except 5 that will work across all boards.

If your solution is going to be a generic one, I would suggest that using a USB ID is not the way forwards. I have ~30 Arduino-based boards, and only 5 of them have built in USB hardware. All the rest of them need an external FTDI cable to be programmed. This means they would all have the same ID.


Do Loop query not stopping I am new to Arduino programming and I would like to ask a question.

Firstly apologies if this has been answered before and I understand if it gets locked if this has been answered elsewhere.

I am trying to get three LED's (red, amber, green) to loop 5 times (in a do loop).

for this I have created a integer variable (x) and initialised the variable to 0.

I then increase x by 1 each time.

However I cannot get them to stop looping when x is greater than 5. The program does work as expected for everything else (green LED lit, wait 1 sec, Yellow LED lit, wait 1 sec, red LED lit and then loop).

   //set LED pins
int greenPin = 13;
int yellowPin = 12;
int redPin = 11;

void setup()
{
  pinMode(greenPin, OUTPUT);      // sets the digital pin as output
  pinMode(yellowPin, OUTPUT);
  pinMode(redPin, OUTPUT);
}

void loop(){
int x = 0;

 do {
  digitalWrite(greenPin, HIGH);   // sets the LED on
  delay(1000);                  // waits for a second
  digitalWrite(greenPin, LOW);
  digitalWrite(yellowPin, HIGH);    // sets the LED off
  delay(1000);
  digitalWrite(yellowPin, LOW);// waits for a second
  digitalWrite(redPin, HIGH);    // sets the LED off
  delay(1000);
  digitalWrite(redPin, LOW);
 }
   while(x<=5); {
    x = x + 1;
   }
}

Chrisl already gave the clue.

However, to add a comment with a code example I use the answer box.

In C you have more or less two kind of loops:

for
do / while

The first one is when you know beforehand how many iterations you have, the second when it depends on external input (e.g. when you expect a value acquired from within the loop).

In your case, you can better use the for loop, so you get:

for (x = 0; x < 6; x++)
{
   ...
}

What this does i:

Initializes x to 0 (first part of the for statement)
It checks the condition x < 5' (second part of theforstatement). If false, it continues with the first statement after thefor` body (after the } bracket).
It runs the body of the loop (inside the brackets)
It increases x (third part of the for statement)
It continues with 2

Also it is quite common for the condition to include the start element of the ragne (x = 0), but exclude the end element of the range (x < 6), thus it runs the last time with x == 5.


Form a signal from an array of bits I need to reproduce with a digital pin of an Arduino such a key in the form of a sequence of 1's and 0's, where a one takes 2 ms high and 2 ms low, and a zero takes 1 ms high and 1 ms low.

  int key = 0b101100001111;

void setup()
{
  pinMode(13, OUTPUT);
}

void loop()
{
  for (int n = 0; n < 12; n++)
  {
    if (bitRead(key, n) == 1) //execute if bit value == 1
    {
      sendSignal(2000);
    }

    else //execute if bit value == 0
    {
      sendSignal(1000);
    }
  }
}

void sendSignal(int duration)
{
  digitalWrite(13, HIGH);
  delayMicroseconds(duration);
  digitalWrite(13, LOW);
  delayMicroseconds(duration);
}

This sketch really works! I figured out what my problem is: I actually need a longer key (64 bits). I am using long type: long key = 0b1000011110001101111100011111001010110001101101111011011100110100; but long only allows 32 bits. What do you recommend to do? Maybe you need to arrange it as an array? I think you can make it easier somehow. thank you

You should make
byte key = 0b101100001111;

global, i.e. put it BEFORE the setup function and not within it.
Also, a byte only can contain 8 bits, you need 12, so make it an int (thanks to ocrdu, see comment below):
int key = 0b101100001111;

If you need more bits, you can use uint32_t or uint64_t, and count further than the current 12.
Now key is a local variable which is removed after exiting the setup function.
I'm not sure where 'key' comes from in:
switch (bitRead(key, n)) {

Do you get a compiler error, or did you ALSO define a global variable named key ?
Anyway, if you make key global it will fix either way.
A few other remarks:

Try to align your parenthesis, like the 3 }'s at the end, indent them properly, this makes your code much more readable
Instead of the switch/case, you could use an if statement in this case, as the re are only (and always) two possible values (0 and 1):

Thus:
 if(bitRead(key, n) == 0)
 {
     ...
 }
 else // 1
 {
     ...
 }

Try also comments to write in English instead of Greek, you never know when your comments will be read by non Greek readers (like now).

You can make the following fragment shorter and less duplicated:

Original:
digitalWrite(13, HIGH);
delayMicroseconds(1000);
digitalWrite(13, LOW);
delayMicroseconds(1000);

If you wrap this in a function:
void sendSignal(int duration)
{
    digitalWrite(13, HIGH);
    delayMicroseconds(duration);
    digitalWrite(13, LOW);
    delayMicroseconds(duration);
}

Then you can write a 1 by calling:
sendSignal(2000);

and a 0 by calling:
sendSignal(1000);


Arduino IDE doesn't pick up serial ports I am fairly new to Arduinos and I recently bought a nodeMCU Amica esp2866 for this tutorial. I have my board connected to my MacBook Air (10.14.5 with Mojave) and only the "/dev/cu.Bluetooth-Incoming-Port" is the only one that shows up.

I am using a basic USB cord to connect the board to my MacBook and I know the cable isn't broken because I have used it in the recent past. If anyone knows how to fix this problem or has run into this problem in the past, please let me know. Let me know if you'd like anymore information. Thank you!

The MAC / Arduino install instructions appear to be here.

If your Arduino (possibly a NodeMCU 1.0 version board) is using the CP210x chip set there appears to be a download page here.

If your Arduino (possibly a NodeMCU 0.9 version board) is using the ch340g, ch34g or ch34x chip set there appears to be an effort to create a Mac OS X driver here.

The install instructions from that github page are as follows:

  Installation

Unplug any CH34* devices.
Unload the old drivers if running:
    sudo kextunload /Library/Extensions/usbserial.kext
    sudo kextunload /System/Library/Extensions/usb.kext
Remove the old driver by issuing one of the following commands (depending on your installation):
    sudo rm -rf /System/Library/Extensions/usb.kext
    sudo rm -rf /Library/Extensions/usbserial.kext
Double-click on the CH34x_Install_V1.5.pkg file and install (no need to reboot)
Instead of rebooting, you can force quit Installer after it completes.
Load the new driver:
    sudo kextload /Library/Extensions/usbserial.kext
Plug in your device. It should now be listed under the /dev directory. Examples:
    /dev/cu.wchusbserial1410
    /dev/tty.wchusbserial14210 (driver version 1.5)


Servos jitter when powered by power module I need 48 sg90 servos to move to a specific position each minute. Now I am using two arduino mega boards to power everything through 6 bread boards but it seems I need more power because some servos are ticking and are delayed. I cant get the external power supply to work independently of the computer. Once I unplug from my computer the servos jitter. Any help would be greatly appreciated.

Most servos use an analog signal (width of a pulse) for positioning.  Any perturbation in that signal will cause unexpected behavior.  Activating 48 servos simultaneously will likely indirectly or directly affect the analog signal.

The unexpected behavior might be mitigated through changes in software or hardware.  These mitigation efforts may include:

Staggering the servo changes so that only 1 servo moves at a time.
Perhaps less effective but worth trying, staggering the servo changes so only 1 servo starts moving at a time.  In this scenario more than 1 servos may be moving at a time.
Using a power supply which maintains the expected voltage even during events such as all servos starting simultaneously.

These are only 3 options to consider.  Many more exist but may not be pertinent to your situation.  More information is needed.


Trying to map a room with Arduino controlled bot What you see above is a map of my room. The boxes in black are obstacles and the box in red is my bot.

Now I want my bot to go around the room, avoiding all obstacles, but at the same time, covering the entire floor. Think of it like the robot is painting the floor and it has to paint the entire floor avoiding all obstacles.

Now my first approach was to put 3 HC-SR ultrasonic sensors on 3 sides and listen to them in a sequence, deciding which path is best and then going there. But this method leaves out quite a lot of floor area uncovered.

So how can I cover the entire floor area here?
 Presently I am working with Arduino UNO and HC-SR04 but wouldn't hesitate to throw my Pi3 or a few more sensors in there...-

This is actually quite a complex thing to achieve. I'll give some suggestions, though this is not something I have attempted (yet).

The main thing to do is divide the room up into a grid. The resolution you choose (X and Y dimensions) depends on how small your robot is, how big the room is, and how much memory your have available (on an Uno that's not much at all).

The second thing you need to do is work out a way of determining exactly where in the room you are. That could be done by trying to get as close to the bottom-left corner as possible before starting to map.

Now you can work from square to square (you could do with some encoders to know how far you have driven, and a magnetometer so you know which direction you are facing) using whatever method you like to decide which way to go, and in each square you look to see which of the squares around you are accessible. From that you can work out which way you can go from that square.

As you go you maintain a map in memory of all the squares you have been to, and the squares that you cannot get to. Note that it may not be enough to say "You can't get to square 4,3" - instead you may to keep a more detailed list (depending on what your obstacles are). "You can't get to square 4,3 from square 4,2, nor 3,3, but you can get to it from square 5,3" for example (e.g., a thin obstacle that only blocks entry to that square from certain sides).

Since your sensors cover longer ranges than just one square (unless you have big squares) you can work out how far away an obstacle is, and mark the square it's in before you even get close to it. The square immediately preceding it on a path between it and you would be the "you can't get there from here" square.

Now you can work out paths and routes to get to the squares you need to so you can cover all the available floor.


How do I upload the sensor data from arduino into a database? I have just connected a Libelium shield to connect many sensors to Arduino UNO, that measure water ph level, temperature,...etc. I really couldn't figure out how do I upload the sensor data into a database(MySQL). I have the code for database connectivity, but still couldn't figure out how(Querying) to upload the sensor data into the database.

The main problem here is how do I make the arduino recognize the sensor data to upload it into database or send to to another Arduino or Raspberry pi through XBee.

Code for database connectivity:

void sendData(){

          Serial.println("Connecting...");
          if (my_conn.mysql_connect(server_addr, 3306, user, password)){
            delay(500);
            Serial.println("Starting SQL!");
            Serial.println(INSERT_SQL);
            my_conn.cmd_query(INSERT_SQL);
            Serial.println("Query Success!");
            my_conn.disconnect();
            Serial.println("\n");
          }
          else {
            Serial.println("Connection failed!");
          }
}

First you have to create the table in your MySQL database, like:

CREATE TABLE IF NOT EXISTS `table_log` (
  `log_id` int(11) NOT NULL AUTO_INCREMENT,
  `log_date` date NOT NULL,
  `log_time` time NOT NULL,
  `log_t1` float NOT NULL,
  `log_t2` float NOT NULL,
  `log_t3` float NOT NULL,
  `log_t4` float NOT NULL,
  `log_vbatt` float NOT NULL,
  PRIMARY KEY (`log_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=1;

You can execute it in your phpmyadmin page (or create the table manually there). Above we have columns for auto-increment id ('log_id' - necessary), date & time, 4 temperature values and voltage value (modify these according your requirements).

Than the query to create a new record would be like this:

INSERT INTO `table_log` (`log_id`, `log_date`, `log_time`, `log_t1`, `log_t2`, `log_t3`, `log_t4`, `log_vbatt`) VALUES
    (0, '2016-03-04', '01:53:30', 1.0, 2.0, 3.0, 4.0, 3.0);

You need to create this string dynamically (with real values) and use instead of INSERT_SQL.


Creating a library of C++ classes for Arduino; How to #include "Arduino.h", "WProgram.h"? I've written 6 C++ classes on the CLion IDE to be used on Arduino. One of these classes uses a C++ library called "Adafruit_PWMServoDriver.cpp" provided by Adafruit to use the PWM driver they sell. I'm trying to test my code in a main.cpp, but upon building my code, I noticed that "Adafruit_PWMServoDriver.cpp" has the following code:

#if ARDUINO >= 100
 #include "Arduino.h"
#else
 #include "WProgram.h"
#endif

Naturally, I copied Arduino.h from the Arduino installation folder to my C++ project header directory. But for reasons I don't know, ARDUINO is apparently not greater than or equal to 100, so it attempts to include "WProgram.h." Because I cannot find this header file, I changed my code to only attempt to include Arduino.h.

#if ARDUINO >= 100
 #include "Arduino.h"
#else
 #include "Arduino.h"
#endif

However, Arduino.h itself includes several header files, and I am not sure where I can find all the find them, or if it is even necessary to try to do so. I need to get my test code running, so I don't want to directly test it in the Arduino IDE yet. What can I do to overcome #include Arduino.h and #include WProgram.h?

The libraries from Adafruit and elsewhere assume you are using the Arduino IDE. If you choose not to use that you will have difficulties compiling your own code. The header files you ask about are in the IDE download. You can always grab a copy of that and put the appropriate .h files into your "include" search path.

  However, in my io.h file, there is a long list of #if defined (AVR_various_names).

Well, do a test compile using the Arduino IDE, using "verbose compiling" and see what defines are generated for your particular board (which you haven't mentioned). There won't be that many of them. Then you can put that on the build commands for your IDE.

  Or can I avoid all this and somehow create C++ classes independently?

You can create C++ classes inside the Arduino IDE. I don't see how this relates to your other issues.

The Arduino IDE basically generates build commands for avr-g++ - it isn't some horrible beast you should avoid using.


How to use this Arduino code to control multiple different LEDs? I am making an Android-controlled LED system over Bluetooth but I need to use 4 LEDs. I have done Android app but I am not able to figure out this Arduino code. Can some please help me get this done?

char command;
String string;
boolean ledon = false;
#define led 5

void setup() {
  Serial.begin(9600);
  pinMode(led, OUTPUT);
}

void loop() {
  if (Serial.available() > 0) {
    string = "";
  }

  while(Serial.available() > 0) {
    command = ((byte)Serial.read());
    if(command == ':') {
      break;
    } else {
      string += command;
    }
    delay(1);
  }

  if(string == "TO") {
    ledOn();
    ledon = true;
  }

  if(string =="TF") {
    ledOff();
    ledon = false;
    Serial.println(string);
  }

  if ((string.toInt()>=0)&&(string.toInt()<=255)) {
    if (ledon==true) {
      analogWrite(led, string.toInt());
      Serial.println(string);
      delay(10);
    }
  }
}

void ledOn() {
  analogWrite(led, 255);
  delay(10);
}

void ledOff() {
  analogWrite(led, 0);
  delay(10);
}

Its better if you use SoftwareSerial for Bluetooth, so the native serial port can be used to debugging. But in case you doesn't need them:

uint8_t led[4] = {5,6,7,8}; // pin for LED 1,2,3,4
char command1,command2;
String string;
  void setup()
  {
    Serial.begin(9600);
    for (int i=0; i<4; i++)
        pinMode(led[i], OUTPUT); //set all LED pin as OUTPUT
  }

  void loop()
  {
    if (Serial.available() > 1) //run if 1 bit or more data received
    {
    string = "";
        command1 = Serial.read();
        command2 = Serial.read();
        switchled(command1-'0',command2-'0');
    string = command1+command2;
    }
    delay(1);
  }
void switchled(char pinLED,char statusLED)
{
    if (statusLED == 0 || statusLED == 1)
    digitalWrite(led[pinLED-1],statusLED);
    else
    digitalWrite(led[pinLED-1],!digitalRead(led[pinLED-1]));

    Serial.print("LED ");
    Serial.print(pinLED);
    Serial.print(" = ");
    Serial.print(digitalRead(pinLED));
}

The code reads 2 byte of data, so if your phone sent "11" the 1st led will turned on, and "10" will turn the 1st led off. The first digit is the LED index (1/2/3/4) and the second digit is the LED state (0/1), other than that, the LED on selected index will be toggled;


UNO's digital pin continue to read 1 for a while I'm doing some tests and I notice a bad things with digitals pins. I have a wire that sends 1 signals. If i connect it to a reading pin, I read 1 - and it's ok. But if i disconnect it, for 5-6 seconds Arduino continues to read 1 instead of 0! How can I stabilize it more quickly?

Digital inputs should either be low or high. In this image acceptable input voltages on the left represent common TTL voltages based on a 0 to 5 volt range:

It is bad practice to leave a digital input floating.  A floating or disconnected input implies the voltage is unknown.  I suspect in your case a small amount of input capacitance held a charge for several seconds.  Once leaked off the input appeared to change from 1 to 0.  Even though you know what might be happening, you should not depend on it as it is unreliable behavior.

If connecting a SPST switch use a pull up (or pull down) resistor to pull the input pin to the opposite voltage the switch is pulling.  In this image the switch is connected to ground so the resistor is connected to positive voltage as a pull up:

The fist image comes from this Logic Level tutorial.


How to use -F option while Burn bootloader for ATtiny 85 using Arduino IDE I'm very new to Arduino. I tried programming Attiny 85 module using Arduino as ISP. It worked fine few times. after that i'm getting below error.

Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.

I understand that i can override this step using -F option. But really cannot figure out how to use -F option in Arduino IDE. Please Help!

For what I know there is no easy way to pass custom options to avrdude via the Arduino IDE, but Sloeber (to which I'm a contributor) does.

Beware though, the -F option of avrdude command doesn't solve the problem, just forces to skip the device signature verification, but if your Attiny is returning such signature something else is wrong and you'll end up with a failed firmware upload anyway.

If the device was working and suddenly stopped it's more than probably a wiring issue, as already suggested in the comments. The second most probable cause, in my experience, would be a hardware issue: you might have accumulated some static charge and then touched the Attiny or any wire connected to it, destroying one of the ISP pins...

My bet is on the former: my experience with the latter is you get changing signatures in the form of 0xFFFF00, 0x0000FF and 0xFFFFFF but, luckily for me, this didn't occur so often to accumulate a true knowledge.


Using an Ethernet Shield and a tlc5940 together I have am using an Arduino Uno R2 and TLC5940 to control a bunch of RGB LEDs. I want to add an Ethernet Shield R3 so that I can control the LEDs over a web-interface. However, the ethernet shield and TLC5940 use many of the same pins. Can I use them together? How?

When using multiple SPI devices the normal way to have them share a bus is to assign them distinct slave select lines. The problem here is that although the '5940 libraries use SPI to send data to it, the '5940 is not actually a proper SPI device and so lacks any sort of slave select line.

All is not lost, however. Since the '5940 responds only to SCLK (and GSCLK of course, but you should be running that one separately) all you need to do is inhibit it while nSS for the Ethernet module is active. This can be done with just a little bit of external circuitry. Since nSS must be high in order for the Ethernet module to be inactive, we can AND SCK with nSS to derive SCLK from it.

Using a 74HC08 for this would work, although it leaves 3 of the gates unused. A 74HC02 will let you do it with no wasted gates, but with a slightly higher propagation delay.

And of course, the requirement to clock in the grayscale data before the grayscale cycle completes is still there; properly interleaving this with the Ethernet communications is left as an exercise for the reader.


Is it better to use Vraw or Vcc on Mini Pro? I have 12V and 5V power available. Is it better to feed the 5V through the Vcc pin or either the 12V or 5V through the Vraw pin?

Use the 5V connected to the Vcc pin.

If you use the Vraw pin, the voltage goes through a voltage regulator. This voltage regulator will convert the higher voltage down to 5V by converting the extra volts to heat. So in case of using 12V you'd be throwing away around 60% of the power. Which is both wasteful, and will heat up the regulator quite a bit (depending on the load).


how to make an led turn on when something gets close to an ultrasonic sensor Hey I just started using arduino and so far can't get any help with how to write a code for an led to turn on when someone gets in range of a three pin ultrasonic sensor, and off when they are out of a specific range.

Any help?

Try with this and check that at least you can reproduce the desired effect:
http://www.arduino.cc/en/Tutorial/Ping?from=Tutorial.UltrasoundSensor

Then you can refer to this for the part related to driving the LED:
http://www.arduino.cc/en/Tutorial/Blink?from=Tutorial.BlinkingLED

Since the ultra sound demo already calculates the distance, you can do the test on that to decide when to turn ON/OFF the LED.


digitalwrite() HIGH for arduino How too know whether digitalwrite(HIGH, pin_number) sets the voltage to 5 volts or 3.3 volts. I am yet to purchase arduino uno. I want digital pin voltage to be 5 volts. I am aware that thereis a pin already have 5 volts but I want to know only about the voltage output at digital pins.
Sorry if question is too silly. I am not very knowledgable in Electronics.

Different boards operate internally at different voltages. This is dictated by the main chip on the board.  That main internal operating voltage is also the voltage at which the IO pins operate.
Most "old" Arduino boards operate at 5V.  This includes, but is not limited to:

Arduino UNO
Arduino Mini
Arduino Leonardo

Newer more powerful boards, many made by other companies, operate at 3.3V. Again, this includes such boards as:

Arduino DUE
Arduino MKR1000
Teensy boards (v3.0+)
chipKIT boards
ESP8266 & ESP32 boards

Some boards come in variants that give either voltage - the most notable being the Pro Mini boards from Sparkfun.  These come in both 5V and 3.3V variants and it is important to pick the right board for your needs.
In general, though:

If it's 8-bit and runs on an ATMega chip it's likely 5V unless otherwise stated
All 32-bit boards will be 3.3V unless otherwise stated.


STM32 and NRF send & receive This is my send and receive code in STM32 (blue board).
But i can't send and receive data . why?
I did use Enrf24.h .
Enrf24 link: https://github.com/spirilis/Enrf24
send code is:

#include <SPI.h>
#include <Enrf24.h>
#include <nRF24L01.h>
#include <string.h>
#define ce_nrf PB12
#define csn_nrf PB13
#define irq_nrf PA0
Enrf24 radio(ce_nrf, csn_nrf, irq_nrf);  // P2.0=CE, P2.1=CSN, P2.2=IRQ
const uint8_t txaddr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0x01 };
void setup() {
  Serial.begin(9600);
  SPI.begin();
  SPI.setDataMode(SPI_MODE0);
  SPI.setBitOrder(MSBFIRST);
  radio.begin();  // Defaults 1Mbps, channel 0, max TX power
  radio.setTXaddress((void*)txaddr);
}

void loop() {
  Serial.print("Sending packet: ");
  radio.print("OONN");
  radio.flush();  // Force transmit (don't wait for any more data)
  delay(1000);
  Serial.print("Sending packet: ");
  radio.print("OOFF");
  radio.flush();
  delay(1000);
}

receive code is:

#include <SPI.h>
#include <Enrf24.h>
#include <nRF24L01.h>
#define ce_nrf PB12
#define csn_nrf PB13
#define irq_nrf PA0
Enrf24 radio(ce_nrf, csn_nrf, irq_nrf);  // P2.0=CE, P2.1=CSN, P2.2=IRQ
const uint8_t rxaddr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0x01 };
const char *str_on = "ON";
const char *str_off = "OFF";
void dump_radio_status_to_serialport(uint8_t);
void setup() {
  Serial.begin(9600);
  SPI.begin();
  SPI.setDataMode(SPI_MODE0);
  SPI.setBitOrder(MSBFIRST);
  radio.begin();  // Defaults 1Mbps, channel 0, max TX power
  radio.setRXaddress((void*)rxaddr);
  radio.enableRX();  // Start listening
}

void loop() {
  char inbuf[33];
  while (!radio.available(true));
  if (radio.read(inbuf)) {
    Serial.print("Received packet: ");
    Serial.println(inbuf);
  }
}

this image can help :

You did not say which library you are using, but based on the #includes, I am assuming http://maniacbug.github.io/RF24

This line in your receiver code:

  while (!radio.available(true));

does not make sense. You are passing true to the radio.available() function, but the function does not care about a parameter.

You probably mean something like:

while (!radio.available());

When you pass in a variable, you are calling a variant of the function that expects a pipe number to be given, and true is defined as 1. Your transmitter, however, is not sending on pipe number 1.


Is it possible to package a sketch with dependent libraries for cross-platform compatibility? I have a complex sketch that I spent many weeks working on, which I am backing up frequently because I'm afraid of losing any of my progress.

I'm wondering if it's common practice to make a self-contained package of the sketch and all its dependencies, so that it can be moved easily to another OS if necessary. My concern is that if my OS crashes and I have to reinstall everything or move to another OS, I might run into library and dependency errors, especially with the libraries that I altered/customized. I need my sketch to be able to compile as quickly as possible on whatever OS I end up using, since it's a home-automation sketch that controls dozens of things around me.

Is this a valid concern? And if so, what are some preferred ways to make a sketch become "self-contained", so that everything necessary is included? Is there some kind of a better version-control system for Arduino sketches that an amateur programmer might not be aware of?

I would suggest switching to UECIDE instead of the Arduino IDE. (Yes, shameless plug, it's my IDE).

UECIDE has a facility that I dubbed "localizing" a library whereby it copies it into a libraries folder within the sketch folder itself, and that copy of the library is used in preference to any other library named the same in the system.

That means that a sketch and its libraries then become completely self contained in one folder, and it's perfectly possible to have different versions of the same library in different sketches.


controlling 2 sensor and 3 pump using millis i make a 3 pump for output and im using millis for it, i want to stop if rach the intervalm now in my code its still looping not realy stop for it thx
int pump1 = 5;//pin D5
int pump2 = 6;//pin D6
int pump3 = 7;//pin D7
float pompa1;
float pompa2;
float pompa3;
unsigned long prev_pump1    = 0;
unsigned long prev_pump2    = 0;
unsigned long prev_pump3    = 0;
unsigned long initiate_start = 0;
int pump_state1 = false;
int pump_state2 = false;
int pump_state3 = false;

and after this this is my loop program
  //-----------PUMP ALGORITHM--------------------
  long int pompa01 = pompa1*1000;//interval pump1
  long int pompa02 = pompa2*1000;//interval pump2
  long int pompa03 = pompa3*1000;//interval pump2

  unsigned long initiate_start = millis();

  //pompa1
  if(intiate_start-prev_pump1 > pompa01)
  {
    pump_state1 = !pump_state1;

    if(pump_state1)
    {
      digitalWrite(pump1, HIGH);
    }
    else
    {
      digitalWrite(pump1, LOW);
    }
    prev_pump1 = initiate_start;
  }

    //pompa2
  if(intiate_start-prev_pump2 > pompa02)
  {
    pump_state2 = !pump_state2;

    if(pump_state2)
    {
      digitalWrite(pump2, HIGH);
    }
    else
    {
      digitalWrite(pump2, LOW);
    }
    prev_pump2 = initiate_start;
  }

    //pompa3
  if(intiate_start-prev_pump3 > pompa03)
  {
    pump_state3 = !pump_state3;

    if(pump_state3)
    {
      digitalWrite(pump3, HIGH);
    }
    else
    {
      digitalWrite(pump3, LOW);
    }
    prev_pump3 = initiate_start;
  }

This is meant as a complement to Michel Keijzers' answer. I fully agree
with his assessment: code duplication is something to be avoided, as it
greatly hurts maintainability. And I sympathise with him feeling the
urge to implement this as a proper class. ;-)
I would argue, however, that between the simplistic version of the OP's
code, and the fully object-oriented one of that answer, there is an
intermediate step that is worth targeting as the next thing to learn. I
mean: arrays and loops.
Many cases of code duplication follow a pattern roughly like this:
// At the top of the sketch:
some_type data0 = some_value;
some_type data1 = some_other_value;
// etc.

// Within a function:
do_lots_of_stuff(data0);
do_lots_of_stuff(data1);
// etc.

where do_lots_of_stuff() may be a lot of code, rather than a single
function call (and it would indeed not be that bad if it was just a
function call).
The simple solution to this kind of code duplication is to put the
variables in an array, and process them by looping through the array:
// At the top of the sketch:
const int data_count = ...;
some_type[data_count] = {some_value, some_other_value, ...};

// Within a function:
for (int i = 0; i < data_count; i++)
    do_lots_of_stuff(data[i]);

Here is my attempt at applying this technique to the OP's code. Note
that, since there are multiple variables for each pump, we need multiple
arrays:
const int pump_count = 3;
const uint8_t pump_pins[pump_count] = {5, 6, 7};
const uint32_t pump_half_periods[pump_count] = {1000, 2500, 3200};

uint8_t pump_states[pump_count];  // LOW or HIGH
uint32_t pump_last_actuations[pump_count];  // time in ms

void setup() {
    for (int i = 0; i < pump_count; i++) {
        pinMode(pump_pins[i], OUTPUT);
    }
}

void loop() {
    unsigned long now = millis();
    for (int i = 0; i < pump_count; i++) {
        if (now - pump_last_actuations[i] >= pump_half_periods[i]) {
            pump_states[i] = (pump_states[i] == HIGH) ? LOW : HIGH;
            digitalWrite(pump_pins[i], pump_states[i]);
            pump_last_actuations[i] = now;
        }
    }
}

This removes all the duplication, and should be easier to maintain and
debug.
Once one is comfortable with this concept, I would argue the next step
in terms of building abstractions would be to bundle together all the
data relative to one pump into a struct. Then we would have a single
array (the elements of which are structs) instead of a collection of
arrays:
// Data structure describing a pump.
struct Pump {
    const uint8_t pin;
    const uint32_t half_period;  // half period in ms
    uint8_t state;               // LOW or HIGH
    uint32_t last_actuation;     // time in ms
};

const int pump_count = 3;

Pump pumps[pump_count] = {
// pin, half-T, state, last_actuation
    {5, 1000, LOW, 0},
    {6, 2500, LOW, 0},
    {7, 3200, LOW, 0}
};

The body of setup() and loop() would be very similar to the previous
version, but with pump_pins[i] replaced by pumps[i].pin and so on.
The third step in the abstraction ladder would be to embed the code that
handles the data structure with the data itself in a class, as shown
in Michel Keijzers' answer. With the proper methods defined, the main
sketch could be reduced to something like this:
#include "Pump.h"

Pump pumps[] = {
    Pump(5, 1000),
    Pump(6, 2500),
    Pump(7, 3200)
};

void setup() {
    for (Pump &pump : pumps)
        pump.begin();
}

void loop() {
    for (Pump &pump : pumps)
        pump.process();
}

I tried all these methods, and it turns out the first one (with a
collection of arrays) is the one that uses the least lines of code, and
the last one (with a class) uses the most. One could wonder then why use
more advanced abstractions, if they increase the amount of code one has
to type. The reason is, these abstractions become useful when the
program grows in complexity. On can put together all the code that deals
with the pumps in one place (maybe in a separate file), all the code
that deals with sensors in another place... and the main sketch that
puts all the pieces together remains simple.


How to handle multiple simultaneous Arduino development environments? I am developing for several different target microcontrollers (on OS X 10.11), which requires some unique combinations of (Arduino) IDE version, library versions, USB drivers, support software, etc.

What are the pros and cons of using separate logged-in users for each environment as opposed to using Virtual Machines? Are there other methods commonly in use to separate environments, and also keep the environments archived for any legacy needs?

Update: I also have a desire to keep these environments as standard as possible: installing released components (e.g., IDE, drivers) and customizing IDE app settings, but trying to avoid source-level forks. This is for my own sanity, and to give best chance of replicating the environment in the future.

I'm yet to see evidence that there is a sound or comprehensive way to do this, so would be pleased to read better suggestions.  As for why you would want to, there are a number of board support plugins/extensions that are moderately functional on some recent Arduino versions, but partially or entirely incompatible with others.

You can achieve a very limited partial version segregation by creating a new sketchbook folder for each version, which would host your libraries and hardware folders.

To get the IDE to pick this up, you could have a custom preferences file (rather than preferences.txt) with that sketchbook location set.  You can specify the file to use on the command line, for example:

/opt/arduino-1.6.8/arduino --preferences-file ~/.arduino15/alternate.txt

However, there is still quite a bit related to extra board support and similar stored in the settings folder, and at present that is hard coded to the same "Arduino15" or ".arduino15" path for all recent versions.

This hard-coding of the settings folder is implemented in the version of Platform.java applicable to the operating system you are running under, so it is not clear how you could change this except at the source level, by modifying the jar, or by playing file-system level tricks with the operating system (process-unique mounts, etc).


What's the smallest (cheap) USB Host solution for Arduino? I'm building a project that will connect to users' phones (Android at first, but iPhone too, if there's enough interest) via USB. Of course, this means that I need a USB host in the project. The total size of the device has to be about the size of the phone, so answers that seriously suggest shields aren't going to be helpful - they'd put me over my size budget by at least a factor of 3.

I'd also rather not require an adapter to go from the USB Mini B connector type to the Micro B connector type.

Gravitech has a USB Host board for the Nano 3 that has a USB Type A connector, and the combination of a Nano and Gravitech Host is about the right size (maybe a little thick, once the whole thing is soldered to my own board), but the USB host is $25. I can get the Nano for about $4 each and would like to keep the USB host in the neighborhood of $8 each. Are the solder fumes getting to me, or is there such a specimen out there and I'm just not finding it?

The Arduino Due and Arduino Mega ADK can both serve as a USB Host. You can also use the chip that the Mega uses yourself


random() Function isn't random at all I'm using the random() to generate random coordinates for coins in a simple game console. The problem here is that the random() function is not generating random numbers, since the coin is at the same coordinates every single time I upload it. I am using the Adafruit GFX library with the Adafruit 1.44" Color TFT LCD Display. Here is my code (sorry, it's kind of long).
//necessary libraries
#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_ST7735.h> // Hardware-specific library
#include <SPI.h>

//colors
#define BLACK    0x0000
#define BLUE     0x001F
#define RED      0xF800
#define GREEN    0x07E0
#define CYAN     0x07FF
#define MAGENTA  0xF81F
#define YELLOW   0xFFE0
#define WHITE    0xFFFF

//pins
#define TFT_CS  10
#define TFT_RST  9
#define TFT_DC   8

//joystick variables
const int VRxPin = A1;
const int VRyPin = A0;
const int SWPin  = 7;
bool mov = false;

//data read from joystick pins
int x = 0;
int y = 0;
int SW = 0;

// X and Y coords for entities
int playerx = 50;
int playery = 50;

long coinx;
long coiny;

//game variables
int score = 0;

//defining the tft class
Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST);

//useful text function
void output(char *text, int x, int y, uint16_t color, bool wrap = 0){
  tft.setCursor(x, y);
  tft.setTextColor(color);
  tft.setTextWrap(wrap);
  tft.print(text);
}

//there is probably a better way to do this but im too lazy to find it
void num_output(int text, int x, int y, uint16_t color, bool wrap = 0){
  tft.setCursor(x, y);
  tft.setTextColor(color);
  tft.setTextWrap(wrap);
  tft.print(text);
}

//clears screen
void clear() {
  tft.fillScreen(BLACK);
}

//setup (lcd init & startup screen)
void setup() {
  Serial.begin(9600);
  pinMode(SWPin,INPUT_PULLUP);
  tft.initR(INITR_GREENTAB);

  long coinx = random(20, 100);
  long coiny = random(20, 100);

  clear();
  output("RAMBUTAN", 40, 60, RED);
  delay(1000);
  clear();
  tft.fillRect(playerx, playery, 5, 5, WHITE);
  tft.fillCircle(coinx, coiny, 5, YELLOW);
}

void loop() {
  //reads data from joystick pins every single tick
  int VRx = analogRead(VRxPin);
  int VRy = analogRead(VRyPin);
  int SW = digitalRead(SWPin);

  //converts joystick pin data into directions
  if (VRx > 250 && VRx < 750 && VRy > 250 && VRy < 750) {
    // middle
  } else if (VRx > 511.5 && VRy < 750 && VRy > 240) {
    // right
    playery -= 5;
    mov = true;
  } else if (VRx < 511.5 && VRy < 750 && VRy > 240) {
    // left
    playery += 5;
    mov = true;
  } else if (VRy > 511.5 && VRx < 750 && VRx > 240) {
    // up
    playerx += 5;
    mov = true;
  } else if (VRy < 511.5 && VRx < 750 && VRx > 240) {
    // down
    playerx -= 5;
    mov = true;
  } else {
    mov = false;
  }

  if (mov == true) {
    clear();
    tft.fillRect(playerx, playery, 5, 5, WHITE);
    num_output(score, 10, 10, WHITE);
    tft.fillCircle(coinx, coiny, 5, YELLOW);
    mov = false;
  }
  delay(100);
}

You are correct, random() isn't random - it's pseudo random. It returns successive results from a mathematical formula which, to all intents and purposes, is random. It's also predictable, as you have seen.
The formula has a starting value, called the seed, which you can choose your self. Changing that seed gives you a different sequence of random-like numbers.
So the trick is to set the seed to something that is truly random. One common source of randomness, or entropy, is an unconnected ADC input:
randomSeed(analogRead(A3));

You can read more about the randomSeed() function here.


Why is my switch not working? I'm trying to have a common light switch turn a LED on and off.

When I connect the light switch directly to a LED, it works like it should - the LED turns on and off with the switch.

When I connect the light switch back to the board, changing the switch does nothing - I get the exact same signals regardless of whether the switch is on or off.

Why?
How do I make the board recognize whether the switch is on or off?

The diagram I followed:

const int  buttonPin = 2;

const int ledUt = 13;
const int ledTest = 12;
int buttonPushCounter = 0;
int buttonState = 0;
int lastButtonState = 0;

int tilstand = 0;

int buttonStateForrigeForrige = 0;

boolean light = false;

void setup() {
  Serial.println("Hello World");
  Serial.begin(9600);
  pinMode(buttonPin, INPUT);
  pinMode(ledUt, OUTPUT);
  pinMode(ledTest, OUTPUT);

}

void loop() {

  digitalWrite(ledTest, HIGH);
  buttonState = digitalRead(buttonPin);
  Serial.println("Sjekk");

  tilstand = LOW;
  if ( buttonState == HIGH ) {
    Serial.println("buttonState HIGH");
    if ( lastButtonState == HIGH ) {
      Serial.println("lastButtonState HIGH");
      tilstand = HIGH;
    } else {
      Serial.println("lastButtonState LOW");
    }
  } else {
    Serial.println("buttonState LOW");
  }

  if (buttonState != lastButtonState) {

    if (buttonState == HIGH) {
      buttonPushCounter++;
      Serial.println("on");
      Serial.println(buttonPushCounter);
    } else {
      Serial.println("off");
    }
  }
  buttonStateForrigeForrige = lastButtonState;
  lastButtonState = buttonState;

  if (tilstand == HIGH) {
    digitalWrite(ledUt, HIGH);
  } else {
    digitalWrite(ledUt, LOW);
  }
  }

See my page about switches. Judging by your very-hard-to-read diagram, you have just connected the switch to an input pin like this:

That will not give a positive reading either way because it is "floating". You should connect a pull-up or pull-down resistor, like this:

Now if the switch is open, it is pulled-up to 5V by the resistor and the input will read HIGH. When the switch is closed the switch conducts and "overpowers" the resistor, and it would read LOW.

An alternative is to use a pull-down resistor like this:

That reverses the sense of the switch. When open it will read LOW and when closed it will read HIGH.

I hope you have a resistor in series with the LED.


class enum was not declared in this scope I am programming an Arduino.  In the same .ino file as setup() and loop() I have defined the following:

void setup()
{
  // setup code
}

enum class CYCLE { TypeA, TypeB };

String cycleToString (CYCLE cycle) {
  if (cycle == CYCLE::TypeA) {
    return "TypeA";
  }
  else if (cycle == CYCLE::TypeB) {
    return "TypeB";
  }
  return "Undefined";
}

void loop()
{
  // loop code
}

But on compiling it gives the error:

sketch_v1:37:22: error: 'CYCLE' was not declared in this scope
 String cycleToString (CYCLE cycle) {
                      ^
/Users/.../sketch_v1.ino: In function 'String cycleToString(CYCLE)':
sketch_v1:37:31: error: 'String cycleToString(CYCLE)' redeclared as different kind of symbol
 String cycleToString (CYCLE cycle) {
                                  ^
/Users/.../sketch_v1.ino:37:8: note: previous declaration 'String cycleToString'
 String cycleToString (CYCLE cycle) {
        ^

Note that the enum class is fine and works as intended but if I try to add the function relying on the CYCLE type it then errors.

This is a known bug of Arduino builder, if you have functions before structs, classes or enums in sketch.
The sketch:
void foo() {
}

enum class CYCLE { TypeA, TypeB };

String cycleToString (CYCLE cycle) {
  if (cycle == CYCLE::TypeA) {
    return "TypeA";
  }
  else if (cycle == CYCLE::TypeB) {
    return "TypeB";
  }
  return "Undefined";
}

void setup() {
}

void loop() {
}

is processed to this .cpp file
#include <Arduino.h>
#line 1 "/tmp/arduino_modified_sketch_327776/sketch_jun23a.ino"
#line 1 "/tmp/arduino_modified_sketch_327776/sketch_jun23a.ino"

#line 2 "/tmp/arduino_modified_sketch_327776/sketch_jun23a.ino"
void foo();
#line 7 "/tmp/arduino_modified_sketch_327776/sketch_jun23a.ino"
String cycleToString(CYCLE cycle);
#line 17 "/tmp/arduino_modified_sketch_327776/sketch_jun23a.ino"
void setup();
#line 22 "/tmp/arduino_modified_sketch_327776/sketch_jun23a.ino"
void loop();
#line 2 "/tmp/arduino_modified_sketch_327776/sketch_jun23a.ino"
void foo() {
}

enum class CYCLE { TypeA, TypeB };

String cycleToString (CYCLE cycle) {
  if (cycle == CYCLE::TypeA) {
    return "TypeA";
  }
  else if (cycle == CYCLE::TypeB) {
    return "TypeB";
  }
  return "Undefined";
}

void setup() {
}

void loop() {
}

as you can see the forward declarations of functions are before the first function so before the enum.
The workaround for this bug is to follow good practice and declare all the structs, enums and classes before the first function definition.


Trouble configuring Arduino Due SPI to ADC I am having trouble configuring Arduino Due SPI to an AD7490 ADC.

Here is how I have the pins connected:

+3.3V > 7490 pin 22 Vin
+3.3V > 7490 Vref
DUE CS (8) > 7490 pin 20 SS - slave select)
DUE SCK > 7490 pin 16 (SCK - clock)
DUE MOSI > 7490 pin 19 (MOSI - data out)
Ground > 7490 pin 24 (all ground lines are tied together)
DUE MISO > 7490 pin 15

Below is my code, I feel like I am writing the correct bits into the register. The problem I think I'm having is getting the timing write. The code is a simple attempt to read a single channel.

#include <SPI.h>

// Set Constants
const int adcChipSelectPin = 8;      // set pin 8 as the chip select for the
ADC:

// Start setup function:
void setup() {

pinMode (adcChipSelectPin, OUTPUT);
// set the ChipSelectPins high initially:
digitalWrite(adcChipSelectPin, HIGH);
// initialise SPI:
SPI.begin();
SPI.setBitOrder(MSBFIRST);         // Not strictly needed but just to be
sure.
SPI.setDataMode(SPI_MODE0);        // Not strictly needed but just to be
sure.
Serial.begin(9600);
//Clock Speed: Master clock/divider
//84Mhz/64 =  1.3 MHz
SPI.setClockDivider(SPI_CLOCK_DIV64);

} // End setup function.

// Start loop function:
void loop() {
float voltage[2];
for (int i = 0; i < 3; i++) {
voltage[i] = readAdc(0, 0);
}

}// End of loop function.

//Function to read the ADC, accepts the channel to be read.
float readAdc(int channel, int slave) {

float value;
if (slave == 0) {
noInterrupts(); // disable interupts to prepare to send address data to the
ADC.
digitalWrite(adcChipSelectPin, LOW); // take the Chip Select pin low to
select the ADC.

byte FirstByte = 0b10000011;
byte SecondByte = 0b00110000;

SPI.transfer(FirstByte);

byte response1 = SPI.transfer(SecondByte);
byte response2 = SPI.transfer(0x00);

digitalWrite(adcChipSelectPin, HIGH); // take the Chip Select pin high to
de-select the ADC.
interrupts(); // Enable interupts.
Serial.println(response1);
Serial.println(response2);

}

The serial.prints output 255 consistently. In my experience this means the SPI is configured incorrectly.

Any pointers are appreciated.

For anyone else who comes across the same problem, this worked for me:

// include the library code:
#include <SPI.h>

// Set Constants
const int adcChipSelectPin = 8;      // set pin 8 as the chip select for the ADC:

// Start setup function:
void setup() {
    pinMode (adcChipSelectPin, OUTPUT);

    // set the ChipSelectPins high initially:
    digitalWrite(adcChipSelectPin, HIGH);

    // initialise SPI:
    SPI.begin();
    SPI.setBitOrder(MSBFIRST);         // Not strictly needed but just to be sure.
    SPI.setDataMode(SPI_MODE0);        // Not strictly needed but just to be sure.
    Serial.begin(9600);

    //Clock Speed: Master clock/divider
    //84Mhz/64 =  1.3 MHz
    SPI.setClockDivider(SPI_CLOCK_DIV64);

    //Send dummy values over when ADC is turned on
    //Hold Din High for 16 clock cycles twice
    digitalWrite(adcChipSelectPin, LOW);
    SPI.transfer(0xFF);
    SPI.transfer(0xFF);
    digitalWrite(adcChipSelectPin, HIGH);

    digitalWrite(adcChipSelectPin, LOW);
    SPI.transfer(0xFF);
    SPI.transfer(0xFF);
    digitalWrite(adcChipSelectPin, HIGH);
    asm volatile("nop");
    asm volatile("nop");
    asm volatile("nop");
    asm volatile("nop");
    asm volatile("nop");
    //Send dummy values, next read should have correct values

    digitalWrite(adcChipSelectPin, LOW);
    byte FirstByte = 0x83;
    byte SecondByte = 0x50;
    byte response1 = SPI.transfer(FirstByte);
    byte response2 = SPI.transfer(SecondByte);

    digitalWrite(adcChipSelectPin, HIGH);

    asm volatile("nop");
    asm volatile("nop");
    asm volatile("nop");
    asm volatile("nop");
    asm volatile("nop");
    ///////////////////////////////////////////////////////////////////////////////////

    //50ns quiet time?
    asm volatile("nop");
    asm volatile("nop");
    asm volatile("nop");
    asm volatile("nop");
    asm volatile("nop");
} // End setup function.

// Start loop function:
void loop() {
    float voltage[2];
    for (int i = 1; i < 17; i++) {
        voltage[i] = readAdc(0, 1);
        //50ns quiet time?
        asm volatile("nop");
        asm volatile("nop");
        asm volatile("nop");
        asm volatile("nop");
        asm volatile("nop");
    }
} // End of loop function.

//Function to read the ADC, accepts the channel to be read.
float readAdc(int channel, int slave) {
    float value;
    if (slave == 0) {
        byte FirstByte = 0x83;
        byte SecondByte = 0x50;
        FirstByte |= channel << 2;

        noInterrupts(); // disable interupts to prepare to send address data to the ADC.

        digitalWrite(adcChipSelectPin, LOW); // take the Chip Select pin low to select the ADC.
        //Write = 1
        //SEQ = 0
        // ADD3-ADD0 = 0000
        //PM1 = PM0 = 1
        //Shadow = 0
        //WEAK/Tri = 1
        //Range = 0
        //Coding = 1
        //0b10000010 1010 0000
        //extra 4 zeros to fill

        //May need to wait 16 * (1/freq)
        //16 * (1/1.3MHz)
        byte response1 = SPI.transfer(FirstByte);
        byte response2 = SPI.transfer(SecondByte);
        digitalWrite(adcChipSelectPin, HIGH);

        interrupts(); // Enable interupts.

        //Serial.println(response1);
        Serial.println(response2);
        byte channel = (response1 >> 4);
        //byte value = (response1 << 4);
        //byte digitalValue = (response1 << 4) | response2;
        //Serial.println(digitalValue);
        //Serial.println(channel);

        byte digitalValue = 0x00;
        float value = (float(digitalValue) * 3.3) / 4096.000; // The digital value is
        converted to an analogue voltage using a VREF of 2.048V.
        //Serial.print(channel);
        //Serial.print("\t");
        //Serial.println(value);
    }
}