text:
No serial data from Adafruit GPS (on Arduino 101)
New Adafruit GPS connected to my Arduino 101 board.
When trying to use the RX/TX hardware serial (on digital pins 0 / 1), with a simple sketch (described by Adafruit) to output a serial response, I'm not seing anything in the serial monitor (9600 baud).
// this sketch will allow you to bypass the Atmega chip
// and connect the Ultimate GPS directly to the USB/Serial
// chip converter.

// Connect VIN to +5V
// Connect GND to Ground
// Connect GPS RX (data into GPS) to Digital 0
// Connect GPS TX (data out from GPS) to Digital 1

void setup() {}
void loop() {}

Wires connected as in the sketch, also tried swapping them out in case of faulty wire.
Went on to try TinyGPS++ default example code, across a variety of pins: 3,4 & 8,9 & 0,1.
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
/*
   This sample code demonstrates the normal use of a TinyGPS++ (TinyGPSPlus) object.
   It requires the use of SoftwareSerial, and assumes that you have a
   4800-baud serial GPS device hooked up on pins 4(rx) and 3(tx). EDITED BELOW.
*/

static const int RXPin = 8, TXPin = 9;
static const uint32_t GPSBaud = 9600;

// The TinyGPS++ object
TinyGPSPlus gps;

// The serial connection to the GPS device
SoftwareSerial ss(RXPin, TXPin);

void setup()
{
  Serial.begin(9600);
  ss.begin(GPSBaud);

  Serial.println(F("FullExample.ino"));
  Serial.println(F("An extensive example of many interesting TinyGPS++ features"));
  Serial.print(F("Testing TinyGPS++ library v. ")); Serial.println(TinyGPSPlus::libraryVersion());
  Serial.println(F("by Mikal Hart"));
  Serial.println();
  Serial.println(F("Sats HDOP Latitude   Longitude   Fix  Date       Time     Date Alt    Course Speed Card  Distance Course Card  Chars Sentences Checksum"));
  Serial.println(F("          (deg)      (deg)       Age                      Age  (m)    --- from GPS ----  ---- to London  ----  RX    RX        Fail"));
  Serial.println(F("---------------------------------------------------------------------------------------------------------------------------------------"));
}

void loop()
{
  static const double LONDON_LAT = 51.508131, LONDON_LON = -0.128002;

  printInt(gps.satellites.value(), gps.satellites.isValid(), 5);
  printInt(gps.hdop.value(), gps.hdop.isValid(), 5);
  printFloat(gps.location.lat(), gps.location.isValid(), 11, 6);
  printFloat(gps.location.lng(), gps.location.isValid(), 12, 6);
  printInt(gps.location.age(), gps.location.isValid(), 5);
  printDateTime(gps.date, gps.time);
  printFloat(gps.altitude.meters(), gps.altitude.isValid(), 7, 2);
  printFloat(gps.course.deg(), gps.course.isValid(), 7, 2);
  printFloat(gps.speed.kmph(), gps.speed.isValid(), 6, 2);
  printStr(gps.course.isValid() ? TinyGPSPlus::cardinal(gps.course.value()) : "*** ", 6);

  unsigned long distanceKmToLondon =
    (unsigned long)TinyGPSPlus::distanceBetween(
      gps.location.lat(),
      gps.location.lng(),
      LONDON_LAT,
      LONDON_LON) / 1000;
  printInt(distanceKmToLondon, gps.location.isValid(), 9);

  double courseToLondon =
    TinyGPSPlus::courseTo(
      gps.location.lat(),
      gps.location.lng(),
      LONDON_LAT,
      LONDON_LON);

  printFloat(courseToLondon, gps.location.isValid(), 7, 2);

  const char *cardinalToLondon = TinyGPSPlus::cardinal(courseToLondon);

  printStr(gps.location.isValid() ? cardinalToLondon : "*** ", 6);

  printInt(gps.charsProcessed(), true, 6);
  printInt(gps.sentencesWithFix(), true, 10);
  printInt(gps.failedChecksum(), true, 9);
  Serial.println();

  smartDelay(1000);

  if (millis() > 5000 && gps.charsProcessed() < 10)
    Serial.println(F("No GPS data received: check wiring"));
}

// This custom version of delay() ensures that the gps object
// is being "fed".
static void smartDelay(unsigned long ms)
{
  unsigned long start = millis();
  do
  {
    while (ss.available())
      gps.encode(ss.read());
  } while (millis() - start < ms);
}

static void printFloat(float val, bool valid, int len, int prec)
{
  if (!valid)
  {
    while (len-- > 1)
      Serial.print('*');
    Serial.print(' ');
  }
  else
  {
    Serial.print(val, prec);
    int vi = abs((int)val);
    int flen = prec + (val < 0.0 ? 2 : 1); // . and -
    flen += vi >= 1000 ? 4 : vi >= 100 ? 3 : vi >= 10 ? 2 : 1;
    for (int i=flen; i<len; ++i)
      Serial.print(' ');
  }
  smartDelay(0);
}

static void printInt(unsigned long val, bool valid, int len)
{
  char sz[32] = "*****************";
  if (valid)
    sprintf(sz, "%ld", val);
  sz[len] = 0;
  for (int i=strlen(sz); i<len; ++i)
    sz[i] = ' ';
  if (len > 0)
    sz[len-1] = ' ';
  Serial.print(sz);
  smartDelay(0);
}

static void printDateTime(TinyGPSDate &d, TinyGPSTime &t)
{
  if (!d.isValid())
  {
    Serial.print(F("********** "));
  }
  else
  {
    char sz[32];
    sprintf(sz, "%02d/%02d/%02d ", d.month(), d.day(), d.year());
    Serial.print(sz);
  }

  if (!t.isValid())
  {
    Serial.print(F("******** "));
  }
  else
  {
    char sz[32];
    sprintf(sz, "%02d:%02d:%02d ", t.hour(), t.minute(), t.second());
    Serial.print(sz);
  }

  printInt(d.age(), d.isValid(), 5);
  smartDelay(0);
}

static void printStr(const char *str, int len)
{
  int slen = strlen(str);
  for (int i=0; i<len; ++i)
    Serial.print(i<slen ? str[i] : ' ');
  smartDelay(0);
}

Serial is spitting out this for every update:

No GPS data received: check wiring

GPS is on, and can see based on the fix LED that satellite fix has occurred in both tests – no difference in output. Wires checked.
Maybe suboptimal pin solder job, but can't see that it should give no signal?

EDIT: After suggestions, re-soldered pinheader – still nothing in the serial prompt on hardware serial (pin 0,1), software serial (pin 3,4) and TinyGPS++ throws the same error (pin 3-4 + 8-9). Double-checked RX/TX order.
A colleague found an old Ublox Neo 6-M GPS, I plugged it in and repeated the above with the same empty serial results, not sure what to make of this..

Solder looks sort of okay, though you may have issue on the Tx pin (middle) where there is no verified solder wicking into the barrel like the others.
As for the code, it looks like the error is caused by the smartDelay() function where it is listening for data from the Tx line and gives you that warning if it does not see more than ten characters after five seconds of waiting for data.
Maybe try temporarily printing raw data via ss.read() in your loop rather than relying on the gps library, to verify if the module is transmitting any data on the Tx pin in the first place.

@depwl9992 I agree the TX pin may need a bit more solder.  You can also use the serial monitor in the Arduino IDE to look for the raw data output (without writing or modifying any code).  This way you can tell if the problem is with the code or the wiring... its easy to get TX/RX swapped and I've done it before!

Thanks for the ideas, no luck though, edited post

Accidentally fixed it when booting up the board tonight – not sure what changed but the serial prompt is on fire.
Wires: 5V - VIN, GND – GND, TX – 8, RX – 9
Code:
#include <SoftwareSerial.h>

// setup gps serial
int gpsTxPin = 8;
int gpsRxPin = 9;
SoftwareSerial gpsSerial(gpsTxPin, gpsRxPin);

void setup()
{
  Serial.begin(9600);  //set monitor to 9600

  gpsSerial.begin(9600); //adjust for GPS unit

  Serial.println("Ready!");
}

void loop()
{
  while(gpsSerial.available())
  {
    char c = gpsSerial.read();
    Serial.print(c);
  }
}

Excerpt from serial monitor:
...

$GPVTG,248.75,T,,M,0.19,N,0.35,K,A*3F
$GPGGA,231351.000,,,,,0,05,,,M,,M,,*7A
$GPGSA,A,1,,,,,,,,,,,,,,,*1E
$GPGSV,2,1,07,13,65,290,32,30,54,066,36,20,48,286,33,15,31,288,31*75

...


text:
Erasing all flash on boards with over 64kb of program memory
I'm using a Mega2560 board.
My project needs to store some large constant data. To preserve the first 64kb flash chunk, I write these data on addresses beyond this limit.
But there is either an issue doing that or I'm doing something wrong...
After writing data the first time, I can read all bytes without no problem, but if I rewrite these data with new ones, the new data are not written correctly. It seems that, before reprogramming, the flash over 64kb are not erased.
Is this correct? How can I resolve this issue?

Note that, to access the data over 64kb, I use a far address.
Reading inside the bootloader source (stk500v2) code, I found that it doesn't erase pages whose addresse falls over 64kb to preserve the bootloader area. It seems that the bootloader is placed at the boundary of the first 64kb.
The following is the relevant the portion of the bootloader source:

// erase only main section (bootloader protection)
// APP_END is below 64KB
if (eraseAddress < APP_END )
{
    boot_page_erase(eraseAddress);  // Perform page erase
    boot_spm_busy_wait();       // Wait until the memory is erased.
    eraseAddress += SPM_PAGESIZE;   // point to next page to be erase
}

/* Write FLASH */
do {
    lowByte     =   *p++;
    highByte    =   *p++;

    data        =   (highByte << 8) | lowByte;
    boot_page_fill(address,data);

    address =   address + 2;    // Select next word in memory
    size    -=  2;              // Reduce number of bytes to write by two
} while (size);                 // Loop until all bytes written

boot_page_write(tempaddress);
boot_spm_busy_wait();
boot_rww_enable();

source: Stack Exchange

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

sort: votes


text:
Multiple timed functions (timing off)
Desired program:
I have 3 momentary push buttons and a 4-channel relay board with my Arduino Uno. The relays are connected to 2 sinks, a shower, and a pump. Each push button should turn the pump and its respective fixture on for 10 seconds. I used a time buffer to debounce the push buttons.
Problem:
The time in which the function stays on is inconsistent. Sometimes 10 seconds, sometimes 3 seconds. Additionally all the relays turn off at the same time even if they were started at different times. they should all be individually timed and the pump should stay on as long as any of the three other relays are on.
Wiring Diagram:

Code:
//initialize and declare variables
// Pins 10,11,12,13 will be connected to their respected relays
const int pump = 13;
const int relay2 = 12;
const int relay3 = 11;
const int relay4 = 10;

//initialize pins 2,3,4 to be connected to the momentary push buttons
const int buttonPin1 = 2;
const int buttonPin2 = 3;
const int buttonPin3 = 4;

//these variables track the state of the buttons, low if not pressed, high if pressed
int buttonState1 = LOW;
int buttonState2 = LOW;
int buttonState3 = LOW;

//Initialize pin states for valve check
int relay2State;
int relay3State;
int relay4State;

long lastDebounceTime = 0; // the last time the output pin was toggled
long debounceDelay = 100; // the debounce time; increase if the output flickers
unsigned long previousMillis = 0;
unsigned long previousMillis2 = 0;
unsigned long previousMillis3 = 0;
unsigned long runTime = 10000;

void setup() {
  //set pins connected to the relays as outputs.
  pinMode(pump, OUTPUT);
  pinMode(relay2, OUTPUT);
  pinMode(relay3, OUTPUT);
  pinMode(relay4, OUTPUT);

  //set push buttons as inputs
  pinMode(buttonPin1, INPUT);
  pinMode(buttonPin2, INPUT);
  pinMode(buttonPin3, INPUT);

  //initialize the starting state of the relay pins
  digitalWrite(pump, HIGH);
  digitalWrite(relay2, HIGH);
  digitalWrite(relay3, HIGH);
  digitalWrite(relay4, HIGH);
} // close void setup

void loop() {
  unsigned long currentMillis = millis();
  unsigned long currentMillis2 = millis();
  unsigned long currentMillis3 = millis();
  //sample the state of the buttons
  buttonState1 = digitalRead(buttonPin1);
  buttonState2 = digitalRead(buttonPin2);
  buttonState3 = digitalRead(buttonPin3);
  //check to see if any valves are open
  relay2State = digitalRead(relay2);
  relay3State = digitalRead(relay3);
  relay4State = digitalRead(relay4);
  //filter out any noise by setting a time buffer
  if ((millis() - lastDebounceTime) > debounceDelay) {
    //sample the state of the buttons
    buttonState1 = digitalRead(buttonPin1);
    buttonState2 = digitalRead(buttonPin2);
    buttonState3 = digitalRead(buttonPin3);
    //check to see if any valves are open
    relay2State = digitalRead(relay2);
    relay3State = digitalRead(relay3);
    relay4State = digitalRead(relay4);
  }

  // if button1 has been pressed, let's toggle the pump and relay2 from off
  //to on for 10 seconds
  if (buttonState1 == HIGH) {
    digitalWrite(relay2, LOW); // turn relay2
    lastDebounceTime = millis(); // set the current time
  }
  if (currentMillis - previousMillis > runTime) {
    digitalWrite(relay2, HIGH); // turn relay2
    previousMillis = currentMillis;
  }
  //if button2 has been pressed, lets toggle the pump and relay3 from off
  //to on for 10 seconds
  if (buttonState2 == HIGH) {
    digitalWrite(relay3, LOW); // turn relay3 on
  }
  if (currentMillis2 - previousMillis2 > runTime) {
    previousMillis2 = currentMillis2;
    digitalWrite(relay3, HIGH); // turn relay3 off
  }
  // if button3 has been pressed, lets toggle the pump and relay4 from off to
  //on for 10 seconds
  if (buttonState3 == HIGH) {
    digitalWrite(relay4, LOW); // turn relay4 on
    lastDebounceTime = millis(); // set the current time
  }
  if (currentMillis3 - previousMillis3 > runTime) {
    previousMillis3 = currentMillis3;
    digitalWrite(relay4, HIGH); // turn relay4 off
  }
  // if any valve is open, turn the pump on
  if(relay2State == LOW || relay3State == LOW || relay4State == LOW) {
    digitalWrite(pump, LOW);
  } else {
    digitalWrite(pump, HIGH);
  }
} // close void loop

Any help would be greatly appreciated. I think I'm stuck in the time buffer for the debounce and my time checks aren't updating right.

In a program like this it rapidly becomes quite confusing with the variable names all being so similar. Because of this, this is a good candidate for creating a class to do the job for you. This is because you have sets of functionality and variables that are duplicated to do the same job with different settings (IO pins).
It would be a trivial matter to create a class that turns on an output for a specified amount of time:
class TimedOutput {
    private:
        uint8_t _pin;
        uint32_t _started;
        uint32_t _runtime;
        bool _running;

    public:
        TimedOutput(uint8_t pin, uint32_t runtime) {
            _pin = pin;
            _runtime = runtime;
            _started = 0;
            _running = false;
        }

        void begin() {
            pinMode(_pin, OUTPUT);
            digitalWrite(_pin, LOW);
        }

        void start() {
            digitalWrite(_pin, HIGH);
            _running = true;
            _started = millis();
        }

        void run() {
            if (!_running) return;
            if (millis() - _started >= _runtime) {
                digitalWrite(_pin, LOW);
                _running = false;
            }
        }
};

// Create the object
TimedOutput shower(10, 10000); // Output on pin 10 for 10 seconds
TimedOutput sink(11, 3000);    // Output on pin 11 for 3 seconds

void setup() {
    // Configure the pin
    shower.begin();
    sink.begin();
    pinMode(2, INPUT_PULLUP); // Button
    pinMode(3, INPUT_PULLUP); // Button
}

void loop() {
    // Start it if the button is pressed:
    if (digitalRead(2) == LOW) {
        shower.start();
    }

    if (digitalRead(3) == LOW) {
        sink.start();
    }

    // Do the checking for if it needs to stop:
    shower.run();
    sink.run();
}

is there no need to debounce the button in this case?

No, not really. Once the output is on its on regardless of what the button does.

the relays start out energized. What would i need to change to have them start deenergized? this would be my last question as this code has helped a ton!

Swap the highs and lows in the digitalWrites in the class.

@NathanH. I see your buttons are pull down. You should change INPUT_PULLUP to INPUT and check if the input is HIGH not LOW.

Take a modular approach to it.
For example, break the functionality intwo two pieces.
Readbutton1() returns 1 if and only if button 1 has been pressed and it passed debouncing. There are tons of ways to do that.
Energizerelay1() is called to energize relay number 1 for 10 seconds. Again, there are tons of ways to do that.
Then you can integrate them all together in your loop.
Fairly easy. The key to any programming is to break down a task into individual modules and then reintegrate those modules together to perform the desired the task.
Coding those individual modules is often simple.

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


text:
Why don't these sketches produce a similar output?
I compiled the following two sketches with the compiler used by the Arduino IDE and ran them on an Arduino UNO (smd edition).
I'm using:

Arduino IDE v. 1.8.0
Arduino AVR Boards v. 1.6.20

1.
void setup() {

  Serial.begin(115200);
  unsigned long a, b;
  //unsigned long c, d;

  a = micros();
  for (unsigned long i = 0; i != 1000000; i++) digitalRead(13);
  b = micros();
  Serial.println(b - a);

  //c = micros();
  //for (unsigned long i = 0; i != 1000000; i++) digitalRead(13);
  //d = micros();
  //Serial.println(d - c);

}

void loop () {}

2.
void setup() {

  Serial.begin(115200);
  unsigned long a, b;
  unsigned long c, d;

  a = micros();
  for (unsigned long i = 0; i != 1000000; i++) digitalRead(13);
  b = micros();
  Serial.println(b - a);

  c = micros();
  for (unsigned long i = 0; i != 1000000; i++) digitalRead(13);
  d = micros();
  Serial.println(d - c);

}

void loop () {}

These were the outputs on the serial monitor:

2452320
3332640
 3332704

Why did each of the two for loops in the second sketch take roughly 33% more time to execute than the loop in the first one?

I ran both sketchs on a Arduino Uno and got the same times (
4275900us +/- 100) in both cases.

If you retry both tests, you get the same numbers as above?

@MichelKeijzers yes, I always get exactly the same numbers.

It would be helpful if you edited your question to state which version of the Arduino IDE you're using and which version of Arduino AVR Boards (shown in Tools > Board > Boards Manager).

@per1234 Arduino IDE 1.8.0, Arduino AVR Boards 1.6.20. I've just edited the question.

The different time implies different (number of) instructions being executed.  This is most probably due to the crappy GCC compiler optimizations.
In the former sketch, probably the compiler manages to use only registers, which are very fast. In the second one, the compiler THINKS it needs 8 more bytes, and there are no registers left, so it uses the stack (internal RAM) to store some variables, which is slower. (still, the optimizer should realize that in fact it don't need more bytes, because a and b are not used after the first println()). To access to a SRAM location, you need a LOAD/STORE operation, which takes a longer time, with respect to an operation between registers (beside having to load the memory address to X, Y o Z).
Probably, the compiler is even crappier, because, instead of putting the rarely-used variables a,b,c,d on the stack, it puts i (which is always incremented) or other variables used in digitalRead().
Still, to explain where is the trouble (i.e. where compiler fails in optimizing the register allocation/usage), you should disassemble the object code. Use for instance Atmel Studio, which still uses GCC, but has a good debugger, disassembler and cycle-exact analysis.
Still, this is very strange, perhaps optimizations were not enabled the platform.txt of your arduino?
EDIT:
Using Arduino 1.8.0, I tested the two sketches and analyzed the lss (generated using avr-objdump). The compiler optimizes a lot more the first code. Instead of making a CALL to digitalRead() (as it happens in the second sketch) it probably recognizes that such function is called only once on the code. Therefore it makes a rjmp to it. At the end of that function, there won't be a RET but a branch to the point where i is computerd and checked (actually i is not incremented, actually gets decremented and checked against 0).
In other words, even if the two codes are equal (except that the second sketch runs the same code twice), they are compiled (optimized) differently.

Sorry, but you are wrong: the generated assembler for both cases works using only registers and inmediate values. No memory access, no stack use. The code and registers used are the same for the common part of both sketchs. Have a look at the .lss generated file (I'm using UECIDE).

Are you sure you are using the same setup of the OP?

Sure we have different setup! But I presented facts, you don't. Maybe I wrong (not the first time); just have look at your generated code, so we can have an useful analysis of platforms and compilers.

Finally I did a test. Actually I was wrong. It's not that GCC does not optimize the second sketch. Instead, it optimize a lot the first one (in my case, I'm using Arduino 1.8.0). Instead of making a CALL to digitalRead, it probably recognizes that digitalRead is called only once in the code, therefore it makes a rjmp to digital read, then from digitalRead goes back to the for loop, where it computes and checks i. (I'll edit the question. Edits will be visible for on the edit history, so the comments will still make sense).

No rjmp in my case. The generated code is the same for all three loops, and it always make a call to digitalRead and other functions. I ran out of ideas.

@LookAlterno and next-hack: first of all, thanks for your interest in my question. But how do you look at the compiled program? I'd like to have a look myself to what you call the "generated code" and - if it can be useful - to provide the one produced by my compiler, but I actually don't know how to get it.

I'm using UECIDE (http://uecide.org/download.php) as my IDE, instead of Arduino IDE.  UECIDE has a tree view of your project: sources (.ino), headers (.h), libraries and Output. Under Output you can find all the intermediate files created by the Compile menu option. One of those is the .lss file, with the assembler code of your complete program (your code + libraries).

The Arduino IDE does not, by default, produce .lss files. You can produce them, by calling avr-objdump from the command prompt: avr-objdump -S -h yourElfFile.elf >destination.txt. You find avr-objdump in the following path: Arduino\hardware\tools\avr\bin (Where Arduino is the directory where you installed the IDE).
By the way, I also achieve exact common codes with Atmel Studio 7, but different codes with Arduino 1.8.0 (see answer). This is probably due to the different settings or different GCC version.

UECIDE's compilation methodology is somewhat different to Arduino's. It probably doesn't optimize in the same way because it compiles the different portions separately and archives them. Makes it harder for functions to be inlined or munged with rjmp instead of call. Also the compiler may be a different version (I haven't updated it in a while, maybe I'll check for a newer version today).

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


text:
HD44780 Extended non-display DDRAM?
According to page 10 of this PDF https://www.sparkfun.com/datasheets/LCD/HD44780.pdf
The HD44780 has enough DDRAM to operate an 80 character display. A 16x2 display has 32 characters meaning we have 48 characters of free DDRAM. Is there anything in the Arduino's LiquidCrystal library which allows direct access to this DDRAM space? The HD44780 datasheet says it can be used as generalised RAM.

Most libraries (and adapters) assume write only access to the LCD. The 80 character buffer is actually to allow smooth scrolling of text line.

I haven't used that particular library but I have used the ddram and cgram as memory / buffets. So the feasibility is never in question.
The downside with this approach is speed and real estate. Those devices are slow by mcu standard. You then have to provision for the rw pin and the data pins - both read and writes. That's what you should check for in the library.
But it is workable for sure.


text:
Error Compiling to Board Teensy LC
I wrote a simple switch program using a teensy LC and transistors, but the Arduino compiler will not compile for the Teensy LC. And not for just my program, but any program, including the example programs included in the Arduino. I have tried compiling for other boards and they all compile fine. This problem was also replicated on another computer running Windows 10, I am running Windows 7, with the same error message. The error message and associated code is below, for reference.
int led1 = 0;
int led2 = 1;
int led3 = 2;

int input1 = 5;
int input2 = 7;
int input3 = 9;

int bypass1 = 23; //output 1
int toneStack1_1 = 22; //output 2
int toneStack1_2 = 21; //output 3
int bypass2 = 20; //output 4
int toneStack2_1 = 19; //output 5
int toneStack2_2 = 18; //output 6
int bypass3 = 17; //output 7
int toneStack3_1 = 16; //output 8
int toneStack3_2 = 15; //output 9

boolean bypass = true;        //idicators for which mode is active
boolean toneStack1 = false;
boolean toneStack2 = false;
boolean toneStack3 = false;

void setup()
{
  pinMode(input1, INPUT);    //setting inputs
  pinMode(input2, INPUT);
  pinMode(input3, INPUT);

  pinMode(led1, OUTPUT);    //setting outputs
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);

  pinMode(bypass1, OUTPUT);
  pinMode(toneStack1_1, OUTPUT);
  pinMode(toneStack1_2, OUTPUT);
  pinMode(bypass1, OUTPUT);
  pinMode(toneStack2_1, OUTPUT);
  pinMode(toneStack2_2, OUTPUT);
  pinMode(bypass1, OUTPUT);
  pinMode(toneStack3_1, OUTPUT);
  pinMode(toneStack3_1, OUTPUT);

  digitalWrite(bypass1, HIGH);   //sets to bypass mode
  digitalWrite(bypass2, HIGH);
  digitalWrite(bypass3, HIGH);

}

void loop()
{
  input1 = digitalRead(input1);    //reads inputs from pushbuttons
  input2 = digitalRead(input2);
  input3 = digitalRead(input3);

  if(input1 == HIGH && bypass == true) //Bypass to tonestack 1
  {
    digitalWrite(bypass1, LOW);   //turns off bypass transistors
    digitalWrite(bypass2, LOW);
    digitalWrite(bypass3, LOW);

    digitalWrite(toneStack1_1, HIGH);   //turns on tonestack 1 transistors
    digitalWrite(toneStack1_2, HIGH);

    bypass = false;
    toneStack1 = true;
  }

if(input2 == HIGH && bypass == true) //Bypass to tonestack 2
  {
    digitalWrite(bypass2, LOW);   //turns off bypass transistors
    digitalWrite(bypass3, LOW);

    digitalWrite(bypass1, HIGH);  //needs to be on to let signal flow to tonestack 2

    digitalWrite(toneStack2_1, HIGH);   //turns on tonestack 2 transistors
    digitalWrite(toneStack2_2, HIGH);

    bypass = false;
    toneStack2 = true;
  }

  if(input3 == HIGH && bypass == true) //Bypass to tonestack 3
  {

    digitalWrite(bypass3, LOW); //turns off bypass transistor

    digitalWrite(bypass1, HIGH);  //needs to be on to let signal flow to tonestack 2
    digitalWrite(bypass2, HIGH);

    digitalWrite(toneStack3_1, HIGH);   //turns on tonestack 3 transistors
    digitalWrite(toneStack3_2, HIGH);

    bypass = false;
    toneStack3 = true;
  }

  if(input1 == HIGH && toneStack1 == true) //tonestack 1 to bypass
  {
    digitalWrite(bypass1, HIGH);   //turns on bypass transistors
    digitalWrite(bypass2, HIGH);
    digitalWrite(bypass3, HIGH);

    digitalWrite(toneStack1_1, LOW);   //turns off tonestack 1 transistors
    digitalWrite(toneStack1_2, LOW);

    bypass = true;
    toneStack1 = false;
  }

  if(input2 == HIGH && toneStack1 == true) //tonestack 1 to tonestack 2
  {
    digitalWrite(toneStack2_1, HIGH);   //turns on tone stack 2 transistors
    digitalWrite(toneStack2_2, HIGH);

    digitalWrite(bypass1, HIGH); //sets bypass transistors
    digitalWrite(bypass2, LOW);
    digitalWrite(bypass3, LOW);

    digitalWrite(toneStack1_1, LOW);   //turns off tonestack 1 transistors
    digitalWrite(toneStack1_2, LOW);

    toneStack2 = true;
    toneStack1 = false;
  }

  if(input3 == HIGH && toneStack1 == true) //tonestack 1 to tonestack 3
  {
    digitalWrite(toneStack3_1, HIGH);   //turns on tone stack 3 transistors
    digitalWrite(toneStack3_2, HIGH);

    digitalWrite(bypass1, HIGH);    //sets bypass transistors
    digitalWrite(bypass2, HIGH);
    digitalWrite(bypass3, LOW);

    digitalWrite(toneStack1_1, LOW);   //turns off tonestack 1 transistors
    digitalWrite(toneStack1_2, LOW);

    toneStack3 = true;
    toneStack1 = false;
  }

  if(input2 == HIGH && toneStack2 == true) //tonestack 2 to bypass
  {
    digitalWrite(bypass1, HIGH);   //turns on bypass transistors
    digitalWrite(bypass2, HIGH);
    digitalWrite(bypass3, HIGH);

    digitalWrite(toneStack2_1, LOW);   //turns off tonestack 2 transistors
    digitalWrite(toneStack2_2, LOW);

    bypass = true;
    toneStack2 = false;
  }

  if(input1 == HIGH && toneStack2 == true) //tonestack 2 to tonestack 1
  {
    digitalWrite(toneStack1_1, HIGH);   //turns on tonestack 1 transistors
    digitalWrite(toneStack1_2, HIGH);

    digitalWrite(bypass1, LOW);   //sets bypass transistors
    digitalWrite(bypass2, LOW);
    digitalWrite(bypass3, LOW);

    digitalWrite(toneStack2_1, LOW);   //turns off tonestack 2 transistors
    digitalWrite(toneStack2_2, LOW);

    toneStack1 = true;
    toneStack2 = false;
  }

  if(input3 == HIGH && toneStack2 == true) //tonestack 2 to tonestack 3
  {
    digitalWrite(toneStack3_1, HIGH);   //turns on tonestack 1 transistors
    digitalWrite(toneStack3_2, HIGH);

    digitalWrite(bypass1, HIGH);   //sets bypass transistors
    digitalWrite(bypass2, HIGH);
    digitalWrite(bypass3, LOW);

    digitalWrite(toneStack2_1, LOW);   //turns off tonestack 2 transistors
    digitalWrite(toneStack2_2, LOW);

    toneStack3 = true;
    toneStack2 = false;
  }

  if(input3 == HIGH && toneStack3 == true) //tonestack 3 to bypass
  {
    digitalWrite(bypass1, HIGH);   //turns on bypass transistors
    digitalWrite(bypass2, HIGH);
    digitalWrite(bypass3, HIGH);

    digitalWrite(toneStack3_1, LOW);   //turns off tonestack 3 transistors
    digitalWrite(toneStack3_2, LOW);

    bypass = true;
    toneStack3 = false;
  }

  if(input1 == HIGH && toneStack3 == true) //tonestack 3 to tonestack 1
  {
    digitalWrite(toneStack1_1, HIGH);   //turns on tonestack 1 transistors
    digitalWrite(toneStack1_2, HIGH);

    digitalWrite(bypass1, LOW);   //sets bypass transistors
    digitalWrite(bypass2, LOW);
    digitalWrite(bypass3, LOW);

    digitalWrite(toneStack3_1, LOW);   //turns off tonestack 3 transistors
    digitalWrite(toneStack3_2, LOW);

    toneStack1 = true;
    toneStack3 = false;
  }

  if(input2 == HIGH && toneStack3 == true) //tonestack 3 to tonestack 2
  {
    digitalWrite(toneStack2_1, HIGH);   //turns on tonestack 2 transistors
    digitalWrite(toneStack2_2, HIGH);

    digitalWrite(bypass1, HIGH);   //sets bypass transistors
    digitalWrite(bypass2, LOW);
    digitalWrite(bypass3, LOW);

    digitalWrite(toneStack3_1, LOW);   //turns off tonestack 3 transistors
    digitalWrite(toneStack3_2, LOW);

    toneStack2 = true;
    toneStack3 = false;
  }
}

And the error message:
Arduino: 1.8.4 (Windows 7), TD: 1.38, Board: "Teensy LC, Serial, 48 MHz, Smallest Code, US English"

In file included from C:\Program Files (x86)\Arduino\hardware\teensy\avr\cores\teensy3\IntervalTimer.h:34:0,

                 from C:\Program Files (x86)\Arduino\hardware\teensy\avr\cores\teensy3\IntervalTimer.cpp:31:

C:\Program Files (x86)\Arduino\hardware\teensy\avr\cores\teensy3\IntervalTimer.cpp: In member function 'void IntervalTimer::end()':

C:\Program Files (x86)\Arduino\hardware\teensy\avr\cores\teensy3\IntervalTimer.cpp:87:20: error: 'IRQ_PIT_CH0' was not declared in this scope

   NVIC_DISABLE_IRQ(IRQ_PIT_CH0 + index);

                    ^

C:\Program Files (x86)\Arduino\hardware\teensy\avr\cores\teensy3\kinetis.h:5627:68: note: in definition of macro 'NVIC_DISABLE_IRQ'

 #define NVIC_DISABLE_IRQ(n) (*((volatile uint32_t *)0xE000E180 + ((n) >> 5)) = (1 << ((n) & 31)))

                                                                    ^

Error compiling for board Teensy LC.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

I'm at my wits end trying to figure this out. I have reinstalled the Arduino 1.8.4, reinstalled Teensyduino, installed previous version of Arduino, and rebooting my system. Nothing so far has worked. I feel like there is something I am missing with this, as it seems no one else has my problem, from what I could find. Any help would be appreciated.

I was able to do a very hacky fix that seemed to work. In the directory Arduino > hardware > teensy > avr > cores > teensy3 there is a .H file called kinetis. This seems to be where some of the timers addresses are stored, and under Teensy LC, the infamous IRQ_PIT_CH0 from the error message is missing. I added it in defining it as 4 and everything seems to be working now. I haven't tested my code yet, aside from compiling it, but the blink program does work. I don't know if this will cause issues down the line, but it has seemingly fixed my current problem.

You did the right thing. Libraries have problems but having the source code lets solve them by yourself.

I experienced a similar error.  Upon further research it seems to be a known issue.  I was able to compile using 1.8.2 and Teensyduino 1.36  I accessed 1.36 from downloading the zip file of the pjrc website in the upper right corner.  The Link was download website.  Then the path was pjrc_2017_04_04\teensy\td_136


text:
ADXL345 hangs the micro-controller as vibrations increase
I am using ADXL345 accelerometer with Adafruit_ADXL345 library for vibration measurement.
I am reading acceleration at X, Y, Z-axis of a sensor placed on a vibrating platform.And serially sending it to PC at a baud rate of 115200.
When vibration is low sensor shows vibrations but as i increase the vibrations serial transmission seems to be halted. As shown in figure:(x-axis=Samples y-axis=Values )
I thought it may be due to loose connections so I soldered its terminals but it behaved the same way at higher vibrations.
 Here is the code that I’m using.
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_ADXL345_U.h>
/* Assign a unique ID to this sensor at the same time */

Adafruit_ADXL345_Unified accel = Adafruit_ADXL345_Unified(12);
int i=0;
struct measure
{
    int timestamp;
    float x;  // ACC in x direction
    float y;  //ACC in y direction
    float z;  //ACC in z direction
};
sensors_event_t event;
struct measure measurements;

int timestamp = 0;

void setup(){
   Serial.begin(115200);

  Serial.println("Accelerometer Test"); Serial.println("");

  /* Initialise the sensor */
  if(!accel.begin())
  {
    /* There was a problem detecting the ADXL345 ... check your connections */
    Serial.println("Ooops, no ADXL345 detected ... Check your wiring!");
    while(1);
  }
  accel.setDataRate(ADXL345_DATARATE_3200_HZ);
  accel.setRange(ADXL345_RANGE_16_G);
     pinMode(LED_BUILTIN, OUTPUT);
  delay(2000);
}

void loop(){

 accel.getEvent(&event);
   measurements.timestamp = timestamp++;
   measurements.x  = event.acceleration.x;
   measurements.y  = event.acceleration.y;
   measurements.z  = event.acceleration.z;

if(measurements.timestamp%2==0)
  digitalWrite(LED_BUILTIN, HIGH);
  else
    digitalWrite(LED_BUILTIN, LOW);

  /* Sending the array with data through serial*/

  Serial.print(measurements.timestamp);
 Serial.print(",");
 Serial.print(measurements.x+0.06);
 Serial.print(",");
 Serial.print(measurements.y+0.7);
 Serial.print(",");
 Serial.println(measurements.z-10.10);
}

Where does problem lie? How to resolve this issue?
Circuit Connections:

After a quick look at the Adafruit code I'd expect it to return zero or junk even if the ADXL stopped working. Is the Arduino subject to vibration as well? I'd try removing the accelerometer code and just transmit 'ABC' or something and see if it still stops due to a hardware problem.

If i remove the accelerometer code and transmit anything, it prints perfectly without any problem (with or without subjecting arduino to vibration)

I smell internal accelerometer problem. Internally they do a lots of approximations to produce the result - if acceleration changes too quickly probably they stop to work.

I've had I2C library problems in the past where the bus encounters problems, the Atmel library I used got stuck in a certain part of the I2C read code and really borked everything. Took ages to track that one down as it was intermittent. I detest I2C.

The Adafruit example has a delay at the end of the loop and you don't. Perhaps you might be transmitting too much data via the serial port. If you want maximum speed, try the SPI bus. You could try an other library, search on Github.com for adxl345. What do you want to do ? How many samples per second do you want ?

Maybe the vibration is shaking your wires loose and breaking communication...

@MasoodSalik - (a) From a quick read of the Arduino & Adafruit I2C code, there is no "hardening" to cope with I2C errors. (b) I see no evidence that the micro-controller is hanging - the code could be in a loop with no timeout (for example). It's important not to blame the MCU prematurely. I recommend you view the I2C signals, ideally using a 'scope, otherwise with a logic analyser(LA), both before and after the problem. Even better if your scope or LA can trigger on the start of the problem. (c) "x-axis=Samples y-axis=Samples" I doubt that - perhaps x-axis = samples & y-axis = values?

(d) It's unclear which axis the red (R), green (G) & blue (B) lines represent, and why they are centred on different values e.g. R centred on +10, B centred on 0 and G centred on -8. Please explain. (e) Compare the "stuck values" on each axis after the start of the problem on several tests. Is the G line always "stuck" on a very different value than R & B? (f) It would also be interesting if you can test increasing G-force on one axis at a time, and reviewing sensor response until problem occurs.

I have also your problem with adxl and micro did you solved?
can you help me?
my email : m.amir.kom@gmail.com

There is a known issue with the default "Wire" library, where if a certain transition is missed, the code goes into an infinite loop (rather than timing out). You possibly are reaching that situation. A possible reason is your printing of numbers at quite a high baud rate. The printing could be taking up so much time (itself causing serial interrupts as the serial buffer empties) that the I2C code doesn't execute in time the I2C interrupt.
You could try dropping the printing baud rate (something I wouldn't normally recommend) which means the serial interrupts would occur less frequently.
There is a library by DSS Circuits that has a time-out for I2C which may work around this issue to an extent:
http://dsscircuits.com/articles/arduino-i2c-master-library
Another thing you could try would be to summarize the data (eg. sample for 500 ms and then send the average), which would reduce the amount of serial comms.

Also you might try lower values for the pull-up resistors, like 4.7k.

So, my recommendations are:

Drop the baud rate (eg. to 9600 baud) and see if the hanging goes away
Summarize data rather than sending each reading
Try 4.7k pull-up resistors

If you have a logic analyzer you could look at the I2C signals and see if you can work out if the data is being transmitted as expected when the vibrations occur.
Saleae sell logic analyzers, the cheapest being $US 109. I use their (more expensive) analyzers extensively for debugging this sort of thing.


text:
I2C from two masters (ATtiny85, ESP8266) to one slave (ATmega328)
I've been working on a project with I2C protocol where an ATmega328 (Arduino) configured as slave, receives messages from an ATtiny (ATtiny85, ATTinyCore by SpenceKonde) configured as master, or from an ESP8266 (ESP-01, Arduino core) configured as master.
All using the standard wire library, powered with 3.3v (LM1117 regulator), SDA and SCL 4.7kohms pull-ups.
The ESP pins used are RX and TX, with 330ohms pull-ups.
Individually, it works (ATtiny to ATmega; ESP to ATmega), but when i connect the three on the same bus, after the first message it stops working and the ATmega doesn't receive more messages.

Code (modified for readability)
ATmega slave:
#include <Wire.h>

const int ADDRESS = 56;

void receiveEvent() {
    Serial.println(Wire.read());
}

void setup() {
    Serial.begin(9600);
    Wire.begin(MY_ADDRESS);
    Wire.onReceive(receiveEvent);
}

void loop() {
}

ESP master:
#include <Wire.h>

const int DISPLAY_ADDRESS = 56;
const int PACKET_SIZE = 1;
const int SDA_PIN = 1;
const int SCL_PIN = 3;

void setup(){
    Wire.begin(SDA_PIN, SCL_PIN);
}

void loop() {
    byte packet[PACKET_SIZE];
    packet[0] = 'e';
    Wire.beginTransmission(DISPLAY_ADDRESS);
    Wire.write(packet, PACKET_SIZE);
    Wire.endTransmission();
    delay(2500;)
}

ATtiny master:
#include <Wire.h>

const int DISPLAY_ADDRESS = 56;
const int PACKET_SIZE = 1;
// SDA = 0; attiny85 pin 5
// SCL = 2; attiny85 pin 7

void setup() {
    Wire.begin();
}

void loop() {
    byte packet[PACKET_SIZE];
    packet[0] = 'a';
    Wire.beginTransmission(DISPLAY_ADDRESS);
    Wire.write(packet, PACKET_SIZE);
    Wire.endTransmission();
    delay(1000);
}

After some research I found out that the wire library can only work with a single master, is this correct? And the esp can only work in master mode.
Am I doing something wrong, or is this simply not possible?
Are there any protocol alternatives for this design?
A single device that only cares about receiving messages, and multiple other devices that only care about sending messages to the central.
Thank you for your time!

Apparently someone made a ESP8266 I2C slave library: https://github.com/esp8266/Arduino/issues/1330#issuecomment-276210394. If this is true, I'd go with it and make the 328 the only master. There is a multimaster mode in I2C, but if the ESP cannot enable it then I think it is useless.

The problem is in your implementation. If you REALLY need 2 masters there should be a way to make it work.
At the moment the problem that I can see is that both masters continually poll the I2C data lines, effectively this means that the data on the lines is all mixed up and scrambled together. What could do is have 2 wires connecting both masters. When one of the masters is writing to the slave pull the line high, the other master should read this line as high, and not write data to the I2C lines. When the line drops low, it should then take its turn to write to the AtMega. This method would ensure only one master is using the data lines at one time. The implementation is pretty rudimentary and fairly crude and I'm aware the ATtiny may not have enough pins for this.
The best way to solve your problem I think is to have the ESP8266 as your single master, with your ATtiny and ATmega as slaves. Make the ESP poll the ATtiny for its data/instructions it wants to pass to the Atmega, and get the ESP to pass on this data or instructions to the ATmega along with its own data and instructions. This should be a robust and reliable fix.

When I started I had almost no knowledge of I2C or Wire lib, I just assumed that would be possible to have multiple masters and slaves.
For your first solution, it requires one wire for each master, correct? If I latter want to add another send device, it would require 3 extra pins on each master?
For your second solution, I think this is what I'll do, as I have no more pins available on the ESP for the previous solution.
If I started all from scratch, what would be a good implementation?

Well yes if you want each master to be able to pause every other master then yes, you'd need a line from each one to each of the others, you can imagine tgat this wiring would quickly become over complex. However there is another way to avoid having 2 lines and only having one. You give one of the masters greater priority.  Holding a single line high when it wants to talk, letting the other talk the rest of the time. This actually becomes very complicated on the coding side of things though (much more so than you'd initially think), so is best to avoid.

If you have 1 receive only device, and 2 send-only devices, why not make the receive-only device the master, but have it poll (periodically, repeatedly ask) the slave devices to send any data they have pending. That way, there is only one master, and it only asks for data when it's ready (that is, not receiving from some other device.)
One purpose of a master/slave bus system is to avoid contention (two or more devices talking at the same time.) The master tells each device when to send, and only listens after it asks.

The ESP8266 only supports master mode (I think), so at least one of the send-only devices has to be master.


text:
Weird output from chained 74HC595 shift registers
EDIT 4/2/18: The Arduino tutorial schematics have been corrected! See https://github.com/arduino/Arduino/issues/6433 for that issue.
I have a project where I am trying to load a 16-bit number onto an EEPROM using an Arduino hooked up to two 74HC595 Shift registers.
I'm loosely following this Arduino tutorial: https://www.arduino.cc/en/Tutorial/ShiftOut, but I'm getting unexpected outputs depending on the number I try to load into the register. I've reduced everything to as simple a setup as I can, and have spent several hours trying to figure out what the heck is going wrong... obviously to no avail.
Here is the schematic - with the exception that I moved the capacitor off of ST_CP (why would they put that in the tutorial?) to between power and ground:

Here is my code:
#define SHIFT_DATA 2
#define SHIFT_CLK 3
#define SHIFT_LATCH 4

void setup() {
  pinMode(SHIFT_DATA, OUTPUT);
  pinMode(SHIFT_CLK, OUTPUT);
  pinMode(SHIFT_LATCH, OUTPUT);

  int address = 0b1111111111111111;  // Case 1
//int address = 0b0000000000000000;  // Case 2
//int address = 0b0101010101010101;  // Case 3
//int address = 0b1010101010101010;  // Case 4
//int address = 0b0101100110101110;  // Case 5

  shiftOut(SHIFT_DATA, SHIFT_CLK, MSBFIRST, (address >> 8)); // Load first 8 bits
  shiftOut(SHIFT_DATA, SHIFT_CLK, MSBFIRST, address);        // Load second 8 bits

  digitalWrite(SHIFT_LATCH, LOW);
  digitalWrite(SHIFT_LATCH, HIGH);
  digitalWrite(SHIFT_LATCH, LOW);
}

void loop() {
  // none
}

Here is a picture of my breadboard setup with Case 1 loaded:

And here follows my test cases.

All 1's (1111111111111111). Looks good.
All 0's (0000000000000000). Looks good.
Repeated 01's (0101010101010101). Looks good.
Repeated 10's (1010101010101010). Output: 1010101000000000. First 8 bits match, last 8 are zeros. Huh?
Random sequence (0101100110101110). Output: all over the place. Initially the first 8 bits match as in Case 4, but on repeated resets of the Arduino the output changes, with some weird momentary flickering going on for some of the LEDs. If I press it enough times I can get it back to the initial output, but never what I expect. I am completely stumped. Here is an animated gif of this behavior running on the breadboard: http://i.imgur.com/KEwpSXe.gifv.

What could my problem be? I assume it's something very simple and I'm being an idiot.

One of the other serious (though more subtle) faults with that poor Arduino tutorial is the resistors are too low. Turn on too many LEDs and you draw more current through the 74HC595 chip than it can cope with. You can potentially try and draw up to approx. 109mA with those values but the 74HC595 can only manage 70mA total.

@Majenko If we instead had, say, 40 LEDs and 5 daisy chained shift registers, what resistor and capacitor values would be appropriate to not blow out the shift registers? Thanks!

@JoeFlip The same as for one. Each shift register is a discrete self contained block.

You should change your capacitors.
You only have 0.1µF instead of 1µF for the bulk capacitor (which really wants to be 10µF). In addition you should add 0.1µF (100nF) capacitors directly across the power pins of each chip:

My god, that actually worked. 10 uF across the power rails makes the output rock solid. Shows me how much to trust in a Nano's voltage regulation. Thank you!

It's not the Nano's regulation, it's the internal switching in the '595. The 0.1uF helps with the transient surges.    TPIC6B595 sinking current thru LEDs is also  a much better chip to use here. Shift a 1 in to turn on an output.

I have forum post about the 595 chip and a question and answer about SPI.
You can use SPI to do the transfer. This is faster and simpler than shiftOut. Also you need to bring the latch low before transferring the data.
Simple example sketch:
#include <SPI.h>

const byte LATCH = 10;

void setup ()
{
  SPI.begin ();
}  // end of setup

byte c;
void loop ()
{
  c++;
  digitalWrite (LATCH, LOW);
  SPI.transfer (c);
  digitalWrite (LATCH, HIGH);
  delay (20);
}  // end of loop

Actually not true re the latch - the latch is edge triggered (a simple RS-type flip-flop per bit) and loads the data from the shift register D-type flip-flops into the output latch RS flip-flops on a rising edge. It doesn't matter when it goes low as long as it goes from low to high at the point you want the outputs to change their state. Simple double buffering. True, it doesn't hurt to set it low early like that, but it's not a requirement. The only thing to watch is the minimum LOW or HIGH period of the RCLK (ST_CL on the diagram above) must be more than 20ns at VCC=4.5V.

I thought it was great how you used c as your variable -> c++

I haven't tried your code before heading off to work for the day, but it's worth noting that I don't see a change in behavior by either setting the latch low before shifting out data, or adding a delay(20) before and after each latch change of state.

@sa_leinad Thanks! Unintentional however. :) Scott: I can't reproduce your problem using actual hardware and your original code. However Majenko's suggestion of the 0.1µF capacitors could explain the problem.


text:
WiFiSSLClient will not connect to servers with LetsEncrypt certificates
I'm trying to send data from an Arduino program to an app running on Google App Engine but WiFiSSLClient.connect() always returns false.
This is despite

the server being up and running;
the code working when the web app was on a different server.

The only possible explanation I can come up with is that the App Engine app uses a LetsEncrypt certificate while the other server was using one by another company.
WiFiSSLClient client;
if (client.connect(server, 443)){
    // Connected to server
} else {
    // Failed to connect
}

Does anyone have any solutions to this problem? I had a look at WiFiClientSecure; it has the ability to set the CA certificate in code but this seems like a bit of a pain.

The solution is to update the certificates the WIFI 101 Firmware Updater tool (in the Arduino IDE).

Install the FirmwareUpdater sketch, as described on the Arduino site.
Select Tools -> WiFi 101 Firmware Updater. Click on the Add domain button at the bottom, enter your domain and click Upload Certificates to WiFi module.

Upload the sketch to your Arduino. It should now connect to the server.


text:
How do I calculate sampling rate of external ADC?
I am wondering if someone could explain this to me.
I want to calculate sampling rate of external ADC.
I am using ADS8320 which has max sampling rate of 100kHz, with Arduino MEGA 2560.
SPI divider is set to 128, which makes SPI frequency 125kHz.
Baud rate is 115200 (I am not sure if this is important).
Thanks a lot!

If you have the ADC then you can write a little sketch to time it yourself. So you will know for sure.

To get an idea of the sampling rate write a loop that takes 10,000 measurements and time how long it takes. You have your sample rate, not perfect but gives you some idea.
long start = millis();
// the loop

Serial.print( 10000000/(millis() - start) );
Serial.println(" samples per second");

Easy.

Based on your set up, figure out the spi speed.
Take a look at the adc datasheet, figure out it's frame of transmission . Aka how many pulses per frame / sampling.
The product of the numbers in 1 and 2 gives you the minimum time per frame. The inverse of it is the maximum transmission in your application. That speed is cap by the devices own max sampling rate (100ksps).
Your actual sampling rate will depend on your specific application but it should not go above the number obtained in 3.
You may need to factor in other timing requirements as well so read the datasheet carefully. But the gist is the same.


text:
Servo motor sweeps beyond 180
I'm trying to get my servo motor to sweep from 0 to 180 degrees then back to 0 degrees for infinite amount of times. I using the following code but my motor keeps resetting when it get backs to 0 degrees (meaning it goes 0-->180-->0 then completes a 360 and starts over). Also the 0-180 degree sweep appears to be more of a 0-270 degree sweep. Anyone running into these problems?
int angle = 0;

void setup() {
  myservo.attach(9);
  myservo.write(angle);
}

void loop()
{
  for (angle = 0; angle < 180; angle += 1)
  {
    myservo.write(angle);
    delay (50);
  }

  for (angle = 180; angle > 0; angle -= 1)
  {
    myservo.write(angle);
    delay(50);
  }
}

Are you trying to have the servo sweep at a particular speed? Why not just use:
void loop()
{
  angle=180;
  myservo.write(angle);

  delay(500); //Allow 0.5 seconds for servo to complete it's move; adjust as necessary depending on servo's rotation speed.

  angle=0;
  myservo.write(angle);

  delay(500); //Allow 0.5 seconds for servo to complete it's move; adjust as necessary depending on servo's rotation speed.
}

Thanks. I tried this and it worked for 0.5 second delay but when I increased the time the servo makes a 360 again. it goes 180 degrees-->360 turn-->0 degree--> 180 then pauses-->360 degree turn and repeats.

Can you post a link to the exact servo unit you are using?

I purchased the Elegoo Uno Project Super Starter Kit                                             (http://www.elegoo.com/product/elegoo-uno-project-super-starter-kit/)

If that servo goes over 180 travel, something is wrong with it.

Is your servo the modified 360 degree type with no position feedback (meaning the internal feedback potentiometer has been disabled)?

Not that I am aware of. I made no modifications to it.

Is it a continuous rotation servo ? Can you give the brand and type and a link to where you bought it ?

I had a bunch of SG90 mini servos so I tried your code. My servos turn 0 -> 180 -> 0 -> 180 -> 0 -> 180, over and over. No 360 spins at all.

Maybe your servo is defect? (can you check with another servo?)
Maybe it is not getting enough power? (how are you powering it?) It needs at least 4.8V and at least 220mA
Maybe it doesn't get a strong clean PWM signal? (You'll probably need an oscilloscope to check this)


text:
How to use ESP8266 wifi shield as a hotspot?
I have bought a ESP8266 wifi shield and I want to use it hotspot, I have tried the examples that have been provided in Arduino IDE, and the shield is getting connected to my network and giving me a wifi but without internet access (like I can connect my phone to the shield but I cannot browse the internet).
Any suggestion please?
Thanks......

What examples have you tried? Are you trying to get internet access onto your phone by going through the WiFi shield and Arduino? Where is the Arduino getting access to the Interent that it could then provide that to your phone?

Connecting through the ESP8266 to the internet would require the ESP8266 to handle Network Address Traversal and/or routing, which is not officially supported.
However, if you are prepared to do a lot of work, it can be done. The performance and reliability is bad, but it can be done. See http://bbs.espressif.com/viewtopic.php?t=960 Note that this will require far more skills than running the examples in the Arduino IDE.


text:
NodeMCU keeps hanging after random time
I have tried almost everything but my NodeMCU keeps hanging after random intervals, it usually stops working after 2 days, but well... I will describe it's behaviour, what I mean by hanging is that the server stops responding to the assigned static ip, if I restart my modem or the node it works again, but this device is meant to be working endlessly and shouldn't stop working even if it has been connected during one week, I have tested it a lot, it has worked for 2 days, for 3 days, once it worked for 4 days without any problem, but after reconnecting it in another place, hanged again after almost 2 days. I started to think that probably the problem it's related to NodeMCU. So please I would really appreciate any helpful suggestion like assigning ip through the modem or something that can help. Thanks in advance.
The NodeMCU is connected to a usb power hub (A regular android phone wall charger), and it controls a relay.
Here is my code:
#include <ESP8266WiFi.h>

const char* ssid = "INFINITUM5607";
const char* password = "********";

int ledPin = 13; // GPIO13
int ledPin2 = 12; // GPIO13
int desconectado = 5;
int conectado = 4;
WiFiServer server(80);
WiFiClient client;

int counter = 0;
int count;

void setup() {
  Serial.begin(9600);
  delay(10);

  WiFi.mode(WIFI_STA);

  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, HIGH);

  pinMode(ledPin2, OUTPUT);
  digitalWrite(ledPin2, HIGH);

  pinMode(conectado, OUTPUT);
  pinMode(desconectado, OUTPUT);
  digitalWrite(desconectado, HIGH);

  connectWifi();

  Serial.print(F("Setting static ip to : "));
  Serial.println(WiFi.localIP());

  // Start the server
  server.begin();
  Serial.println("Server started");

}

void loop() {

  delay(200);

  if (WiFi.status() != WL_CONNECTED) {
    delay(100);
    digitalWrite(conectado, LOW);
    digitalWrite(desconectado, HIGH);
   connectWifi();
  }

  // Check if a client has connected
  client = server.available();
  if (!client) {
    return;
  }

  // Wait until the client sends some data
  Serial.println("new client");
  count = 0;
while(!client.available()){
delay(1);
count++;
if ( count > 1000 )
{
Serial.println("Abandoned Client");
client.stop();
return;
}
}

//Serial.println("new client");
//  int t = millis();
//  while(!client.available()){
//  delay(1);
//  if (millis()-t>130) return;
//  }

  // Read the first line of the request
  String request = client.readStringUntil('\r');
  Serial.println(request);
  client.flush();

  client.println("HTTP/1.1 200 OK");
  client.println("Access-Control-Allow-Origin: *");
  client.println("Content-Type: text/html");
  client.println(""); //  do not forget this one

  // Match the request
  if (request.indexOf("/switch") != -1)  {
    digitalWrite(ledPin, !digitalRead(ledPin));
    digitalWrite(ledPin2, !digitalRead(ledPin2));
    printSwitch();
  }else if (request.indexOf("/uno") != -1) {
    client.print("Canal 1 apagagado | Canal 2 encendido");
    digitalWrite(ledPin, HIGH);
    digitalWrite(ledPin2, LOW);
  }else if (request.indexOf("/dos") != -1){
    client.print("Canal 1 encendido | Canal 2 apagado");
    digitalWrite(ledPin, LOW);
    digitalWrite(ledPin2, HIGH);
  }else if (request.indexOf("/tres") != -1){
    client.print("Canal 1 apagado | Canal 2 apagado");
    digitalWrite(ledPin, HIGH);
    digitalWrite(ledPin2, HIGH);
  }else if (request.indexOf("/cuatro") != -1){
    client.print("Canal 1 encendido | Canal 2 encendido");
    digitalWrite(ledPin, LOW);
    digitalWrite(ledPin2, LOW);
  }else if (request.indexOf("/cinco") != -1){
    printIP();
  }else if (request.indexOf("/apagaruno") != -1){
    client.print("Canal 1 apagado");
    digitalWrite(ledPin, HIGH);
  }else if (request.indexOf("/apagardos") != -1){
    client.print("Canal 2 apagado");
    digitalWrite(ledPin2, HIGH);
  }else if (request.indexOf("/prenderuno") != -1){
    client.print("Canal 1 encendido");
    digitalWrite(ledPin, LOW);
  }else if (request.indexOf("/prenderdos") != -1){
    client.print("Canal 2 encendido");
    digitalWrite(ledPin2, LOW);
  }else if (request.indexOf("/canaluno") != -1){

    if(digitalRead(ledPin) == HIGH) {
      client.print("Off");
  } else {
    client.print("On");
  }

  }else if (request.indexOf("/canaldos") != -1){

    if(digitalRead(ledPin2) == HIGH) {
    client.print("Off");
  } else {
    client.print("On");
  }

  }

// Set ledPin according to the request
//digitalWrite(ledPin, value);

  // Return the response

  delay(1);
  Serial.println("Client disonnected");
  Serial.println("");
  client.stop();

}

void printSwitch(){

  if(digitalRead(ledPin) == LOW) {
    client.print("Canal 1 Encendido");
  } else {
    client.print("Canal 1 Apagado");
  }
  Serial.println("");
  if(digitalRead(ledPin2) == LOW) {
    client.print("Canal 2 Encendido");
  } else {
    client.print("Canal 2 Apagado");
  }
}

void printIP(){
  delay(100);
  client.print(WiFi.localIP());
}

void connectWifi()
{
  Serial.print("Connecting to "+*ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
  delay(500);
  Serial.print(".");
  }

  // config static IP
  IPAddress ip(192, 168, 1, 66);
  IPAddress gateway(192, 168, 1, 1);
  IPAddress subnet(255, 255, 255, 0);
  WiFi.config(ip, gateway, subnet);
  digitalWrite(conectado, HIGH);
  digitalWrite(desconectado, LOW);
  Serial.println("");
  Serial.println("Connected");
  Serial.println("");

  // Print the IP address
  Serial.print("Use this URL to connect: ");
  Serial.print("http://");
  Serial.print(WiFi.localIP());
  Serial.println("/");
}//end connect

Check the power source. If you're powering it via USB it is likely to malfunction over time, but if you use an external and stable power source you won't have that kind of problem.

What do you mean if I'm powering via usb, then how should I power it if I'm not using it's micro usb input? I'm using a wall power hub, like an android device charger.

I meant using a reliable external power source (which is probably what you're doing) as opposed to using your PC's USB port (as many people do, and it frequently results in that kind of problem). But even so, if you are getting it to work for 2 or 3 days straight, I would still check the power supply. To guarantee that is the problem, you can power it with a battery and see how it goes (just make sure to measure the current first and implement a sleep mode if necessary, otherwise it might run out of power too fast).

Is there the possibility of all this being a bug on the NodeMCU?


text:
Very long range wireless communication between two arduinos(500-1000 KM)
I searched for very long range wireless communications between two Arduinos, but can't find solutions. I don't live in USA, In my country there are regions, where GSM does not work.
I want wireless communication approximately 500-1 000 KMs.
What are options without GSM for that distance wireless communication(500-1000 KM)?

What do you want to send between them? How many bytes and how often?

I want to send text and voice, 4096 bytes in 1-5 seconds interval

Do you have a budget in mind for the initial build? Ongoing costs?

Satelite communication is expensive, but that can be used for voice and for short data messages. The short data messages are used for example by ships. Do you have a shortwave license for an extremely powerful transmitter ? As far as I know, everything else is illegal.

I don't have license, but I have budget.

Back in the old days, we used things called modems to connect computers across POTS.

Your country may not have GMS, but I bet you still have old land lines. In that case, you can use a land line + modem to connect the arduinos directly , no Internet involved, no ISP needed, no overhead, no lag, nothing. It's just one Arduino at each end of a very long cable. No TCP/IP needed, but you need your own protocol to keep data in sync and filter out errors. There is lot of well proven ones from the golden era of BBS.
I search Aliexpress, I didn't find any modem suitable for direct conection with Arduino, but there is a lot of USB modem like this:

I don't know if they can work with Arduino. I'm afraid that they are win-modem only.
What it really works with anything is a traditional modem, like this model from Multitech (not an endorsing):

You will need a RS-232 level converter however, because RS-232's voltages can go up to 25V. The converter avoids you to deal with the peculiarities of the RS-232 standard and DB-9 connector.

And a cable, of course.
You can develop and test your project using a null modem cable, to connect both Arduinos, a few meters apart, without need of a land line.

What are options without GSM for that distance wireless communication(500-1000 KM)?

1) use the internet;
2) use narrow band transmission, like qrp;
3) use relays;
4) use satellite phones;
5) use a high-powered lw transceivers.
6) ...


text:
Simulate V1838B IR LED output
I have a HDMI switcher which uses a TL1338 IR LED that's connected via a 3.5mm audio jack. It has its own remote for switching between the inputs, but I want to use my TV remote.
In order to do that I want to connect the IR led to an ATTiny85 to receive the input and send the 'translated'code to the switcher.
When analysed with an oscilloscope it seemed that Arduino Libraries output a PWM signal, while the TL1838 outputs a digital signal. Is there a way to simulate a TL1838 signal?
Original situation:

Goal situation with ATTiny85.

What you want to do is send "unmodulated" IR Codes, but the library is trying to modulate them with a 38khz carrier. (The TL1838 device has a built-in demodulator.)
While your question is not a duplicate, this answer applies.

Thank you very much. Now that I have the term unmodulated I can research more in the right direction as well. It's also a very complete answer.


text:
How to send information from Arduino?
I plan to make an air quality monitoring system that uses Arduino uno, but I can't decide how I will be able to distribute the air condition and harmful gas concentration info and have it available to other people.
Aside from using a GSM module to text individual persons and making a new website to chart the data from the Arduino, what else can I use to receive information that my Arduino sensed to people's smartphones/computers wirelessly?

Use a nodeMCU: faster, more memory and WiFi included. You can even run a little web server from it.

what else can I use to receive information that my Arduino sensed to people's smartphones/computers wirelessly?

take a different route. get the information to a pc (or to a server through a pc) and you have much more flexibility.
there are many ways to get that information to a pc, like serial, spi, i2c, acquisition cards, wired / wireless, ....

There is a Wi-Fi module named "ESP-01" (which uses the ESP8266 microcontroller) and it comes ready to be used with Arduino. But better than that, I think, is that you can program it directly via Arduino's IDE if you flash it with NodeMCU's firmware. You can also use a NodeMCU instead of Arduino, but ESP-01 has the advantage of being much, much cheaper.

You can use a pair of ESP8266 WiFi Transceiver modules (one as the client and the other as the server).
There are a few guides to getting started with the ESP8266 out there, which generally contain some helpful tips.
I also found this fairly straightforward ESP8266 – Wireless Weather Station with Data Logging to Excel project which illustrates the principle of using a pair of ESP8266 modules as client and server.

Others suggest ESP8266, but I think it's now outdated, there's a new and improved version of it available named ESP32, it's better in basically every way (faster, more RAM, ROM etc.), not that much more expensive and can still be programmed using the Arduino IDE, that means programming it just as simple as programming an ESP8266.
Disclaimer: ESP32 Arduino core is still under development, some less frequently used features might be experimental or missing.


text:
ESP-01 adapter and logic level converter
I read that I'll need a logic level converter like this to run an ESP8266-01 from the Uno.
But I saw this ESP adapter:
http://www.ebay.com/itm/ESP-01-ESP8266-Serial-Wi-Fi-Wireless-Adapter-Module-3-3V-5V-Compatible-Arduino-/282524471281?hash=item41c7c54ff1:g:wp0AAOSwQ59ZaClP
Two questions:

The ESP-01 has 8 connections but this has only 4, how come? Will I get the same functionality?
If I'll use this adapter, then I won't need the logic level converter?

"with an integrated logic level converter like the wemos d1 mini" ... please show me the schematics and point to the logic level converter.

My electronic background is limited, but with the wemos you don't need any logic converter for the ESP so I can only assume that it's built in. @yeti

I'll just move this to a comment: save yourself time and get an ESP module without any extra parts like the wemos d1 mini.

The module has a 3.3V voltage regulator circuit and 5v-3.3v onboard level conversion circuit.
Yes, the module can be used with Arduino UNO R3 or compatible board without needing an additional level converter, as it is integrated in the module.
The module has Vcc, GND, TX and RX, so it means it uses a serial protocol for Arduino communication (and you will need two pins in the Arduino). Other pins in the ESP-01 are not needed in this scenario, but you still have access to them via the 8-pins female connector on the module.
It's totally plug and play.
Addendum: The old way
This how you connect a standard ESP-01 with an Arduino. The module you are looking at include all the resistors and also connect the CH_PD pin to Vcc. You only need to connect four pins. It saves you time, money and space.

Why the other pins are not needed?

The eight ESP-01 pins are: Vcc, GND, TX, RX, RESET, and two GPIO that you will not use (because they are only accesible from code running in the ESP-01 itself. Less pins means less worries.

Are those resistors enough to lower the logic level? No need for a level converter? It's a little funny how such a popular board is so complicated to use.

@kuhaku. The ESP01 is being powered by the Arduino 3.3V output pin. In some cases, you can connect two devices, one with 5v logic, the other  3.3v 5v tolerant.

The ESP-01 is a microcontroller that works only with 3.3V. If you don't use a logic converter, it will not work correctly with 5V on TX and RX and you might even damage your module if you use it like that. So answering your second question, the important thing to keep in mind is that you need to power it with 3.3V and the logic level of the data you send must also be 3.3V.
As for the number of pins, the 4 pins are for VCC, GND, TX and RX. These are the only ones you'll need to connect with Arduino. The other pins on the ESP-01 are CH_PD, RST and two GPIOs.
(I'm not sure if you need to connect any of these while using it with Arduino, but in my experience using it standalone i know CH_PD must be connected to VCC in operation mode, and RST must be connected with GND on flashing mode.)

I used in one of my projects, instead of a logic level converter, some voltage dividers on the pins, Arduino inputs don't mind the 3.3v, it works just the same.


text:
Using multiple sensors on ESP8266 Wifi module
I have an ESP8266 ESP-01 WiFi module.
I have a project where I need to use the following and send their data to a firebase database.
2x Force Sensitive Resistors(Sensor)
1x GPS module
My question is what GPS module can I use to send GPS location thru the ESP8266 Wifi module. My ESP-01 has only 2 GPIO. What should I do so I can use 2 FSR and GPS module at the same time send all 3 data to firebase realtime database.
Thanks

I would go for an i2c A/D converter, example ADS1015 (4 analog input, 12 bit) and connect that to the ESP-01.
Ref.:
https://en.wikipedia.org/wiki/I%C2%B2C
https://www.youtube.com/watch?v=6IAkYpmA1DQ&t=32s

Hello thank you for response. I searched this device and does this work like a 'GPIO' extension? Since ESP-01 only have 2 if I use this it will have 4 inputs? What is the connection when I use it on ESP-01?
http://www.esp8266learning.com/wp-content/uploads/2016/09/wemos-ads1015_bb.png

It has 4 GPIO, https://acrobotic.com/media/wysiwyg/products/esp8266_esp01_horizontal-01.png . And yes ADS1015 uses a i2c communication, https://en.wikipedia.org/wiki/I%C2%B2C, an universal serial buss where you can connect several devices to.

If I will use a different esp version NodeMCU V3 ESP8266 ESP-12E will it give me more GPIO slots? I checked them and found out that the ADS1015 price is closer to a new esp. What do you think? I just need enough slots for 2 FRS and 1 GPS module. Thanks

The ESP8266 chip only have one ADC (Analog input). And yes it will give you more I/O pins. So its the demand for two FRS that causes the demand for an alternative.

The ADC analog input is for the FRS or the GPS? Sorry Im really lost right now. Im trying to use this https://imgur.com/Rk67hI1 Will this be enough to power 2 FRS and a gps module? Thank you for your patience...

ADC = Analog to Digital Converter = Analog input that can measure voltage. And I assume that the FRS is analog resistors? Oh and the NodeMCU is nice, I prefer WEMOS D1, but it's quite the same

I think the NodeMCU got 1ADC and WEMOS got 11 Digital I/O pins
1 Analog Input pin which I think not enough for 2 FRS which uses ADC pins what do you suggest?

If I'm going to help you, you have to work also, not just asking! And I can't see that you give credits. So google the words "ESP8266 ADS1015 arduino"

I apologize. I guess I got too dependent on your replies and haven't done my part but thank you for still replying even though im kinda annoying. I have decided to use an Arduino UNO r3 which have 5 ADC slots and gonna use the Esp8266 esp-01 to send the data to firebase. Thank you for helping.

@Snoopy You are welcome and if you need any help in the future you are welcome, and the choice you have made is a good one. And one thing that also drive one to answer is to get credit for it :-) its the arrows to the left of the discussion.

You really need something external to both provide the analog inputs for the force sensors and the serial communication for the GPS module.
The simplest "something" is another microcontroller.  Ideally one with two UART ports.
You can then:

Communicate between the microcontroller and the GPS with one UART
Sample the FSRs with the microcontroller
Format and send the data to the ESP-01 through the other UART

Using SoftwareSerial you chould just about do it with an Arduino Uno (though you'd have to disconnect whatever was on the hardware UART every time you wanted to program it), but ideally something with more UARTs would be better, such as a Mega2560.
A halfway house between the two would be a board based around the ATMega32U2 which uses a direct USB connection for programming leaving the hardware UART free to be used permanently. However you'd still need to use SoftwareSerial to emulate the second UART (maybe best for the GPS since it's then only used for receiving).

Why not just write the sensor-handling code on the ESP8266, using an external ADC to work around the single-ADC on the ESP8266? The ESP is quite capable.

@josecanuc The chip is capable, but the ESP-01 is seriously lacking in IO pins. It has the UART pins and two GPIOs that are used to select the boot mode, so you have to be very careful with them. Best to stick to UART only.

@Majenko Thanks for the response I am still new to embedded systems and somehow i cannot understand some of it but I have an USB to TTL UART and Arduino UNO to use. My code is currently programmed in the wifi module using the GPIO2 as the sensor #1. i do not know where to plug the sensor#2 and gps module. If I plug them at the arduino or UART how will they send data since the code is inside the wifi module. I am confused Sorry im beginner

@Majenko If I will use an NodeMCU V3 ESP8266 ESP-12E instead will it be enough to run all 2sensors and 1 gps module?

Unless it has an added external ADC chip you still only get 1 ADC channel. However it is possible to add an external ADC chip to it for more channels. The GPS should be able to attach directly.

Thanks! May I know the difference between the ADC slot and GPIO slot? So I need 2 ADC slots for the FRS and the GPS will attach to the GPIO? This is the exact product im trying to buy https://imgur.com/Rk67hI1

FSRs are analog. You need to connect them to an analog (ADC) port. The GSM is UART. You need to connect it to a pair of UART pins or a pair of GPIO pins which you emulate UART on with SoftwareSerial.

I understand now thank you. Last question what ESP8266 can you suggest that has atleast 2 ADC pins for FSR and some GPIO for the GPS? There are so many too choose from and i dont know what to use best.

No ESP8266 has more than one ADC pin. You may find a board with an external ADC chip added but I don't know of one of hand. Wemos and NodeMCU are probably the boards to look at.


text:
How to switch on or off up to seven devices individually?
Is there a way to turn on or off the power supply of up to seven hard drives with the help of an Arduino? Or maybe there is another way to ultimately - but restorable - prevent read/write access to the disks.

Internal or external? External or internal power supply? Where you want to cut power? At mains or near to the disk?

To turn off a harddisk, you can give it a command to do so. Turning a harddisk off might not lengthen its lifetime, but it will reduce power.

Can't vote to close on the first day, so here is some advice for this question.  Do some quick research on how Arduino can be used to control 5V relays, then write some Arduino code.  Come back and edit this question to show that code and describe how you would put it together, then ask a specific question about Arduino wiring or code.  If you have some relays on hand, then actually put it together.  If there is a problem with the Arduino code then put that in the question very specifically.

Why ? Please explain why do you want to this. What is your goal ? Your question has a typical xy-problem aura hanging around it: http://xyproblem.info/

Switching power on and off to hard drives is not as simple as you may think.
First you have three voltages to control - 3.3V, 5V and 12V, and on top of that you have (ideally) pre-charging for the 5V and 12V pins. The power-on sequence would ideally be:

Power up 5V and 12V pre-charge
Power up 3.3V, 5V and 12V main power

That's 5 poles for one drive (although you can get away without the pre-charge).
So you would be switching at minimum 3 power signals per drive. For 7 drives that would be 21 power signals that need to be switched.
HOWEVER
Switching off power to a hard drive using mechanisms that aren't directly under the control of the operating system can cause file-system corruption and data loss.
The operating system caches data internally and writes it to the hard drive when able to. If the hard drive is turned off while there is still data cached that data will never get written to the hard drive. Worse still, if you turn it off whilst it is writing the file-system could become irrevocably corrupted (depending on the file-system in use and the resilience of it).
Most hard drives have the ability to power themselves down at a command from the operating system. I suggest you use this mechanism instead, since it is more reliable that blindly shutting off the power. Chances are your hard drives are already doing this, since most operating systems enable it by default.

Unmounting the drive will help to prevent data-loss. But I agree with you on the power-on sequence - will it be the same with SSD drives?

Sure, if you're on an OS that supports that. SSD AFAIK only has 5v and 3.3v, however powering those down would be completely pointless since they use next to no power when idle and produce no noise.

drives don't get 3.3v power, only the mobo does. drives use only red+yellow atx leads. the BIOS menu often allows for "power on HD delay", which is what i think you're hinting at in the "power up" notes...

@dandavis You should look at the specs of the SATA power connector. They have an orange wire (3.3V) as well as the red and yellow. True, 5V is (usually) optional, since most drives will regulate their own 3.3V (if needed) from one of the other rails, but the standard is to provide 3.3v.

@Majenko: not sata, that signaling 3.3v drives logic and needs not be switched; if you chop the molex power the drive will power down. use hot swaps...

@dandavis Check pins 1, 2 and 3: https://en.wikipedia.org/wiki/Serial_ATA#Standard_connector Those are power. 3.3 V is supplied along with the traditional 5 V and 12 V supplies. However, very few drives actually use it, so they may be powered from a four-pin Molex connector with an adapter. Few drives use it, but there are some. Not all drives work with an old Molex -> SATA adaptor since that doesn't provide 3.3V.

fair enough. i myself haven't seen such fancy drives. would switching the ground work or smoke?

The problem with switching ground is power likes to find its way through to ground through any other available route. So smoke is a possibility. That is why the SATA power connector staggers its pins so GND is connected before anything else.

An Arduino have 13 digital I/O pins so theoretically you can control 13 devices without any additional additional circuits.
You will probably need some circuits for the devices you want to control.

If you want to control them externally, I suggest buying e.g. an 8 channel relay. This way you can easily control them with the Arduino, and using external power for the devices to switch on/off.
If you want extra protection (especially with motors or expecting spikes on signals), use relays with opto-couplers.

Like that: https://arduino-info.wikispaces.com/ArduinoPower

Note that a typical 3.5" SATA hard drive has 3 power feeds - 12V, 5V and 3.3V, and all three need to be switched together. For 7 hard drives you'd need 21 single-pole relays, or 14 double-pole relays. Ideally you should also pre-charge the drive using the 5V and 12V pre-charge pins which you would provide power to before applying main power. That would raise it to 5 poles per drive, or 35 single-pole relays.


text:
SIM900A A6 module Arduino +CME error 58
I've recently bought a SIM900A A6 GSM module. Whenever I send a command it gives an error: +CME error 58.
Does anybody know what this means and how to solve it?

Post your schematic and a complete test sketch that show your problem.

I am also working on A6 and receiving the same error. I suspect it has something to do with the power supply. Will post my final answer once I have finished. Hassan (hassan.uh@gmail.com)

Which commands are you sending? From my experience it seems the command isn't supported. What happens if you issue just AT or ATZ?

Your sim card is probably protected by a PIN. Easiest way to get it working is to put the SIM into a normal phone and remove the PIN protection.

I've already done that it is receiving text messages and calls but its still giving this error

I had the same error.  My error was using the incorrect baud rate.  Set the baud rate to 115200.  Also, ensure that "Both NL & CR" option is selected for new line options.  After changing those settings, I had to reboot the A7, and wait for all the status messages to complete before I could send the AT command.


text:
Serial.print and char[] & null
I don't write a lot of C, so I'm always discovering things I only partly understand in the Arduino variety. One of these is how Serial.print handles char[].
Does Serial.print always require a null terminator? In the case of (say) Serial.print(88, DEC); is a null implied?
What happens in the following cases?
char buff[3] = "ABC"; // warned because no room for a null
Serial.print(buff);   // will absence of a null cause overrun?

char buff[4] = "ABC"; // now there's a null
Serial.print(buff);   // will the null character be sent too?

Any references appreciated.

When passing a char* you need to also pass some way of telling the function where it ends. In C that is usually the null terminator and that's all a null terminator is for. If that is missing then you get a buffer overrun.
The null terminator is not sent.

The "Serial" is a object/class and that makes it possible to have more than one function for Serial.print(). According to the type of the parameter the proper Serial.print() is selected.
This is the include file for the Serial.print(): Print.h
And these are the possibilities:

size_t print(const __FlashStringHelper *);
size_t print(const String &);
size_t print(const char[]);
size_t print(char);
size_t print(unsigned char, int = DEC);
size_t print(int, int = DEC);
size_t print(unsigned int, int = DEC);
size_t print(long, int = DEC);
size_t print(unsigned long, int = DEC);
size_t print(double, int = 2);
size_t print(const Printable&);

The reference for Serial.print() is short, but it explains pretty well that those different parameters are possible.
Your Serial.print(88, DEC); does not use a string of text, it uses the integer number 88.
As soon as a string of text is used, it should be zero-terminated.
The line char buff[3] = "ABC"; is indeed wrong, as you already wrote. That is one of the things of the 'c' language. The "ABC" gets a zero-terminater and that makes 4 bytes.


text:
Powering Arduino with 12V AC-DC Adapter Jack
I have 12V,700mA AC-DC adapter power jack. Is it ok power on arduino board directly using this power jack?
Though Arduino webpage suggests that arduino can stand and upto 20V power supply, I ask this because somewhere it is written that supply 12v, 700mA will end up the board to smoke and need a converter to make it 5V.
Is this correct?
Thanks,
Jyoti Raj

You can use that to power the Arduino through the barrel jack or the VIN pin.  The only way you end up with smoke is if you try to pull too much current through that setup.  Don't power any motors or solenoids directly off of output pins for example.

I am using barrel Jack. My setup is simple it just has temperature, moisture sensors and ZigBee attached.

I don't know how much power the ZigBee draws,  but if it is very much then you might consider powering it separately.  When you supply 12V to the barrel jack then there's a lot of power that has to be dissipated across the regulator as heat.  Since there's not a very big heat sink on the regulator on the Arduino this can cause it to get hot and shut down.  If you're just running the processor off the on-board regulator and nothing else is pulling power through it then you're fine at 12V.

Is it ok power on arduino board directly using this power jack?

it depends on the regulator used and the current you expect to draw from the regulator.
essentially, you want to make sure that the power dissipation over the regulator isn't too much. that power dissipation is proportional to the voltage drop over the regulator (Vin - Vcc) and the current draw (20ma + whatever you may draw from the arduino).
once you have that, check against the regulator datasheet to make sure that its temperature rise is within range.


text:
connecting multiple keypads
My project is to use an Arduino to control the lighting of a small apartment. My preferred option is to replace each wall light switch with a 4x4 membrane keypad (https://www.amazon.co.uk/Mirocle-Matrix-Membrane-Keyboard-Arduino/dp/B01LMU6OPG/ref=sr_1_19?s=electronics&ie=UTF8&qid=1504376458&sr=1-19&keywords=membrane+keypad). The UX would allow any keypad to control any light, eg. pressing 1-4 will set light 1 to brightness 4.
The problem I have is this will result require 4 x 8 = 32 pins, so I'm looking for alternatives.
So my questions:-
1/ Is there a simple pll to serial converter that I should be using to interface the keypads?
2/ Can I wire multiple keypads onto the same set of 8 pins? Only one keypad will ever be touched at one time.
3/ Are there simple serial versions of the classic membrane keypad.

Why? The only reason for that is to avoid searching the light switch in the dark, but that's not the case when you are in your own house. I can walk around mine in complete darkness and find the light switch for any room.

the short answer is "because it's my apartment and that's what I want to do". The slightly longer answer is "my apartment is never pitch black, also some lights are on photocell-gated, PIR motion detectors, and also the bottom left key will turn on a light with a single press. Luckily it's not a requirement of SE that every Arduino question needs to come with a justification for the project. Notwithstanding that, thanks for sharing that you can walk around your apartment in complete darkness with the SE community. We're all enriched by that knowledge.

As far as I know, you can connect multiple keypads of this type to a single set of 8 pins.  However, it seems like a lot of wire needs to be strung to get this to work, for each switch, 8 wires for the keypad, and two, or more, for power control.
Were I to do this project.  I would likely handle each switch independently, embedding a Pro Mini in each switch box along with an HC-12, or some such.  This means no wires are needed, any pad could control any switch, and expansion is much easier.
Of course, this is only what I would do, and you understand your own requirements far better than I.

many thx. I'm very open to alternative approaches, so I'll look into HC12. My architecture is the way it is because I want to run everything off a dedicated 12V circuit, and was trying to avoid having to distribute too much power.

@pinoyyid Good luck in your endeavour, whatever path you choose.
You will find the HC-12 to be very easy to work with, and highly reliable. I have used a few dozen with different networked projects of mine, and it is one of my favourite components.

Cool. Part of my architecture is to link the Arduinos with a controlling Raspberry. The HC-12 looks a great option for that aspect.

Or the 8 pins 4 will be connected to output pins to be enabled one at a time and 4 will be connected to input pins that get shorted to the input pins when the button is pressed.
The way to get a keypress from this will be to pull a single output pin high and then check all of the inputs, if any of them are high then the corresponding button is pressed.
If you want to treat all keypads the same then you can simply put them in parallel. If you want to treat each of them differently then you can parallel either the inputs or the outputs. But the other set needs to have a S2P or P2S shift register to get the proper data or make the correct pin high.
Though it will probably be simpler if each got their own microcontroller to poll the keypad and use a different longer range protocol to communicate to the main controller.

I will be treating all keypads the same.


text:
XBee s6b internet
For my project i need to send some data logged into a SD card to a remote server.
For this im using an XBee S6b wifi module connected to an arduino. ive had trouble connecting the xbee module to wifi. and also how can i set the ssid and other information through arduino?

You configure the XBee with AT commands. However there is one important thing to know about the XBee: it loves to be in "data" mode and won't stay in command mode while you play with it.
You need to first get into command mode by sending +++ with a delay each side of it:
delay(1000);
xBeeSerial.print(F("+++"));
delay(1000);

Then you can send commands:
// Set the SSID:
xBeeSerial.println(F("ATIDThis Is My SSID"));
// Set the wireless key:
xBeeSerial.println(F("ATPKTh!sI5mYk3Y"));

Once you have set the details you need to write the settings to flash and reset the XBee for the changes to take effect:
xBeeSerial.println(F("ATWR"));
xBeeSerial.println(F("ATFR"));

After each command you should really be looking for the "OK" response.
If at any time you don't sent anything for more than a few seconds the XBee will exit command mode and go back to data mode - at which point you will have to go back to command mode with the delays and +++.
It's easiest to configure the XBee using your computer and an XBee Explorer.
All the AT commands are detailed here.

thank you very much. so once i set the ssid and key and write them to the flash then how can i send the data that i want to a particular server over the internet. for example say that i have a server running and it waits for some POST data.

The X6B doesn't work like that. It is designed to create a virtual serial connection to another X6B. When not in command mode any data sent to it is sent to the destination IP and port. If it is in TCP mode and the connection isn't open it will open the connection and it will remain open until closed by the remote end. It is possible, if you are very careful, to get it to connect to a website to allow you to send a request, but it's not easy.

ok so can you suggest me something other than the xbee which i could use in my project. what i want is to send the data that i logged to a remote server over the internet

The most popular small module is the ESP-8266.

thank you very much i will look into it, if you know any place where i could quick start with a code please let me know.

There are examples all over the place, and hundreds of questions and answers on this site.


text:
Servos: attach() and write()
Arduino newbie here, so this question might sound too simple. I am trying to run a parallax continuous rotation servo using Arduino Uno. From the reference, I learned that the servo needs to be "attached" to one of digital pins with PWM capability, and the servo's speed can be controlled by write(0~180, 90=stop).
But I am having a hard time understanding the role of the PWM digital pin. If the servo's speed and direction of rotation is determined by write(), what is the role of attach(pin#)?
Thanks in advance!

attach tells the servo library which pin it should be writing to, this is stored somewhere in ram and write will look it up and communicate with the correct pin.
It's possible that you are using the other pwm capable pins for other purposes and suddenly having that library interfere with that is not a good thing.

First of all, you don't need to connect it to one of the PWM pins. Any digital output pin will work just fine.
Judging by the Arduino reference, attaching the servo to a pin is kind of like to declare a variable. By using myservo.attach(pin) you also give the servo a name (myservo in this case), and you can also add maximum and minimum values to the servo's rotation by adding two extra values to the end: myservo.attach(pin, min, max)
When you then use the myservo.write() function, the Arduino will "remember" what pin myservo is connected to, as well as the maximum/minimum settings for it.

Servos need the pwm on the control line, they compare the duty cycle value to the internal potentiometer and apply torque to correct any discrepancy

@ratchetfreak yes, but what I meant is that you don't have to use one of the pins with PWM labeled onto them. On the Arduino Uno, pin 3, 5, 6, 9, 10 and 11 are PWM pins, but you don't have to use one of these.


text:
Is it possible to connect nodemcu to mobile internet and how?
Guys i have done project home automation over Android in which i have use NodeMCU and relay to control switching of lights but this is a offline project.
Now I want to connect it with internet please tell me if I can connect NodeMCU to mobile WiFi.
I don't have router at home  please tell me if it is possible and how?

please explain "mobile WiFi", I suspect you are referring to whats aka mobile internet, 3G/4G, LTE and so on.

Yes i want to connect nodemcu to mobile internet

NodeMcu is made specially for wireless communication. You can connect it to wifi and hospot. You just need to pull in some library and pass you data to connect.

If you have a mobile wifi router, the nodemcu can connect to it just as it would connect to a fixed router.
If you want to connect the nodemcu to the internet without a mobile wifi router, you can use a gsm/gprs/3G/4G module, for example the SIM800L. (Provided the location has cell coverage.)

SIM800 is 2G = low bandwidth

I don't think switching lights will need a lot of bandwidth though.

I agree, it shouldn't.

I have a wifi library.This is how I connect the NodeMCU with that library.
#include <ESP8266WiFi.h>

#define WIFI_SSID "name_of_your_hotspot"
#define WIFI_PASSWORD "password_of_hotspot"

void setup() {
   Serial.begin(9600);
   WiFi.begin( WIFI_SSID,  WIFI_PASSWORD) ;

    Serial.print("connecting");

    while (WiFi.status() != WL_CONNECTED ) {
        Serial.print(".");
        delay(500);
    }

     Serial.println();
     Serial.print("connected");
     Serial.println(WiFi.localIP);
}

void loop () {
    // Your code
}

I used this tested and working code. Comment if any issue.
Make sure you import the library.
Hope this fixed your issue.
EDIT : 4th Jan 2018
I know this topic is old and maybe the OP solved this problem but I saw many people struggling with this same situation how to connect nodeMCU to an internet connection.
So, I created a medium post with detailed information on how to Connect ESP8266 module to the internet? You can read the story here (I am not paid or sponsored by this post I made this story to help the newbies)
If you still have any problem comment down below or add a response in my medium story.

Can u provide link for wifi library

The library is built in. Check in the list of library. Sketch > Include Library  > ESP8266WiFi

@Mayur did that work?

You don't need an external router or LAN to connect nodeMCU with Android or any other TCP/IP device. nodeMCU is capable of works as a WiFi access point, among other things.
You use he function wifi.setmode() to configure the WiFi mode to use. NodeMCU can run in one of four WiFi modes:

Station mode, where the NodeMCU device joins an existing network.
Access point (AP) mode, where it creates its own network that others can join.
Station + AP mode, where it both creates its own network while at the same time being joined to another existing network
WiFi off

When using the combined Station + AP mode, the same channel will be used for both networks as the radio can only listen on a single channel.
Now, to connect to Internet you will need something else. You can use a SIM800/SIM900 module, which let you conect your nodeMCU to Internet and send/receive SMS.
In this scenario, nodeMCU will connect directly to Internet for your remote connections, and will also works as WiFi router for local connections.
Keep in mind that nodeMCU is a lightweight router.

I Dont want to use gsm here is their any other option im using Android application to control relay i want to connect nodemcu to internet so that the signal from app can be accessible from anywhere can u tell me how to connect it with webserver

Can u tell me the way without using gsm to connect it to internet and send and receive signal over it

The viable solutions is GSM/3G/4G or WiFi. Satellite is a bit outside my knowledge.