switching two relays without delay using millis I have an Arduino-uno and two relays. Each relay has two switch on for two seconds at regular intervals.
total loop time relay 1 and relay2 is 1800 seconds.
relay 1 - 2 on,360 off,2 on,600 off,2 on,430 off,2on,402 off.
relay 2 - 12 off, 2 on, 358 off, 2 on, 606 off, 2 on, 478 off, 2 on, 338 off.
Can somebody help me on a code for this please.

this is a typical application for Blink Without Delay

// Turn leds on and off at certain times.
//
// When the digital output pin is HIGH, then the relay is off.
// When the digital output pin is LOW, then the relay is on.

enum actionEnum {
  RELAY1_ON,
  RELAY1_OFF,
  RELAY2_ON,
  RELAY2_OFF,
};

struct tableStruct {
  unsigned int time;
  actionEnum action;
} const table[] = {
  { 0, RELAY1_ON},
  { 2, RELAY1_OFF},
  { 2 + 360, RELAY1_ON},
  { 2 + 360 + 2, RELAY1_OFF},
  { 2 + 360 + 2 + 600, RELAY1_ON},
  { 2 + 360 + 2 + 600 + 2, RELAY1_OFF},
  { 2 + 360 + 2 + 600 + 2 + 430, RELAY1_ON},
  { 2 + 360 + 2 + 600 + 2 + 430 + 2, RELAY1_OFF},
  // remaining 402 for a total of 1800
  { 0, RELAY2_OFF},         // not needed, it is already off
  { 12, RELAY2_ON},
  { 12 + 2, RELAY2_OFF},
  { 12 + 2 + 358, RELAY2_ON},
  { 12 + 2 + 358 + 2, RELAY2_OFF},
  { 12 + 2 + 358 + 2 + 606, RELAY2_ON},
  { 12 + 2 + 358 + 2 + 606 + 2, RELAY2_OFF},
  { 12 + 2 + 358 + 2 + 606 + 2 + 478, RELAY2_ON},
  { 12 + 2 + 358 + 2 + 606 + 2 + 478 + 2, RELAY2_OFF},
  // remaining 338  for a total of 1800
};

const unsigned int totalTime = 1800;  // total amount of seconds for sequence
unsigned int seconds;

unsigned long previousMillis;
const unsigned long interval = 1000;  // 1000 ms is one second

const int relay1Pin = 2;
const int relay2Pin = 3;

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

  // The relay is off when the pin is high.
  // Turn output high before setting the pinMode.
  // Then the output changes from a floating pin to high,
  // and the relais will not be activated.
  digitalWrite(relay1Pin, HIGH);
  pinMode(relay1Pin, OUTPUT);
  digitalWrite(relay2Pin, HIGH);
  pinMode(relay2Pin, OUTPUT);
}

void loop() {
  // A one-second timer with millis
  if (millis() - previousMillis >= interval) {
    previousMillis += interval;

    // Scan table
    for (int i = 0; i < int(sizeof(table) / sizeof(tableStruct)); i++) {
      if (table[i].time == seconds) {
        switch (table[i].action) {
          case RELAY1_ON:
            Serial.println("Relay 1 on");
            digitalWrite(relay1Pin, LOW);  // low = relay on
            break;
          case RELAY1_OFF:
            Serial.println("Relay 1 off");
            digitalWrite(relay1Pin, HIGH);  // high = relay off
            break;
          case RELAY2_ON:
            Serial.println("Relay 2 on");
            digitalWrite(relay2Pin, LOW);   // low = relay on
            break;
          case RELAY2_OFF:
            Serial.println("Relay 2 off");
            digitalWrite(relay2Pin, HIGH);  // high = relay off
            break;
          default:
            Serial.println("Error, a bug in the sketch");
            break;
        }
      }
    }

    seconds++;
    if (seconds >= totalTime) {
      seconds = 0;
    }
  }
}


2.8" TFT Touchscreen Prohibits Access to Unused Pins This is probably a beginner question. You've been warned.

I recently purchased a touchscreen (http://www.adafruit.com/products/1651#tutorials) specifically because it left so many pins open to work with and I needed to hook up one, possibly two more items to my Arduino. However the touchscreen fits over the Arduino and covers all the pins.

How do I access the pins that the LCD isn't using?

To be specific, I will be adding a Galvanic Skin Sensor on two analog pins.

Several options:

Use wires to connect it rather than sticking it directly onto the Arduino.
Use a header extension to lift the display away from the other headers.
Use right-angle headers on the other pins.

get a Protoshield, a good one and put it between the arduino and the shield


Automotive Lighting Control Module I am looking for an Arduino-based solution for an automotive lighting application.

System Requirements:

Able to Operate in Automotive (Interior) Environment (12 +/- 2V DC    Voltage)
Minimum 3 12 V DC Inputs (Preferably 6)
Minimum of 3 12 V DC Outputs capable of operating standard automotive-style
relays. (Preferably 6)
Compact/Condensed Form-Factor

Finding an Arduino that runs on a 12 V power supply is simple, but finding one that can handle 12 V I/Os has proven tricky.

Using a relay shield for the outputs is straightforward enough, and would be a safe way to step up the output voltage and current (although current is of little concern, given I'm only going to powering the coil in a relay). But what to do about the inputs? I don't want a transistor on each input - that would get quite tedious and large very quickly. Using relays on both sides would work, but most shields are setup to receive coil activation signals from the Arduino and as such also can't handle 12 V inputs, so using a relay shield to step-down from 12 V to 5 V also seems problematic.

Is there an all-in-one I/O solution that can step-down incoming voltages for the board and step-up output voltages on the other side?

What are my best options? I'd prefer not to have to custom-make a shield for such a basic I/O application...

Any and all help is greatly appreciated!

A Logic Level Converter can step-down incoming voltages for the Arduino inputs and may also work to drive the relay coils. Heres an example of a 4 channel board:

https://www.sparkfun.com/products/12009

and there are also 8 channel boards:

http://www.ebay.ca/itm/8-Channel-I2C-IIC-Logic-Level-Converter-Module-Bi-Directional-for-Arduino-MF-/172424799119?hash=item282551a38f:g:6Q0AAOSwo4pYPDwg.

The boards are small and use BSS138 MOSFETs, which, according to the data sheet: http://cdn.sparkfun.com/datasheets/BreakoutBoards/BSS138.pdf can handle a maximum of 0.22A continuous current and a Drain-Source Voltage of 50V. The SparkFun link has lots of information about these devices. Normally, you would use them to translate between 5V and 3.3V but I don't see why you couldn't power the "high voltage side" with the vehicles 12 - 14V and the "low voltage side" with 5V from the Arduino.

I Suggest you to use esp8266 in order to control appliances over wifi and I want to know that why you want to use 12v power supply in  your project... Most of the programmable boards, sensors are only compatible with 5v...... So please think about that...


How to connect the INT pin of a MPU 6050? I am using an Arduino Leonardo together with a GY-521 breakout board (like this one, schematic) for an MPU 6050.

I am currently trying to get the DMP Version of the examples from Mr Rowberg to work.

For all my tests, I use these connections:

GY-521 ->  Leonardo
VCC -> 5V (3.3V has the same behaviour)
SDA -> SDA
SCL -> SCL
GND -> GND

The "raw" sketch works fine, I can read out the sensor data. For the DMP version I think I need to connect the INT pin to pin 3 on the leonardo, to allow the MPU6050 to trigger an interrupt.

But as soon as I connect INT to anything (pins 0 through 3), the sketches do not find the MPU6050 any more. (They report ""MPU6050 connection failed").

Is my wiring off, or is my chip defective, and even more important, how could I figure that out on my own in the future? =)

Edit:
The example source code says

/* =========================================================================
   NOTE: In addition to connection 3.3v, GND, SDA, and SCL, this sketch
   depends on the MPU-6050's INT pin being connected to the Arduino's
   external interrupt #0 pin. On the Arduino Uno and Mega 2560, this is
   digital I/O pin 2.
 * ========================================================================= */

The example does nothing (that I can see) to configure this pin.

Edit again:

I've borrowed an oscilloscope. SDA and SCL sit on 3.3V during normal communication, and I can see packets being exchanged. As soon as I connect the INT pin to any input pin on my Leonardo, both SDA and SCL go to ground. This means nothing to me, but maybe to someone else.

Possible problem: pin interference

  But as soon as I connect INT to anything (pins 0 through 3), the
  sketches do not find the MPU6050 any more. (They report ""MPU6050
  connection failed").

  Is my wiring off, or is my chip defective, and even more important,
  how could I figure that out on my own in the future? =)

If I'm reading the Arduino Leonardo schematic correctly,
Arduino D0 is Rx, Arduino D1 is Tx,
Arduino D2 is the I2C_SDA, and Arduino D3 is the I2C_SCL.

You're already using the I2C_SDA and I2C_SCL as bidirectional I2C communication;
connecting some other output pin (such as the MPU6050 INT pin) to either of those pins is going to disrupt that communication and then things won't work.

On most Arduinos, Serial.println() and Serial.read() and the reprogramming process use the Rx and Tx pins.
Perhaps connecting the MPU6050 INT pin to either of those pins also causes some sort of problem leading to things that don't work.
(Although the Arduino Leonardo actually uses its USB_D- and USB_D+ pins for both Serial.println() and reprogramming, so maybe it isn't really a problem for the Leonardo?).
I would avoid using those pins for anything other than serial communication, even though I'm not at all sure that would actually cause a problem on the Arduino Leonardo.

  The example source code says
  ... this sketch depends on the MPU-6050's INT pin being connected to
  the Arduino's external interrupt #0 pin. ...
  The example does nothing (that I can see) to configure this pin.

I assume you're using https://github.com/jrowberg/i2cdevlib/blob/master/Arduino/MPU6050/Examples/MPU6050_DMP6/MPU6050_DMP6.ino , right?

Interrupts are configured a little differently than I/O.
(In particular, "volatile" is critical to getting interrupts working right).

The part that configures that interrupt is in the setup() function:

void setup() {
    // ...

        // enable Arduino interrupt detection
        Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
        attachInterrupt(0, dmpDataReady, RISING);
    // ...
}

The "attachInterrupt(0, dmpDataReady, RISING)" line
configures the interrupt vector table and the configuration bits so that when something drives Arduino pin D2 (i.e., external interrupt source 0) from a low to a high, no matter what the Arduino is in the middle of doing, the Arduino puts that on hold, executes the dmpDataReady() function, and then the Arduino resumes where it left off.

I don't see how that ever worked, since "external interrupt 0" comes from pin D2, which on the Arduino Leonardo is connected to I2C_SDA, which we're using for I2C communication, so we can't use it for watching the gyro interrupt pin.

However, since the "attachInterrupt()" gets run long after the "MPU6050 connection failed" message gets printed out on your screen, a software bug in how the example code uses attachInterrupt() doesn't explain why you get that "fail" message printed on your screen.

what to do about pin interference

I would try either using some other pin, or try getting it to work without hooking that pin to the Arduino at all.

Using some other pin

I would try to assign a dedicated pin on the Arduino to the MPU6050 INT pin.
Maybe D9 would work?

I'm guessing on the Arduino Leonardo, the interrupt should be set up something more like:

// warning: untested code.
#include <PinChangeInt.h>
#include <PinChangeIntConfig.h>

// connect MPU6050 interrupt to Arduino D9
#define MPU6050_INT D9

void setup(){
    // ...
    // pin change interrupt
    pinMode(MPU6050_INT, INPUT);
    PCintPort::attachInterrupt(MPU6050_INT, dmpDataReady, RISING);
    // ...
}

Getting it to work without hooking INT to the Arduino

It's not at all clear that the Arduino really needs to be connected to the MPU6050 INT pin.
It appears that another option is for the Arduino to occasionally use the I2C communication to read the status of the MPU6050, which includes the current state of that pin.
That simplifies the hardware -- simply leave the MPU6050 INT pin unconnected.

the interrupt pin in the attachInterrupt command should be kept to #4 which is pin D7 as stated here "http://arduino.cc/en/Reference/AttachInterrupt" since we can't use pins D0-D3 the only left out option is D7 but the problem still persists. Somebody please solve this !!


How to display a number using SevSeg library on 4 digit 7 segment LED display I am getting error with this. It is displaying those segments which are not to be displayed, i.e., 3.141 is dark and other segments are red.

#include "SevSeg.h"

SevSeg sevseg; //Initiate a seven segment controller object

void setup() {
    byte numDigits = 4;
    byte digitPins[] = {2, 3, 4, 5};
    byte segmentPins[] = {6, 7, 8, 9, 10, 11, 12, 13};
    sevseg.begin(COMMON_ANODE, numDigits, digitPins, segmentPins);
    sevseg.setBrightness(1000);
}

void loop() {
    sevseg.setNumber(3141, 3);
    sevseg.refreshDisplay(); // Must run repeatedly
}

There are two main types of seven segment display:

Common Anode
Common Cathode

The common refers to the fact that one end of the LEDs within a digit are linked, and need to be connected to either Vcc or GND, depending on the type of the display (see below). The other end of each led (one per segment) is used to switch them on, and it is these that go to the Arduino pins, or LED controller.
Common Anode

The common end is connected to the Vcc line. If you wish to light a segment, then the input pin for that segment needs to be pulled LOW.

Source: Four multiplexed 7-segment COMMON ANODE LED
Common Cathode

The common end is connected to the GND line. If you wish to light a segment, then the input pin for that segment needs to be pulled HIGH.

It sounds as if you have the logic inverted, so the wrong segments are lit, when they should be dark, and vice versa.
Either that, or you need to invert the logic in your code, and for example if you are currently pulling a pin LOW to light up a segment, then you need to change your code to pull the pin HIGH.

Image sources:
Electronics-Tutorials
Common Anode/Cathode 7-segment displays

set the brightness to a value between 10 -100 not 1000..


Why it shows d2 was not declared in scope #define BLYNK_PRINT Serial
#include <SPI.h>
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <SimpleTimer.h>
#include <DHT.h>
#define BLYNK_PRINT Serial
#include <OneWire.h>
#include <DallasTemperature.h>
#define ONE_WIRE_BUS D2

OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
char auth[] ="your auth token";
char ssid[] = "your wifi name";
char pass[] = "your wifi password";

#define DHTPIN 2
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
SimpleTimer timer;

void sendSensor()
{
  float h = dht.readHumidity();
  float t = dht.readTemperature();

  if (isnan(h) || isnan(t)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }

  Blynk.virtualWrite(V5, h);  //V5 is for Humidity
  Blynk.virtualWrite(V6, t);  //V6 is for Temperature
}

void setup()
{
  Serial.begin(9600);
  Blynk.begin(auth, ssid, pass);

  dht.begin();

  timer.setInterval(1000L, sendSensor);
  Serial.begin(115200);
  Blynk.begin(auth, ssid, pass);
   sensors.begin();
}

int sensor=0;

void sendTemps()
{
  sensor=analogRead(A0);
  sensors.requestTemperatures();
  float temp = sensors.getTempCByIndex(0);
  Serial.println(temp);
  Serial.println(sensor);
  Blynk.virtualWrite(V1, temp);
  Blynk.virtualWrite(V2,sensor);
  delay(1000);
}

void loop()
{
  Blynk.run();
  timer.run();
  sendTemps();
}

Arduino pins are defined only by a simple number, with the exception that the analog pins are also named as 'A0' through 'A8' (or however many analog pins the specific processor has). Thus, D2 is not defined. If you mean to refer to Arduino pin 2, its name is just '2'. So:
#define ONE_WIRE_BUS D2  ->  #define ONE_WIRE_BUS 2


Ignore event until x minutes I have an arduino where I looking for an input event then do something. Unfortunately this input event can occur like 200 times and I only care about the first notification. Since I have a DS1302 timer handy in the circuit already for other purposes I was thinking using the minutes reading out of this to squelch this event.

Here is the code I come up with:

if (digitalRead(sensor_event)==HIGH)
  {

      if (RTC.read(tm)) {

              if(time_set)
                {
                       if (tm.Minute > time_pushed+5)
                           time_set=0; // Unlock
                 }
               else
                 {
                        if (tm.Minute >= 55)
                          time_pushed=0;
                        else
                          time_pushed=tm.Minute; // Set global volatile min value

                        print("Sensor event");
                        time_set=1;
                 }
      }
  }

About the seconds and hours I don't care all I need is if this event is detected then go ahead with a function and put it on a 5 minutes hold before checking it again.

The small issue here is the minute overflow. For example if the minute is just at 56 when this happens the time_pushed would be set to 56 then the time_pushed+5 would give 61 (which of course is never reached).

Is there a better way to code this? What is the name of this time issue I having to ignore an event until x minutes? What I found for this was mostly debounce but I'm sure this has to be handled by others sometimes too.

Thanks

Use the millis() function instead if you can accomodate a rollover after 50 days.

Take a reading of millis() at the start time.
time_pushed = millis() + 5 * 60 * 1000;   // 5 minutes into future.

The rest of your code shouldn't require too much editing.

Don't bother with the RTC, just use millis().  Or just convert the time in hours/minutes/seconds to a single number in seconds (i.e. UNIX timestamp) and use that.  Then use these time comparison macros:

#define time_after(unknown, known) ((long)(known) - (long)(unknown) < 0)
#define time_before(unknown, known) ((long)(unknown) - (long)(known) < 0)
#define time_after_eq(unknown, known) ((long)(unknown) - (long)(known) >= 0)
#define time_before_eq(unknown, known) ((long)(known) - (long)(unknown) >= 0)

Then do something like this in your main loop, with a variable unsigned long sample_timer that's initialized to 0 at the start of your program:

if (time_after_eq(millis(), sample_timer))
{
    if (event)
    {
        sample_timer = millis() + 5*60*1000;
        // handle event...
    }
}

These time comparison macros will properly handle overflow if you use unsigned long for your timestamps.


use button to select variable i have a need to use 3 buttons a a simple option/variable selector at sketch start up ...

Pretty much at startup , script must wait for button press ( one of 3 ) , when button is pressed , use that buttons predefined string value as a variable for the loop script further down .. if wanting to change the "variable" then a reboot is required ..

i know how to digital read in the buttons , but not sure how to

1) wait for one of the buttons to be pressed to then jump to main loop
2) Associate a "string" variable to each button

thinking about it i suppose a If/Else loop will be required for the Input 'wait" and then just if the digital input (button) is pushed then continue .. am i correct ?

Ideas or better way to do it ?

Thx
Greg

When I am searching for something inside a loop, I find that the
simplest thing to do is to just break out of the loop once I found it.
This was frowned upon in the days when structured programming was a hot
thing, but as long as it makes things simpler, you should not be ashamed
to break:

const int button_pins[] = {2, 3, 4};
const char * const urls[] = {"foo.com", "bar.org", "baz.net"};
const char * url;  // the selected URL

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

    // Configure input pins.
    for (int i = 0; i < 3; i++)
        pinMode(button_pins[i], INPUT_PULLUP);

    // Find first button pressed.
    int i;  // button index
    for (i = 0; ; i = i==2 ? 0 : i+1) {
        if (digitalRead(button_pins[i]) == LOW)
            break;
    }

    // The button index selects the URL.
    url = urls[i];

    Serial.print("Selected URL: ");
    Serial.println(url);
}

void loop() {}

The for loop above is written as an endless loop (no end condition).
The expression i = i==2 ? 0 : i+1 means: “if i is 2, make it 0,
otherwise make it i+1”. In other words, we are endlessly looping i
over 0, 1 and 2.

Now, it may well happen that you actually do not care about which button
was pressed once you have selected the proper URL. In this case, you can
use the URL pointer as a “flag” that tells you when you can end the
loop:

// First button pressed selects the URL.
for (int i = 0; !url; i = i==2 ? 0 : i+1) {
    if (digitalRead(button_pins[i]) == LOW)
        url = urls[i];
}

Where !url means “the URL has not been found”. This works because the
C runtime initializes url to zero, which is interpreted as false in
boolean context.

Addendum: If you are likely to add new button/URL pairs, you can
make this easier by structuring the list as an array of structs:

const struct {
    int pin;          // pin number
    const char *url;  // associated URL
} buttons[] = {
    {2, "foo.com"},
    {3, "bar.org"},
    {4, "baz.net"}
    // etc. just add to this list as needed.
};
const size_t button_count = sizeof buttons / sizeof buttons[0];

Then the search becomes:

for (int i = 0; !url; i = i==button_count-1 ? 0 : i+1) {
    if (digitalRead(buttons[i].pin) == LOW)
        url = buttons[i].url;
}

You can try this. The comments in the program explain quite well.

const int buttons[3] = {2,3,4}; // buttons pins

int butStatus = 0;

void setup() {
  pinMode(buttons[0], INPUT); // declaring pins as inputs
  pinMode(buttons[1], INPUT);
  pinMode(buttons[2], INPUT);

  while(butStatus<=0) //waiting for a button to be pressed
  {
    for(int i=0; i<3; i++) //running trough the 3 buttons
    {
      if(digitalRead(buttons[i]) == HIGH)
      {
        butStatus = i+1; //set variable to the button that has been turned on
      }

      else
      {
        butStatus = 0; //if there is no button press, keep the variable at 0
      }
    }
  }
}

void loop() {
  //variable butStatus is now equal to the button that has been pressed
}


Arduino and SIM900 unavailable all the time I have the a problem with my arduino MEGA 2560 and the SIM900 module.
I want to save the outputs of the AT commands, but I never get a chance. If I print mySerial.available() I only get 0.
Sending SMS works fine on the other hand.

Initializing...
AT+CMGF=1
AT+CNMI=2,2,0,0,0

OK
Done
AT+CMGL="REC UNREAD"

OK
0
0
0
0
0
0
0
0
0
0
0

This is the sketch I use:

#include <SoftwareSerial.h>

//Create software serial object to communicate with SIM900
SoftwareSerial mySerial(11, 10); //SIM900 Tx & Rx is connected to Arduino #7 & #8
String incoming="";
String incoming2="";
String messages="Test";
String auth_num="+49xxxxxxxxx";
char incoming_char=0;

String response = "";

const byte numChars = 32;
char receivedChars[numChars];
boolean newData = false;

int period = 6000;
unsigned long time_now = 0;

void setup()
{
  //Begin serial communication with Arduino and Arduino IDE (Serial Monitor)
  Serial.begin(9600);

  //Begin serial communication with Arduino and SIM900
  mySerial.begin(9600);

  Serial.println("Initializing...");
  delay(1000);

  mySerial.println("AT+CMGF=1");
  mySerial.println("AT+CNMI=2,2,0,0,0"); // Decides how newly arrived SMS messages should be handled
  //mySerial.println("ATE0");
  updateSerial();
  Serial.println("Done");

  //sms_versenden("xxxxxxxx", "text");
}

void loop()
{
  updateSerial();
  Serial.println(mySerial.available());
  if(millis() - time_now > period){
    time_now = millis();
    if(sms_erhalten()){
      sms_autorisiert();
    }
  }
}

void updateSerial()
{
  delay(500);
  while (Serial.available())
  {
    mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
  }
  while(mySerial.available())
  {
    Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port
  }
}

void sms_versenden(String rufnummer,String text)
{
  mySerial.println("AT"); //Handshaking with SIM900
  updateSerial();

  mySerial.println("AT+CMGF=1"); // Configuring TEXT mode
  updateSerial();
  if(rufnummer.startsWith("0")){
    rufnummer.remove(0,1);
    mySerial.print("AT+CMGS=\"+49");
    mySerial.print(rufnummer);
    mySerial.println("\"");
  }else if(rufnummer.startsWith("+49")){
    mySerial.print("AT+CMGS=\"");
    mySerial.print(rufnummer);
    mySerial.println("\"");
  }else{
    return;
  }
  updateSerial();
  mySerial.print(text); //text content
  updateSerial();
  mySerial.write(26);
}

boolean sms_erhalten()
{
  mySerial.print("AT+CMGL=\"REC UNREAD\"\r");
  //recvWithEndMarker();
  Serial.println(mySerial.available());
  delay(30);
  while (mySerial.available()){
    String inData = mySerial.readStringUntil('\n');
    Serial.println("Got reponse from SIM900: " + inData);
  }
  /*if(mySerial.available()>0){

    incoming = mySerial.readString();
    Serial.print(incoming);
    delay(10);
  }*/
  updateSerial();
  if(incoming.startsWith("+CMGL:"))
  {
    return true;
  }
  else{
    return false;
  }
}

void recvWithEndMarker() {
    static byte ndx = 0;
    char endMarker = '\n';
    char rc;

    while (mySerial.available() != 0 && newData == false) {
        rc = mySerial.read();
        updateSerial();
        if (rc != endMarker) {
            receivedChars[ndx] = rc;
            ndx++;
            if (ndx >= numChars) {
                ndx = numChars - 1;
            }
        }
        else {
            receivedChars[ndx] = '\0'; // terminate the string
            ndx = 0;
            newData = true;
        }
    }
}

void showNewData() {
    if (newData == true) {
        Serial.print("This just in ... ");
        Serial.println(receivedChars);
        newData = false;
    }
}
String getResponse() {
    while(mySerial.available()>0){
        response += mySerial.read();
    }
    return response;
}

Thanks in advance for every idea.
Bravodelta

Rather than creating your own function used SerialEvent function in arduino. It acts as a serial interrupt in arduino. For example:

String inputString;
void serialEvent() {
      while (Serial.available()) {
        // get the new byte:
        char inChar = (char)Serial.read();
        // add it to the inputString:
        inputString += inChar;
        // if the incoming character is a newline, set a flag so the main loop can
        // do something about it:
        if (inChar == '\n') {
          Serial.Println(inputString);
        }
      }
    }


Execute Code on power off? Arduino newbie here.

I'm thinking about building an Arduino-based light switch to control the Philips Hue light system in my living room. I have standard wall light switches that power ceiling lamps, and I basically want all Hue lamps that are scattered around the room to be on when the switch is on, and off when the switch is off, so that I don't necessarily need the app or the Hue remote to turn the room's lights on.

My idea is to install an Arduino on the ceiling instead of a normal lamp, so that its power supply is switchable through the light switch.

I would configure it as a Hue remote control, e.g. with ArduinoHue; if all works well, this would control the Hue lamps directly via ZigBee or via WiFi through the bridge - in both cases without having to use additional wiring.

Whenever it gets power, I would have it turnOn() all lamps, and whenever its power supply is turned off, I would have it turnOff() all lamps.
The first part seems simple to me, the second part - not so much.

So here's my question:
Can I execute code in the event of the Arduino losing power, i.e. turn off my Hue lights with its last energy before shutting down? Is there maybe some hardware configuration that would allow me to detect the power off event and retain enough energy through a battery or capacitors to still run the code?

I have never worked with Arduino before, but I do have some colleagues that can help me out when there's trouble.

You could do what you want as you describe it, but are making things harder for yourself that you need to. If you can access the circuit from the switch at or near the switch (which should be 'easy' in most cases) then your system does not have to be depowered when the lighting circuit is as you will have access to the mains AC voltage on either side of the switch.

If you do wish to depower the processor when the lights are turned off you can easily add either a backup battery or a capacitor that runs the processor for "long enough". You can also run a processor in "sleep" mode at extremely low power so that it is always running so have no 'wakeup time". And it is possible to power up a processor so that the delay is not noticeable for practical purposes.

However, as Hue Bulbs are Zigbee controlled, with provision ofr both iOS and Android control,  you should be able to control them via Zigbee directly without any connection to their wiring.

Hue control

Hue specifications

Execute Code on power off?

that's like wanting to be alive while dead, or in sleep while awake, :)

the typical way is to wave up periodically; sometimes, run the mcu at very low speed.

the 2nd approach is quite doable on mcus with external r/c oscillator -> you can use a few gpio pins to affect the equivalent R in that r/c oscillator;

for crystal-based oscillator, your options are limited to pll, or fixed dividers if the system offers that option.


How can the Arduino check if it is connected to a PC and the PC is on? I have been searching around the Internet to find if there is a way to check whether an Arduino is connected to a PC or not.

For example: if my PC is turned on, the Arduino will listen to any serial commands it receives, BUT if my PC is turned off, the Arduino will receive some random characters.

How can the Arduino check if it is connected to PC and the PC is on?

As suggested by Paul & Gerben, you could check the 5V USB line to see if it has a voltage or not.

I am assuming from your question that the Arduino is not powered from the USB line. I am also assuming that the USB port is not powered when the PC is turned off.

All you have to do is connect VUSB to a digital input through a resistor like so:

Alternatively, you could have the computer send a pre-determined message telling the Arduino that its alive.

If the Arduino receives this message then it lights up the LED on pin 13. If the Arduino hasn't received the "I'm alive" message for a while (ie. a timeout) it then turns off the LED.

A simple PC program could be written to automate this task.

jumper reset -> ground and rx -> tx (with power disconnected)
connect power, open serial monitor in arduino ide and type anything in and input. if the serial monitor echoes what you typed in, then your connection is good and you should look elsewhere for problems.

Found this solution on the arduino.cc community site.


Connect an Arduino directly to RGB LED strip I am totally new in this area. I have an Arduino mega 2560 and I have this LED RGB Strips. I would like to know if there is any way of connecting the Strips directly to the arduino. The strip has already solded 4 cables:

one cable on 12V
one cable on G
one cable or R
one cable on B

I don't have additional equipment. Also, I can't find anything online which uses the same type of strips as mine. Many thanks.

Those LED strips are multiple parallel chains of 3 LEDs in series, with a 150Ω resistor for each chain.  The chains are arranged as common anode, and the chains are grouped into the three colours for the cathodes.

You require a power supply with enough current to supply all the LEDs (such as the 3A one supplied in the package).

Further, you require a method of switching each of the three channels, such as n-channel MOSFETs, which can handle enough current for each channel (one MOSFET per channel) - that is, 1A per channel if the whole strip takes 3A (but you can "derate" it by providing capacity for more current which helps alleviate some heat dissipation problems).

As long as the MOSFETs are logic level (such as the IRLxxx series) you can then switch them directly using the PWM outputs of the Arduino.

You can use a couple of relays on the arduino outputs, and control it from there.


Arduino relay. risks? I just started working with arduinos recently. I'm really interested in working with relays. I would like to turn a desk lamp on and off using an ios app or a web browser button. I have no experience working with relays but I would love to experiment with relays in order to turn a desk lamp on or off based on an external switch in like an IOS app or a browser.

I am wondering what are the risks in relays with arduino ? I would like to switch a desk lamp on or off using a relay but I don't really understand the risks with creating a desk lamp powered using a wall socket and turned on or off using a arduino relay module . What is the worst case scenario if I screw up ? What are the risks and precautions I should take while working with relays and trying to build a relay controlled desk lamp?

I live in an apartment and I am trying to make sure that my entire building does not lose electricity or I don't screw up the electricity in my unit. What are protective measures that I can take to minimize damages while working on this project?

Basic safety precautions:

Always fully unplug the lamp before working on any wiring, even when working with the low-voltage side of things.
Invest in a proper enclosure and follow the rules of insulation and earthing: if the enclosure is metal or has exposed metal they have to be earthed. If it is plastic it is insulated and there is nothing to earth (plastic is best).
Use nylon bolts etc when situated near mains voltages.
A proper relay module with good screw terminals is recommended.
Do not tin your mains wires when screwing them into a terminal block
Do your mains wiring with your left hand in your pocket (an old electrician's trick: if you should get a shock the path to earth is down the side of your body and through your foot. If you have your left hand touching something the path to earth could well be straight across your chest, through your heart, and down your other arm, killing you. It has saved my life a few times...)
Keep mains voltages and low-voltage areas separate. Cable ties and self-adhesive nylon cable tie pads are great for keeping cables where they should be.
Shield any exposed mains connections from touch. Things like the underside of the relay module where the terminal blocks are soldered, that sort of thing.
Don't let the relay module wave around loosely. Keep it well secured in the enclosure.

I'm sure I could find more tips if I tried :)

The main thing to remember is that mains electricity is deadly and should be treated with the utmost respect.

For the ultimate in safety though you could get an isolating transformer. This separates your work from the main supply and means that the only way of getting a shock is by actively touching both outputs of the transformer at once - something you're not really likely to do - and even then it's usually a very localised path for the electricity (through a finger or two).

Adding an ELCB to the lamp's plug (if it is earthed) can be a good precaution while you are working too - and making sure the socket is connected to a ring main that is protected by an RCD is pretty much essential (in the UK it is the law that all ring mains are protected by an RCD - I would hope the same is the case where you live).

this is andrew.
I saw your Question.
Relay's are not even risky Electronic device , it can be controlled by 5v or 12 v.

On behalf, you can just run your simple led blink program to Start up your relay.
Just use the Default (13th) pin for relay input. Run your Code. If your code runs successfully, the relay activates, led in the relay will light up and as well as Your default Led also light up in your arduino Board. After that you can give the output 220v power to control electronic Devices.
if any doubt just ping me.


Arduino Robot won't move I am building a robot for a school project. I use an Arduino Uno, 2 dc motor's and an Ultra Sonic range measurement module. I want the robot to be autonomous, he has to be able to move around on his own using the Ultra Sonic sensor. Important to mention is that I don't use a MotorShield to control my dc motors. This is my latest version of coding:

#include <Servo.h> //include Servo library
#include <AFMotor.h> //include DC motor Library
#define trigPin 12// define the pins of your sensor
#define echoPin 13
AF_DCMotor motor2(7); // set up motors.
AF_DCMotor motor1(6);

void setup() {
  Serial.begin(9600); // begin serial communitication
  Serial.println("Motor test!");
   pinMode(trigPin, OUTPUT);// set the trig pin to output (Send sound waves)
  pinMode(echoPin, INPUT);// set the echo pin to input (recieve sound waves)
  motor1.setSpeed(105); //set the speed of the motors, between 0-255
    motor2.setSpeed (105);
}

void loop() {

   long duration, distance; // start the scan
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2); // delays are required for a succesful sensor operation.
  digitalWrite(trigPin, HIGH);

  delayMicroseconds(10); //this delay is required as well!
  digitalWrite(trigPin, LOW);
  duration = pulseIn(echoPin, HIGH);
  distance = (duration/2) / 29.1;// convert the distance to centimeters.
  if (distance < 25)/*if there's an obstacle 25 centimers, ahead, do the following: */ {
   Serial.println ("Close Obstacle detected!" );
Serial.println ("Obstacle Details:");
Serial.print ("Distance From Robot is " );
Serial.print ( distance);
Serial.print ( " CM!");// print out the distance in centimeters.

Serial.println (" The obstacle is declared a threat due to close distance. ");
Serial.println (" Turning !");
    motor1.run(FORWARD);  // Turn as long as there's an obstacle ahead.
      motor2.run (BACKWARD);

}
  else {
   Serial.println ("No obstacle detected. going forward");
   delay (15);
   motor1.run(FORWARD); //if there's no obstacle ahead, Go Forward!
    motor2.run(FORWARD);
  }

}

Now I added an ARDUINO MOTOR SHIELD REV3 to control my dc motors. Now the wheels are actually spinning, but after a few turns they stop. I think it is software related, but I am not 100% sure. Also I think I am connecting my motors correct to my motorshield, but don't adress them properly in my code.
And I don't have any clue how to solve this problem.
Can anybody help me with this?

I think your problem is that you connected the positive wire to the 5v pin when it said 5v and not 9v. Also, I am assuming the 6 double AA is in series creating 9v. The thing is, double AA has a lot of amps. I tested it with my multimeter and it has 7 Amps, way to much. What I would do it connect a 9v battery to the voltage in pin-Vin. That pin can take a 9v but not 7 Amps produced by your 6 AA in series. You have 2 dc motors you said.Each is running I am assuming for each of them I notice draw about 1 Amp. 9v will supply enough and be safe. Try connecting a 9v to the Vin pin. I don't think your issue is software related.


Sketch is not being received by Arduino even though Arduino Editor acts like it is finished? In my attached screen capture the Arduino Editor appears to be performing the upload, however it never finishes. Completes three steps, the last being the sketch up-load and then states that it is busy.  Sorry that I can't submit a short video. Please suggest ideas to solve this issue.  Maybe this is related to my first question?

Thank you to all who have suggested corrective action for my posted communication problem. After trying all of the suggestions, I threw up my hands and deleted all evidence of Arduino Create Editor. Next I installed the Arduino Create Editor as a fresh/new install. Magically, all of my communication issues with the Arduino Uno have been corrected. Apparently, something in the communication code was corrupted during my first attempt install on my desktop PC.

I would suggest you start with a simple blink example sketch and be sure it works. I believe it will. Your picture is almost impossible to read but i caught you have multiple libraries and several other problems. Look at the errors and resolve them one at a time. Until you do it will never load, that is the way it was designed. Be SURE there is only one file with the .ino extension unless it is also part of your sketch.


High range Obstacle detection system I am making a high range and fast Obstacle detection system ,
HC-04 is slow for that, other sensor don't have the range and Lidar is too costly.

Any idea how to make a long range(more than 10m) high speed Obstacle detection system

You can Use PIR Sensor which is Cost Effective and covers upto 10 Meters


LCD prints weird characters when I place the print statement in setup after pinMode statements #include "LiquidCrystal.h"

const int rs = 7, en = 6, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7)

void setup() {
  Serial.begin(9600);
  lcd.begin(16, 2);
  pinMode(22, INPUT_PULLUP); // Reed switch - Row1
  pinMode(24, INPUT_PULLUP); // Reed switch - Row2
  pinMode(26, INPUT_PULLUP); // Reed switch - Row3
  pinMode(28, INPUT_PULLUP); // Reed switch - Row4
  pinMode(32, OUTPUT);
  digitalWrite(32, HIGH);
  lcd.setCursor(0, 0);
  lcd.print("hello");
}

When I run the above code I get weird characters in my LCD. I removed all the connections to the pins` defined in pinMode and left only the lcd connections but kept the pinMode and digitalWrite statements in the code, but am still getting weird characters. But when I remove the pinMode and digitalWrite statements from my code the lcd works fine. Can anyone help me out.

Edit:
Another weird thing happened, I removed all the pinMode and digitalWrite statements do my setup() had only Serial.begin() and lcd.begin() and I only had the lcd connections. Now I put this code to print into an function called lcdprintMove() and there were other functions too which were performing other tasks when I ran it as such I got weird characters in the LCD but when I removed all of the other functions,the lcd printed fine. From this I was able to conclude that this problem can't be because of the supply but has to be something else. But I still can't figure it out.

Problem Solved

Today I commented all the digitalWrite statements and uploaded the program and it worked! So,  I am going to connect the lcd onto a separate arduino and communicate serially. Someone suggested the solution of putting a cap to ground and buff the power of 5 v pin can you explain this in more detail.

Circuit diagram   Note: Rs is connected to pin 7 and E to 6

The capacitor between 5V and GND effectively acts as a small battery. When a sudden demand in a current relatively large occurs, the system can get that extra small amount from the cap and not experience a voltage drop.


Issue with If statement and boolean logic I'm trying to control motor based on rain sensor and my own build anemometer. It should only controlling motor clockwise/CW for open the roof if there are no rain (indicated by value above 900) AND the wind speed below 4 km/h. If there are raining (analog value below 650) and/or wind speed above 4 km/h the motor should spin counterclockwise/CCW. I succeed to rotate the motor CCW if rain and/or high wind speed happen, but when the motor hit the limit switch for stopping the motor, motor only stop for maybe 2 seconds and then back rotating CW (open the roof), even the wind still above 4 km/h. The roof should be open only when there is no rain (analog value above 900) and the wind speed below 2 km/h. Here is my If Statement logic program:

if ((analogRead(rain) < 650 || (Wind > 4)){
  motor_closed();
}

else if (analogRead(rain) < 650 && (Wind > 4)){
  motor_closed();
}

else if (analogRead(rain) < 650 && (Wind < 2)){
  motor_closed();
}

else if (analogRead(rain) > 900 && Wind > 4){
  motor_closed();
}

else if (analogRead(rain) > 900 && Wind < 2){
  motor_open();
}

Did I make mistake when using && boolean operator? Or its something else?

Try this:

if(analogRead(rain) > 900 && Wind < 2){
  motor_open();
}
else{
  motor_closed();
}


Logic level converter 12v to 5v What is the cheapest and best method to convert 12v(14)<->5V(3.3)? Need to connect Arduino to a car.

I need logical shifter not buck converter to connect Arduino to car 12v circuit. I would like to control electrical equipment of car by Arduino. For example, I want to connect input pin to heater, when heater is on from 12v circuit I get HIGH 12v signal which processes by Arduino, but like everyone knows, Arduino can handle only 5/3.3V. Then Arduino going to change state of equipment by connecting optocoupler/relay/transistor to  button(of elect. equip.) and will act like physical press.
P.P.S I know that more clever to hack and control by CAN bus. But not all eq. are connected to CAN bus and it`s a little bit risky but I'm working on it as well.
I'm looking for best low cost solution. I have found it on ebay . Will it work like I want? Offer DIY solutions as well.

Ok, so... I can see your question is a bit obscure, so I'll try to cover a generic approach.

Power If you need to power the arduino, you can get a cheap car USB adapter. If you want a "solderable" solution, I'd avoid linear regulators (such as a 7805)and go with a cheap switching module. For low power applications I usually buy some modules called mini360 (for instance here is a link from aliexpress) which are cheap and ok for even some hundreds of milliamps. You FIRST turn the potentiometer to set the output voltage (checking with a multimeter) and THEN connect the arduino to it.
Get status If you need to get the status of something (e.g. whether the lamp is on or off) you have to analyse the circuit. If you have to detect if either 12V or GND are applied, you can solve the problem with a voltage divider. But if the lamp is always connected to 12V and then the GND side is he controlled one then you will always force a (small) current inside it. If this is the case, maybe an optocoupler is the best solution. If the signal is a PWM maybe you need some filtering, if it is a digital wire maybe it is already at the correct voltage, .... You have to figure out what is the best solution for you
Set status If you need to control something (e.g. turn on a light) your best bet is to use a 5V relay. There are plenty of them, even modules with the transistor and diode necessary to control them with an arduino.

Here are some ideas and rough schematics for the three points

simulate this circuit – Schematic created using CircuitLab

Just one very big WARNING: you have to carefully double check that the modification does not blow something up (for instance, you can make a short circuit if the body computer tryes to force a wire to 12V and you close the relay to ground). So... Be very careful, since what you do can break a lot of things, and if you are very lucky the bill can be only some couple of thousand dollars (I'll let you figure out what happens if you are not lucky enough)

What are you trying to achieve?

It's simply unclear if you want to run the Arduino on 12v of the car battery. Or if you want to control the car-windows by hooking into them? Or if you want to read out your car using the arduino.

I'll go with the later since otherwise the question would be stated a little different.

Also, you're looking for something good/cheap.
You don't tell what type of car you want to connect to.

But I think this might help you out: https://www.sparkfun.com/products/13262

25€ isn't that pricey, compared to the car you're fiddling with... So you should go with a little quality (also, you don't need them in batch?).

While a bit subjective, sparkfun could be considered a better vendor than most e-bay suppliers. Both in documentation and support. And in this case, their price isn't that bad. (I'm not affiliated with sparkfun, I actually never bought stuff of them, since e-bay works well for me. There may be hundreds of other good/better suppliers, but this one popped up first on google)

Also, "hacking" your car can have serious safety risks.


ATmega168a Breadboard - can't load via Arduino IDE I have ATmega168a on a breadboard. I am programming it via the Arduino IDE and a FT232RL USB adapter. When I select my board for 168 and upload, I get the following error:

stk500_getsync(): not in sync: resp=0x00

Normally this error means that either:

My wiring is not correct
I choose the wrong board

So to double check my wiring, I replace the 168 with a 328p. I am able to program the 328, so I think its the board selection.

I have tried Ardiono Diecimila or Duemilanove w/ ATmega168 and I also have a custom board entry:

atmega168bb.name=ATmega168 breadboard (16 MHz internal clock)
atmega168bb.upload.protocol=stk500
atmega168bb.upload.maximum_size=14336
atmega168bb.upload.speed=57600

atmega168bb.bootloader.low_fuses=0x62
atmega168bb.bootloader.high_fuses=0xDF
atmega168bb.bootloader.extended_fuses=0xF9
atmega168bb.bootloader.path=arduino:atmega
atmega168bb.bootloader.file=ATmegaBOOT_168_atmega328_pro_16MHz.hex
atmega168bb.bootloader.unlock_bits=0x3F
atmega168bb.bootloader.lock_bits=0x0F

atmega168bb.build.mcu=atmega168
atmega168bb.build.f_cpu=16000000L
atmega168bb.build.core=arduino:arduino
atmega168bb.build.variant=arduino:standard

Also, I am able to program the 168 via my AVR Programmer/Debugger. If you are wondering why I should just use the AVR Dragon, there reason is that I a sometimes don't want to remove the chip from the bread board while developing and programming.

Any suggestions I can try?

Have you burned a bootloader?
The standard Arduino IDE upload requires that you have a bootloader on the chip.
You can burn a bootloader with the Arduino IDE and your AVR dragon

you should be selecting the Arduino NANO board as the original Arduino Nano board is equipped with the FT232RL, rest all have either atmega chip for usb to ttl conversion or CP2302 chip. So select Arduino Nano and try.


D1 mini does not resume operation as expected after deep sleep I'm trying to get the D1 mini to return operation after ESP.deepsleep(). The code below compiles and gives the expected output for the first run. Five seconds after the announcement that that the device is going to sleep, there is a brief flash on the on board LED and I get a string of garbage on the serial monitor. Ideas for things to try would be appreciated.

// Testing d1 mini deep sleep
// D0 and RST are connected

/*  platformio.ini:
  [env:d1_mini]
  platform = espressif8266
  board = d1_mini
  framework = arduino
  monitor_speed = 115200
*/

#include <Arduino.h>

void blink();

void setup() {
  Serial.begin(115200);
  pinMode(D0, WAKEUP_PULLUP);
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  blink();
  delay(1000);
  Serial.println("Going for some deep sleep");
  ESP.deepSleep(5e6); // 5e6 is 5 seconds
}

void blink() {
  digitalWrite(LED_BUILTIN, LOW);
  delay(500);
  digitalWrite(LED_BUILTIN, HIGH);
  delay(500);
}

As you can guess I'm running this with platformio. The output on the serial monitor is:

stefan@Cameron ~/.../Projects/Deep sleep $ platformio device monitor --baud 115200
--- Miniterm on /dev/ttyUSB0  115200,8,N,1 ---
--- Quit: Ctrl+C | Menu: Ctrl+T | Help: Ctrl+T followed by Ctrl+H ---
Going for some deep sleep
sl␀l��|␀�l�|␂␌␌␄�␄l�␌c|ǃ␃�␛�r�cd�c��gg�doo���␌cpp��$sd{d␛�{��o�c�gbx␀�

There is a blink of the LED on the first run, nothing there either after the apparent reset.

The garbage is because the ESP8266 outputs boot information at 76800. This should include the boot reason and may help you understand why the code's not working as expected.

Try changing your Serial speed to 76800 in your code (just so that your messages don't end up being gibberish), use 76800 on platformio's monitor and you should be able to at least see what the D1 says it's doing.

You should see a line that ends in something like:

  rst cause: x, boot mode:(y, z)

x should be 1 ("Power reboot"), 2 ("External reset or wake-up from Deep-sleep" - obviously what you want), 3 ("Software WDT" - the software watchdog went off) or 4 ("Hardware WDT reset" - the hardware watchdog timer went off)

boot mode indicates where the runtime image came from - y should be 3 ("Flash"); anything else is really unlikely for your setup.

There's more info on this at ESP8266 Reset Causes
and Common Fatal
Exception Causes

If you try this please post how it goes! I'd like to hear more about what's going on here.

Try and clear out the whole memory. Maybe there is something that is messing it up.

I tried your code and it works for me. I do not have a D1 mini but I can't see any reason for it not to work. (due to hardware reasons)

I would include a delay and then output a newline in the setup. As it is your loop print is written after the boot info and gets lost at the end of the line.

Like I said, your code worked for me. But I find this more user friendly. https://raw.githubusercontent.com/wemos/D1_mini_Examples/master/examples/02.Special/DeepSleep/Blink/Blink.ino

Check again your connections. (I'm sure you have done that a dozen times)


3.3 V Arduino Pro Mini and nRF24L01 issues I have a 3.3 V Pro Mini connected to nRF24l01 as xmtr. The nRF24L01 does not respond to the Pro Mini. Any help will be appreciated.

I have attached the print detail output:

Transmitter 2  Started
STATUS       = 0xff RX_DR=1 TX_DS=1 MAX_RT=1 RX_P_NO=7 TX_FULL=1
RX_ADDR_P0-1     = 0xffffffffff 0xffffffffff
RX_ADDR_P2-5     = 0xff 0xff 0xff 0xff
TX_ADDR      = 0xffffffffff
RX_PW_P0-6   = 0xff 0xff 0xff 0xff 0xff 0xff
EN_AA        = 0xff
EN_RXADDR    = 0xff
RF_CH        = 0xff
RF_SETUP     = 0xff
CONFIG       = 0xff
DYNPD/FEATURE    = 0xff 0xff
Data Rate    = 1MBPS
Model        = nRF24L01
CRC Length   = 16 bits
PA Power     = PA_MAX

Transmitter 2 Started
STATUS       = 0x0e RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=7 TX_FULL=0
RX_ADDR_P0-1     = 0xe8e8f0f0e2 0xc2c2c2c2c2
RX_ADDR_P2-5     = 0xc3 0xc4 0xc5 0xc6
TX_ADDR      = 0xe8e8f0f0e2
RX_PW_P0-6   = 0x20 0x00 0x00 0x00 0x00 0x00
EN_AA        = 0x3f
EN_RXADDR    = 0x03
RF_CH        = 0x73
RF_SETUP     = 0x07
CONFIG       = 0x0e
DYNPD/FEATURE    = 0x03 0x06
Data Rate    = 1MBPS
Model        = nRF24L01+
CRC Length   = 16 bits
PA Power     = PA_MAX
voltage = 3.97 V
0
RSLT (1 = success) 0
Data Sent 3.00  0.00  3.97
voltage = 3.85 V
voltage = 3.79 V
voltage = 3.75 V
voltage = 3.73 V
0
RSLT (1 = success) 0
Data Sent 3.00  0.00  3.73
voltage = 3.70 V
voltage = 3.68 V
voltage = 3.65 V
voltage = 3.62 V
0
RSLT (1 = success) 0
Data Sent 3.00  0.00  3.62
voltage = 3.58 V
voltage = 3.54 V
voltage = 3.50 V
voltage = 3.45 V
0

The top transmitter output is before I changed the nRF24L01 module which appeared to be bad.
The second transmitter started output. Module is good but nRF24L01 would not connect to receiver with 3.3 V Pro Mini. It connects if I use a Nano.

voltage = 3.97 V 0 RSLT (1 = success) 0 Data Sent 3.00 0.00

nrf24l01 is a 3.3V device, Where'd that come from?

Promini 3.3V regulator is also only good for 150mA. I think the nrf24L01 needs more current than that.


Trouble using proximity sensor as input and LED output I was wondering if anyone had any pointers or advice to make this project work. Essentially I would like to have the LED fade (meaning like fade on and off at a calm rate) at one rate when there is nothing close to the proximity sensor, and then to speed up the fade amount when there is something close to the sensor.

#include <NewPing.h>   //include the library

int led = 9;           // the PWM pin the LED is attached to
int brightness = 0;    // how bright the LED is
int fadeAmount;    // how many points to fade the LED by

int triggerPin = 12;   //pin conneccted to the Trig pin on the sensor
int echoPin = 11;       //pin connected to the Echo pin on the sensor
int maxDistance = 200;  //set the max distance for the sensor to read (helps with errors)
int distanceVal;        //variable to hold the distance val

int sampleRate = 200;   //how fast to sample the value
long lastReading;       //used for the timer

NewPing proximity1(triggerPin, echoPin, maxDistance);   //sets up the sensor object

void setup()
{
  Serial.begin(9600);  //start the serial port
  pinMode(led, OUTPUT);
}

void loop() {

    if(millis()-lastReading>=sampleRate) //this very simple statement is the timer,
  {
  distanceVal = proximity1.ping_cm();  //get the distance value in centimeters

  lastReading = millis();

  Serial.print("Distance Reading CM : ");  //print the value to the Serial monitor
  Serial.println(distanceVal);

if(distanceVal<20){

fadeAmount = 5;
}
else{
  fadeAmount = 2;
}

  // set the brightness of pin 9:
  analogWrite(led, brightness);

  // change the brightness for next time through the loop:
  brightness = brightness + fadeAmount;

  // reverse the direction of the fading at the ends of the fade:
  if (brightness <= 0 || brightness >= 255) {
    fadeAmount = -fadeAmount;
  }
  // wait for 30 milliseconds to see the dimming effect
  delay(30);
  }
}

https://github.com/sanaalla/Fade-LED-with-Proximity-sensor

Above is my code, which is not working. I am fairly new to Arduino and so would greatly appreciate some more seasoned wisdom!

You want 2 independant loops, one for the measurement and one for the dimming effect. The latter one must also be able to run when not measuring.

if(millis()-lastReading>=sampleRate) //this very simple statement is the timer,
{
  distanceVal = proximity1.ping_cm();  //get the distance value in centimeters

  lastReading = millis();

  Serial.print("Distance Reading CM : ");  //print the value to the Serial monitor
  Serial.println(distanceVal);
}

if(millis() - lastFade >= fadeRate) //other timer
{
  lastFade = millis();
  if(distanceVal<20){
    fadeAmount = 5;
  }else{
    fadeAmount = 2;
  }

  // set the brightness of pin 9:
  analogWrite(led, brightness);

  // change the brightness for next time through the loop:
  brightness = brightness + fadeAmount;

  // reverse the direction of the fading at the ends of the fade:
  if (brightness <= 0 || brightness >= 255) {
    fadeAmount = -fadeAmount;
  }
}

*update! I fixed the code and got it to do what I want.

#include <NewPing.h>   //include the library

int led = 9;           // the PWM pin the LED is attached to
int brightness = 0;    // how bright the LED is
int fadeAmount1 = 10;    // how many points to fade the LED by
int fadeAmount2 = 2;    // how many points to fade the LED by

int triggerPin = 12;   //pin conneccted to the Trig pin on the sensor
int echoPin = 11;       //pin connected to the Echo pin on the sensor
int maxDistance = 200;  //set the max distance for the sensor to read (helps with errors)
int distanceVal; //variable to hold the distance val
int lastFade;
int fadeRate = 200;

int sampleRate = 200;   //how fast to sample the value
long lastReading;       //used for the timer

NewPing proximity1(triggerPin, echoPin, maxDistance);   //sets up the sensor object

void setup()
{
  Serial.begin(9600);  //start the serial port
  pinMode(led, OUTPUT);
}

void loop() {

  if(millis()-lastReading>=sampleRate) //this very simple statement is the timer,
{
  distanceVal = proximity1.ping_cm();  //get the distance value in centimeters

  lastReading = millis();

  Serial.print("Distance Reading CM : ");  //print the value to the Serial monitor
  Serial.println(distanceVal);
}

if(distanceVal<20){

    // set the brightness of pin 9:
  analogWrite(led, brightness);

  // change the brightness for next time through the loop:
  brightness = brightness + fadeAmount1;

  // reverse the direction of the fading at the ends of the fade:
  if (brightness <= 0 || brightness >= 255) {
    fadeAmount1 = -fadeAmount1;
  }
  // wait for 30 milliseconds to see the dimming effect
  delay(30);
}

else{

    // set the brightness of pin 9:
  analogWrite(led, brightness);

  // change the brightness for next time through the loop:
  brightness = brightness + fadeAmount2;

  // reverse the direction of the fading at the ends of the fade:
  if (brightness <= 0 || brightness >= 255) {
    fadeAmount2 = -fadeAmount2;
  }
  // wait for 30 milliseconds to see the dimming effect
  delay(30);
}

}


Best way to power an Arduino using the Vin pin I have a powerbank rated 5v. The battery is actually 3.6v, powering the built-in SMPS to give out 5v. I have stripped one end of the USB cable coming from the power bank, powering a motor driver and the Arduino in parallel. The positive end of the power bank, which is 5v, is going into the Arduino and the motor driver IC's Vcc.

I heard that 5v is not enough to drive the Arduino from the Vin pin. And there is only one power out from the powerbank, so directly connecting the Arduino through the USB would leave nothing to drive the motor driver IC.

A USB splitter would be the obvious solution, but is there anything else I can do? The power source has to be mobile. Can I power the Arduino through the Vin with those 9v batteries commonly used in electronics hobby projects?

You have a powerbank which has a USB output, right? Why not just plug a cable from that into the Arduino USB port? That will connect the 5V directly into the 5V pin of the Arduino (probably via a switching MOSFET). Then you can connect to your motor driver from the 5V pin on the Arduino (and Gnd of course). There may be some limitations on how large a motor you can drive (based on the capacity of the power bank, and to an extent also the thickness of the traces on the Arduino board).

As others have commented, Vin is not intended for that purpose (ie. to supply 5V). You should supply 7V or more to Vin to force the switching MOSFET to disconnect the USB input. In your case you don't have 7V from the powerbank.

Here is how the Uno Rev3 power system works:

The input jack (circled in blue) goes through a diode (D1) to the Vin line.

Vin then goes through the 5V voltage regulator (U1) to provide +5V.

However on the top left you see 2 x 10K resistors (RN1A and RN1B) which make a voltage divider from Vin to Gnd. This is compared to the output of the 3.3V voltage regulator by U5A op-amp (circled in red). If higher, then T1 (circled in green) will turn off, disconnecting USBVCC from the +5V line. If lower, then USBVCC is connected to +5V. The nett effect is that if Vin in greater than 6.6V (because of the voltage divider) then the circuit chooses to use Vin, otherwises it uses USBVCC (USB power).

That's why they recommend to use 7V or more into Vin.

Note that you lose around 0.7V through the diode, which is why you need something like 7.3V at the input jack to allow for the loss of the 0.7V before the op-amp compares it to 6.6V.

Most of Arduino Boards you may purchase online, have got a 9 V battery holder with wire leads. Check out the following video to have an idea of using a portable power supply for an Arduino Board.

https://www.youtube.com/watch?v=W-T4Sq0VmGk


Arduino Ultrasonic Sensor and LCD - Help Needed- I just recently purchased an Arduino Uno 3 and I wanted to make an ultrasonic distance sensor that outputs the readings to a 16x2 LCD. I followed this guide:
http://www.mertarduino.com/using-ultrasonic-distance-sensor-hc-sr04-with-lcd-display-and-arduino/2018/11/22/ but it gave an error when I uploaded the code. The error was: a function definition is not allowed here before '{' token. I don't know too much about Arduinos, so I need help.
Thanks to whoever responds!

Here is the code:

// put your setup code here, to run once:
#include <LiquidCrystal.h> //Please replace the single quote characters ('') with the parenthesis character (<>)

LiquidCrystal lcd(1, 2, 4, 5, 6, 7); // Creates an LCD object. Parameters:
(rs, enable, d4, d5, d6, d7)

const int trigPin = 9;
const int echoPin = 10;
long duration;
int distanceCm, distanceInch;

void setup() {

lcd.begin(16,2); // Initializes the interface to the LCD screen, and
specifies the dimensions (width and height) of the display
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);

}

void loop() {

digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

duration = pulseIn(echoPin, HIGH);
distanceCm= duration*0.034/2;
distanceInch = duration*0.0133/2;

lcd.setCursor(0,0); // Sets the location at which subsequent text written to
the LCD will be displayed
lcd.print("Distance: "); // Prints string "Distance" on the LCD
lcd.print(distanceCm); // Prints the distance value from the sensor
lcd.print("  cm");
delay(10);
lcd.setCursor(0,1);
lcd.print("Distance: ");
lcd.print(distanceInch);
lcd.print("inch");
delay(10);
}

The root of your problem is this bit:

LiquidCrystal lcd(1, 2, 4, 5, 6, 7); // Creates an LCD object. Parameters:
(rs, enable, d4, d5, d6, d7)

I think in copying-and-pasting you ended up with a line split across two giving you an error. It should read:

LiquidCrystal lcd(1, 2, 4, 5, 6, 7); // Creates an LCD object. Parameters: (rs, enable, d4, d5, d6, d7)

You have a similar problem here:

lcd.begin(16,2); // Initializes the interface to the LCD screen, and
specifies the dimensions (width and height) of the display

Again that has split across two lines and should read:

lcd.begin(16,2); // Initializes the interface to the LCD screen, and specifies the dimensions (width and height) of the display

And a third:

lcd.setCursor(0,0); // Sets the location at which subsequent text written to
the LCD will be displayed

which should be:

lcd.setCursor(0,0); // Sets the location at which subsequent text written to the LCD will be displayed

When those three are corrected the code compiles properly.


Arduino -> Processing conversion: creating mux channels As the title alludes to, I'm in the process of converting an Arduino sketch to a Processing sketch. So far, mostly pretty straightforward.

I'm running into an issue with creating an array of ints for the channels for two muxers. Below is the code that I currently have working for the Arduino sketch:

int writeMux(int channel){
  int controlPin[] = {s0, s1, s2, s3, s4, s5, s6, s7};

  int muxChannel[20][8]={
    //Mux 1
    {0,0,0,0,0,0,0,0}, //channel 0
    {1,0,0,0,0,0,0,0}, //channel 1
    {0,1,0,0,0,0,0,0}, //channel 2
    {1,1,0,0,0,0,0,0}, //channel 3
    {0,0,1,0,0,0,0,0}, //channel 4
    {1,0,1,0,0,0,0,0}, //channel 5
    {0,1,1,0,0,0,0,0}, //channel 6
    {1,1,1,0,0,0,0,0}, //channel 7
    {0,0,0,1,0,0,0,0}, //channel 8
    {1,0,0,1,0,0,0,0}, //channel 9

    //Max 2
    {1,1,1,1,0,0,0,0}, //channel 0
    {1,1,1,1,1,0,0,0}, //channel 1
    {1,1,1,1,0,1,0,0}, //channel 2
    {1,1,1,1,1,1,0,0}, //channel 3
    {1,1,1,1,0,0,1,0}, //channel 4
    {1,1,1,1,1,0,1,0}, //channel 5
    {1,1,1,1,0,1,1,0}, //channel 6
    {1,1,1,1,1,1,1,0}, //channel 7
    {1,1,1,1,0,0,0,1}, //channel 8
    {1,1,1,1,1,0,0,1}, //channel 9
  };

  //loop through the 4 sig
  for(int i = 0; i < 8; i ++){
    digitalWrite(controlPin[i], muxChannel[channel][i]);
  }

  //write the value at the SIG pin
  analogWrite(SIG_pin, testValue);

  //return the value
  return 0;
}

Below is the slightly varied version that I'm using for my Processing-equivelent sketch.

int readMux(int channel){
  int controlPin[] = {s0, s1, s2, s3};

  int muxChannel[20][8]={
    //Mux 1
    {0,0,0,0,0,0,0,0}, //channel 0
    {1,0,0,0,0,0,0,0}, //channel 1
    {0,1,0,0,0,0,0,0}, //channel 2
    {1,1,0,0,0,0,0,0}, //channel 3
    {0,0,1,0,0,0,0,0}, //channel 4
    {1,0,1,0,0,0,0,0}, //channel 5
    {0,1,1,0,0,0,0,0}, //channel 6
    {1,1,1,0,0,0,0,0}, //channel 7
    {0,0,0,1,0,0,0,0}, //channel 8
    {1,0,0,1,0,0,0,0}, //channel 9

    //Max 2
    {1,1,1,1,0,0,0,0}, //channel 0
    {1,1,1,1,1,0,0,0}, //channel 1
    {1,1,1,1,0,1,0,0}, //channel 2
    {1,1,1,1,1,1,0,0}, //channel 3
    {1,1,1,1,0,0,1,0}, //channel 4
    {1,1,1,1,1,0,1,0}, //channel 5
    {1,1,1,1,0,1,1,0}, //channel 6
    {1,1,1,1,1,1,1,0}, //channel 7
    {1,1,1,1,0,0,0,1}, //channel 8
    {1,1,1,1,1,0,0,1}, //channel 9
  };

  //loop through the 4 sig
  for(int i = 0; i < 4; i ++){
    digitalWrite(controlPin[i], muxChannel[channel][i]);
  }

  //write the value at the SIG pin
  arduino.analogWrite(SIG_pin, testValue);

  int val = 0;
  return val;
}

I'm currently getting an error of unexpected token: int error at the following line:

  int muxChannel[20][8]={

And, an error of The type of expression must be an array type but it resolved to int at this line:

digitalWrite(controlPin[i], muxChannel[channel][i]);

Thank you!

When making an array I processing you must use the code

int[] xyz = \*declare variable or new*\ {
    this is some code
}

You used

int xyz[num][num]

You must declare the values of the array only after declaring it.
Also, did you try declaring digitalWrite as a new variable?


20x4 LCD will write but then won't update I am controlling a solar tracker, and it needs to be reset every 10 minutes or it loses its mind.  My program works fine, controlling power relays, so I have added I2C&Power to be able to see the status remotely.  For now it is set up on the workbench with fairly short cables.  I also have a RTC and the i2cscanner finds them all..

LCD init code is pretty basic:

// 20 x 4  LCD Display
#include LiquidCrystal_I2C.h
// set the LCD address to 0x3F for a 20 chars 4 line display\/ Set the pins on the I2C chip used for LCD connections:
//                    addr, en,rw,rs,d4,d5,d6,d7,bl,blpol
LiquidCrystal_I2C lcd(0x3f, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

then

lcd.begin(20,4);
lcd.clear();
lcd.setCursor(2,0);
lcd.print("PV Control 3.9");

My LCD (20x4) works fine at first, writing the top line with the name of the program, then the bottom line with a temperature reading, then every 10 minutes I need the second line to show when the power is off for 10 seconds.  It shows "power off" just fine, but after the delay(10000) it is supposed to overwrite that line with  "power on" but nothing changes...

Serial.println("POWER OFF");
lcd.setCursor(4,1);
lcd.print("-Power Off- ");
digitalWrite(power1,HIGH);  // DC HOUSE power off
digitalWrite(power2,HIGH);  // DC HOUSE power off
delay(10000);
Serial.println("POWER ON");
lcd.setCursor(4,1);
lcd.print("-Power On-  ");
digitalWrite(power1,LOW);  // DC HOUSE power on
digitalWrite(power2,LOW);  // DC HOUSE power on

The problem is that it continues to say "power off" and doesn't overwrite it.

I can see from the Serial Monitor that the program is running fine, but the LCD doesn't change after the first set of lcd.prints at those character positions.

I haven't heard of anybody having this problem, but perhaps someone out there know about this.   Any suggestions would be very welcome.

Question is:  How can I make the LCD update lines that have been originally written?

UPDATE:  Problem solved by simply clearing and rewriting the display when things change.  I can't debug libraries but at least it is working now.

Ah ha.   I solved it by using lcd.clear() and simply repainting the entire display with every change.  I have much simpler LCD programs that don't require doing this, but it worked in this instance.

Same code as above, but with this before each power notification:

lcd.clear();
lcd.setCursor(2,0);
lcd.print("PV Control 3.9");

etc...

UPDATE:
  Now that I have two 20x4 LCD screens showing readings from two separate Arduinos (PV Controls and Weather station) I have discovered that it is very important to keep the screen writes to a minimum.  No time delays in between writing parts of the screen, for instance (like when I had Serial.print statements in there for debugging), doing all the readings and calculations before writing the screen, and timing the screen updates to be infrequent, like on the order of 65 seconds for weather and 10 minutes for the PV.  I2C does not have collision detection so it is important to try to prevent the two screens from being updated at the same time.  The I2C&Power arrangement is working great.  One source of power is all it takes to activate the entire network.


AT command not send but blue LED stays on I am new to working with Arduino Uno and ESP8266.

Firstly I connected an ESP8266 to an Arduino Uno like so:

TX to TX,
RX to RX,
GND to GND,
VCC to 3.3V,
CH_PD to 3.3V and
adding RESET to GND on the Arduino Uno.

After completing the wire connection, I opened the Arduino IDE serial monitor, where it always shows symbols and text and I set baud rate 115200 and adjusted both NL and CR.

After all of that, when I send an AT command, then no response is shown.

TX is an output. RX is an input.

By connecting TX to TX and RX to RX you have connected an output to an output, and an input to an input.

You need to connect the TXs to the other RXs.

Also: see (NEWBIE) Sending AT Command from Arduino UNO to ESP8266 doesn't work


How to represent -1 as a byte I want to initialize the value of byte to -1. When I just use byte num = -1 the value ends up being a decimal 255. I've also tried int8_t number = -1 and then byte num = number but this didn't work either.

A byte can't be -1. A byte can only store numbers between 0 and 255 inclusive.

Depending on the range of your numbers you could use a char (-128 to +127) or an int (-32768 to +32767).

As the other two users have already mentioned:
A byte can only store a number between 0-255, which obviously means that -1 can't be stores as a byte.

I suggest storing it as a positive number, and then when you want to use it just multiply it by -1, which will turn it into a negative one.

Example to convert positive number as a byte to a negative number:

    negativeNumber = positiveNumberStoredAsByte * -1


How to add more inputs on Arduino? I'm building an instrument that has 72 buttons that can be pressed. Now I'm planning on using Arduino to send data to computer via USB cable about which buttons are pressed. So I figured I'd need 72 different input pins, one for each button(the button is connected to the Arduino via a wire). But, the Arduino doesn't have 72 input pins, so this seems kind of impossible. So what I'm looking for is a way to somehow extend the number of pins on the Arduino or another way to solve my problem. Maybe it would be better to use another micro-controller? Maybe using analog inputs for this is better?

If it makes any difference, the max number of buttons that can be pressed at once is 10.

There is a whole concept you need to learn:

Matrix

By using a matrix arrangement you can, using (8 + 9 = ) 17 IO pins you can create a grid of 8 × 9 buttons, which is 72 buttons.

This method is used all the time for keypads, and you can read more here: http://playground.arduino.cc/Main/KeypadTutorial

To further reduce the number of IO pins used you can replace the 8 IO pins for one dimension of the matrix with a 3-to-8 decoder, since only one pin is ever active at a time.  That reduces it down to just 12 IO pins for the whole shebang.

You may try making something like a button grid, Like the ways Leds are connected in a Led cube, For example - In a 4*4*4 led cube, u don't need 64 pins, but a smart connection of all on x and y axis,

what i mean to say is,
you need to make rows and columns of button, But i don't think this idea would work cause buttons are totally different from leds, But then also try searching for led cube circuit, let it spark a new idea in your mind.


Shared 5v power for Due dedicated application I would appreciate input on this situation:

I plan to power a fairly high current, 5 volt supply, 3.3v signal, device from a suitable wall wart. I would like to power the due that controls it through the due's usb port by tapping the 5v from the wall wart into a suitably modified USB cable (leaving the signal pins unused). No significant external power demands would be made on the due's 3.3v or 5v headers.

So there are two devices sharing the wall wart: one device that uses high current, and the other device is the due.

Yes it is possible. You just need to connect both Grounds


Managing timer intervals using millis at random intervals I am doing a project which needs to meet the following specifications.

  On receiving an SMS arduino will start switching 1st relay on after some
  time duration(say 30 Seconds) relay 1 will be turned off and it will now turn on 2nd relay for (say 20seconds) so on 1>2>3>4.

The problem im facing is managing the time intervals between the switching process,i did think of using millis() i.e (currentMillis-previousMillisx>Intervalx) as in blinkWithoutDelay ,how ever this will work only once as i dont not know when will the next SMS come to the system ,if the user decides to send the message after 1hour currentMillis-previousMillisx will always return true so i cannot keep the motor on for (Say 30 seconds) and same will happen with all 4 cases.

If there is any alternative logic for this problem please suggest me or can i just add RTC for my project to manage time easily

Thank You

I do not really understand your problem. More specifically,
“currentMillis-previousMillisx will always return true” does not make
sense, as it is not a boolean expression (it's unsigned long).

Anyway, the technique shown in blinkWithoutDelay is the way to go. Here
is my (untested) version:

const int relay_count = 4;  // we have 4 relays
const int relay_pins[relay_count] = {2, 3, 4, 5};
const unsigned long durations[relay_count] = {30000, 20000, 15000, 10000};
bool sms_received();  // you implement this one

void loop()
{
    static int current_relay = -1;  // meaning: no active relay
    static unsigned long last_switch;
    unsigned long now = millis();

    // If no relay is active, wait for an SMS.
    if (current_relay == -1) {
        if (sms_received()) {
            // Switch on first relay.
            current_relay = 0;
            digitalWrite(relay_pins[current_relay], HIGH);
            last_switch = now;
        }
    }

    // Otherwise, switch relays when it is time to do so.
    else if (now - last_switch >= durations[current_relay]) {
        digitalWrite(relay_pins[current_relay], LOW);
        if (++current_relay == relay_count) {
            current_relay = -1;  // no active relay
        } else {
            digitalWrite(relay_pins[current_relay], HIGH);
            last_switch = now;
        }
    }
}

BTW, you did not specify what should happen if you receive an SMS while
one of the relays is active. I assume the SMS are only acknowledged when
no relay is active. Otherwise you would have to change the code.

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


Programming addressable LED I have TM1812 addressable LED strip (1meter long 96 LED). I am looking a way to program it and i found this http://www.deskontrol.net/blog/arduino-based-artnet-node-for-led-pixels/
and its mentioned in article that it doens't work with current version of Arduino IDE.

Is there some other lib/api available to program it or another method?

UPDATE
As mentioned by @dlu FastLED support wide variety of LEDs. I contacted developers of FastLED on google + and they have updated there documentation for support of TM1812 its similar to TM1809

There is a very nice library called FastLED, it is also on GitHub as FastLED/FastLED. It is quite flexible and supports a huge range of addressable LEDs. I'm currently using it with 1.6.6.

The code that you linked to was developed with an older version of the Arduino IDE, so you might want to see if you can find an older version and try building with that.

All TM chip Family is supported by Fastled Libs if you use a TM1811 just put TM1809.

It should work, I have tried and it succeeded.


How to convert this prototype to finished product? My prototype contains below components:

Arduino Uno R3
Bluetooth LE nRF8001 Break-out (https://www.adafruit.com/products/1697)
MicroSD Break-out (https://www.adafruit.com/products/254)
ADXL335 triple-axis Accelerometer

I think It's OK on paper (and presumably on a breadboard too). I'm trying to wrap my head around on how to convert it to a finished product that sits inside a plastic box.

What are my options?

For instance, can I create a single PCB that contains all the components? If not, how can I connect these multiple break-out boards together? Is soldering some wires on both boards to connect them is a viable option?

Edit:

My ultimate goal is to create a product that is for sale. So I mean something that can be mass-produced and can meet regulatory requirements.

This is why I was thinking about a single PCB. Arduino (or should I say ATMegaXXX?) is fairly simple to place on a custom PCB. So I was thinking perhaps I could "re-create" my break-outs (see above) on this PCB thus creating a single piece including all components and the microcontroller. For some reason this makes sense to me but I don't know how hard it is or if it is even possible.

First, you should read this this question here.

The reasonable answer here varies a lot depending on how involved you want to get, and what volumes you want to sell at.

Fortunately, you're not using any breakouts with truly exotic parts. The nRF8001 is just a QFN part, which can be soldered by hand without too much trouble.

Speaking loosely, the process would look like this:

Design a PCB layout that contains everything.
(Optional) - Figure out if you want to put it in a enclosure of some sort.
(Optional) - Determine how you're going to have the enclosures produced or modified from an existing product. You can have a contract machine-shop do the work, but again, $$$$.
Send out to have PCB prototypes manufactured. I like OSHPark, but there are LOTS of options.
Assemble your boards.
Find out your prototype doesn't work.
Go back to step 1 (expect this to happen a few times)
Rent/Beg/Borrow some equipment to do EMC pre-qualification testing (for FCC).
Realize you have an EMC disaster.
Respin boards a few more times (e.g. go back to 1 again) to fix the pre-qualification EMC issues.
Feel like you have a decent layout, have it FCC tested.
Pay $10K+ for FCC testing.
If you're lucky, you passed, you now have a proper, FCC certified product.
Nope, go back to 1 again if you failed.
Do lot assembly, either manually (major time investment), or contract out (expensive!).
Sell your widget!

Note that you can contract out the prototype assembly, but doing so is expensive, even if you do it in china. The magic (or cursed, really) term here is "NRE", or non-reoccurring expenses/engineering. Colloquially, it's the "setup cost" of doing a production run. Sure, you may only pay $5-50 per-widget to have them assembled, but there will be a $1000+ base charge. This reflects the fact that the primary time-cost on the part of an assembly house to build your widget is setting up the production line, working up and debugging a pick-and-place routine, building test-setups, etc... Once everything is up and running, the actual per-unit cost is fairly marginal.

This is also why commercial electronic devices can be so cheap. They're made in truly enormous volumes, and that lets the companies amortize the NREs across the entire production run. NREs are basically the bane of any small electronics business. They're also basically the reason specialty widgets are so expensive. Places like spark-fun can get away with fairly cheap products because they have their own complete assembly line in-house, and even there, you're often paying 4X+ the cost of parts for just the IC on a PCB with a few cents worth of passives.

Since you seem to be new to PCB design, this is possibly not a great first project. It's doable, but expect it to cost 4X+ what you expect, and take 2X+ the time you planned. There are a LOT of facets to designing a proper product, and they each contain an entire field.

It'd probably be better off to start out with some simpler boards, maybe a through-hole-only arduino clone, or similar (though SOIC can be soldered without a hot-air station or anything).

Some assumptions I'm making:

If you're serious, you will have to lean SMT assembly practices. Through-hole only is not a viable stance anymore.
Expect to buy a lot of tools, and burn a lot of money in failed prototypes.
Expect 3 board revisions. At minimum, before you have something you can get tested. I could maybe do it in 2, if I got really, really lucky, but I doubt that would happen, and this sort of thing is my day-job.

Hardware is HARD, and worse, it's completely unforgiving. If you're coming from a software engineering background, you basically have to discard all your assumptions, as they will actively hurt you.

Imagine a software project where "compiling" can take 4 weeks. That's hardware development.

Single PCB is not viable, as some chips are near impossible to solder by hand. Also, you'd have to get your PCB checked for FCC compliance (because of the bluetooth), which you don't want.

You could design a PCB that contains the Arduino micro controller (ATMega328), and that all the other board plug into.

Wires could also be a solution, by you probably need to find a way to securely mount all the boards inside the enclosure (no rattling).

PS I'd suggest something like an Arduino Nano as it's smaller, and you can remove the header pins and solder wires directly to PCB.


Programming an ATtiny85 Recently I ordered some ATtiny85's from Jameco, and I've been trying to upload code to them through an Arduino Uno, following the instructions from this video on YouTube. I've been getting a lot of unexpected errors and I am now wondering if the chips I bought are the problem. Here are the specs from the Jameco website:

Flash (Kbytes): 8 Kbytes
Pin Count: 8
Max. Operating Frequency: 20 MHz
Power Supply: 2.7 - 5.5V
Operational Range: Industrial (A) (-40°C to 85°C)
CPU: 8-bit AVR
Number of Touch Channels: 3
Hardware QTouch Acquisition: No
Max I/O Pins: 6
Ext Interrupts: 6
USB Speed: No
USB Interface: No

Does the "USB Speed: No; USB Interface: No" mean these aren't programmable by my set up? Or is there is anything else I should know about these chips? Do I need to get new ones that are different?

Before you panic (try not to panic) and buy new chips, test the existing ones. See my page about detecting chip signatures which has links to code on Github for a sketch you can run on your Uno, to test the ATtiny85.

You can also upload code from a .hex file (which the IDE produces) by using a different sketch (same code link) from this page about a hex uploader and wiring like this (you also need an SD card adapter):

The first sketch and wiring should at least confirm your chips are OK. The second one is an alternative way of programming them.

I would suggest you to take a look at this video which explains step by step how to program the ATtiny85. https://www.youtube.com/watch?v=i9WOwDrpRKs

From my early days trying to program the ATtiny, i have watched this video.


What's the difference between all the Software Serial Libraries? Which one is Arduino Nano compatible? There are so many Software Serial Libraries, what are the differences between them? And which one I can use with my Arduino Nano? For my Arduino Nano I need one Hardware Serial Port and one Software Serial port at a baud rate of 115200.

On which pins of the Arduino Nano can I use the software serial library?

This answer lists the 4 basic choices:

HardwareSerial, always the best.  Simply use the pre-defined Serial variable.  On some Arduinos, there are extra HardwareSerial ports, called Serial1, Serial2, etc.  The Nano only has Serial.
AltSoftSerial, the best of the software serial libraries.  Only one instance is allowed, and it is must be used on one of the Input Capture pins (pins 8 & 9 for a Nano).
My NeoSWSerial is next best.  It works on any two pins, but only at baud rates 9600, 19200 and 38400.
SoftwareSerial is the worst choice.  It works on any two pins, but it is very inefficient.  It disables interrupts for the entire time that a character is being sent OR received, and it cannot do both at the same time (unlike all the other serial choices).  This can interfere with other parts of your sketch, other device communications, or with libraries.

If you could use a slower baud rate, you could keep your debug prints on Serial, and use either AltSoftSerial or NeoSWSerial for your device.

But if you have to use 115200, the only reliable choice is Serial.  Although AltSoftSerial and SoftwareSerial allow that baud rate, they may not send/receive data correctly.

In that case, I would suggest using Serial for the 115200 device.  Unless you are using an ISP, you will have to disconnect the device to upload a new sketch over USB.

Then use AltSoftSerial or NeoSWSerial for your debug statements.  You will need a TTL Serial-to-USB adapter (aka FTDI) on the selected pins to connect to the PC.  The Serial Monitor or other Terminal emulator program will read from that USB COM port.

Serial software emulate a serial port, diferent from a native port which has register to save all bits in order and them set a flag to call the main loop, a software serial has nothing of that.
Software serial must receive all bits, one by one, so you must read a digital port, wait a specific time and read the digital pin again. You must make it 10 times (1 start bit, 8 data bits and 1 end bit). The time is very important.
For use a software serial you need to worry more about performance.

You can use a digital interrupt pin for the RX pin, so you are "called" in the down border (start bit) and the received the 8 bits.


AVR has no vprintf_P? Well this was unexpected. AVR libc has many the variants of printf, including vprintf, but is missing vprintf_P. Is this really just not present or implemented elsewhere?

It has vfprintf_P and stdout is a FILE. Why would you want to waste time and space with implementing vprintf_P as well?

If you really want it, you can make your own:

#define vprintf_P(...) vfprintf_P(stdout, __VA_ARGS__)

Incidentally, the source code to vprintf looks like this:

int
vprintf(const char *fmt, va_list ap)
{
    return vfprintf(stdout, fmt, ap);
}

That does exactly the same job as a preprocessor macro - just forwards your request on to the FILE-based function.

It is actually more efficient to use a preprocessor macro than needlessly nesting functions like that - less stack usage, less calls, etc (unless the compiler happens to choose to inline that function, which since it is in a library it likely won't).

The non-FILE based functions can be considered simple wrapper functions to the FILE-based ones. They are mostly provided for convenience, but are actually completely redundant and can all be replaced with direct calls to the FILE-based variant.  They mostly still exist purely for historical compatibility. And since _P is specific to AVR libc there is nothing historical for it to be compatible with.


How to use 503 Thermistors for temperature? I have a black Thermistor with the number 503 on it.

I know that I would need a 50k resistor as a voltage divider.

I don't get to convert the number I am getting. I get the number 340 when my house is at 64*F.
I bought a kit on Amazon and it came with it and there is no documentation.A test with multimeter has shown at 17*C I get 30k ohms.

This is how it is wired:

[Ground] -- [50k-resistor] -- | -- [(503)thermistor] --[Vcc (5v)]
                              |
                         Analog Pin 0

First of, 503 means 50 x 10^3, ie 50K Ohm: that is the maximum resistance of this thermistor (the higher resistance occurs for lower temperatures). However, having just that without any precise reference may prove difficult to find a relevant datasheet that could help you calculate the temperature from the measured voltage.

I think what could work well is just simple calibration by establishing a mapping between
the value returned by analogRead() and the temperature measured by a real, good precision, thermometer.

Establighing the mapping for 2 extreme temperatures would provide a first approximation on computing any temperature from the read value.

However, such an approximation would not be very accurate because thermistors are not linear, ie their resitance don't vary linearly with temperature.

What you can try to do then, is to increase the number of mapped value<->temperature with regular intervals of temperatures; then you can use linear approximation between two consecutive mapped values, which would provide better results.

The difficulty here is to "produce" the temperatures for which you want to find the mapped value: if you can spend one year for that, then just let the chqanging seasons operate that for you :-) otherwise use what you can find at home: fridge, oven, fan, heater...

Here is a link to Jameco, one supplier of a 503 thermistor - it is a negative-coefficient thermistor. They have a link to a data-sheet for it. I can't say for sure that this is your device, but a simple experiment with your ohm-meter should confirm it.


(ESP8266) Check if a SSID is in range I need to check if a given SSID is in range. Would be good if it didn't disconnect from the current wifi network that it's connected to, but it doesnt matter, i just need to see if a SSID is in range, whether it does disconnect or not.
It should be something like this:

if(WiFi.SSID(checkforthisSSID)) {
  //do something
}

Thanks.

Not so tough it is possible just try the bellow code :)

void loop() {
  Serial.println("scan start");

  // WiFi.scanNetworks will return the number of networks found
  CheckPossibility();
  }

 CheckPossibility(){
 int n = WiFi.scanNetworks();
  Serial.println("scan done");
  if (n == 0)
    Serial.println("no networks found");
  else
  {
    Serial.print(n);
    Serial.println(" networks found");
    for (int i = 0; i < n; ++i)
    {
      // Print SSID and RSSI for each network found
      if(WiFi.SSID(i) == "REPLACE THIS WITH YOUR SSID"){ //enter the ssid which you want to search
      Serial.println("The network you are looking for is available");
      }
    }
  }
  Serial.println("");

  // Wait a bit before scanning again
 // delay(5000);
}

Try to connect to an AP, Use scan networks example, then look if the SSID in in the response.
Did not try, the scan networks example has an "WiFi.disconnect()" before the scan() function.


UART ESP and MEGA2560 Could someone help me with some suggestions please?
Using ESP8266 and MEGA2560 on UART interface i want to display the message received on the mega serial to the LCD connected to it on i2c. The problem is that the LCD shows some strange unknown character and the serial monitor corresponding to mega shows this :

LED on LED OFF LED on LED OFF LED on LED OFF LED on LED OFF LED on LED OFF LED on LED OFF LED on LED OFF LED on LED OFF LED on LED OFF LED on

when it should display this:

LED on
LED OFF
LED on
LED OFF
LED on
LED OFF
LED on
LED OFF
LED on
LED OFF
LED on
LED OFF
LED on
LED OFF
LED on
LED OFF
LED on
LED OFF

the code for ESP is this:

int pinLed = 16;
void setup()
{

 Serial.begin(115200);
 Serial.begin(115200);
 pinMode(16,OUTPUT);
 delay(500);
}

void loop()
{

digitalWrite(16,HIGH);
Serial.print("LED on\n");
delay(5000);

digitalWrite(16,LOW);
Serial.print("LED OFF\n");
delay(5000);

}

the code for mega is this:

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include<SoftwareSerial.h>
LiquidCrystal_I2C lcd(0x3F,20,4);

void setup()
{

  Serial.begin(115200);
  lcd.init();
  lcd.backlight();
  while (!Serial)
  {

    Serial.print("Attempting to connect! ");
    Serial.print("Trying again...");
  }
}

  void loop()
{

  if (Serial.available()>0)

  {
    char c = Serial.write(Serial.read());
    Serial.print(c);
    lcd.print(c);
  }
}

Solution to your problems.

Use println instead of print.
Change char c = Serial.write(Serial.read()); to char c = Serial.read();

Use:

println *emphasized text*

instead of

print *emphasized text*


Why Firmata Test doesn't allow me to choose a port? I'm a beginner and, sorry, also I don't speak English very well. However, I'm going to try to explain my problem.
I'm working on Ubuntu 14.04.2 and Arduino Uno R3.
I downloaded Firmata Test binaries for Linux 64 bit, I gave it permissions with chmod 754 <file>. Also I uploaded StandardFirmata from Arduino IDE to the board. Afterwards, I quit Arduino IDE and ran Firmata Test with ./file. But, the Port menu has no items within. I tried restarting the board and the application as well.

What can I do?

I had the same problem until I ran it as:
sudo ./file


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.


Uploading a sketch causing an error message in Arduino Uno avrdude:

  no programmer has been specified on the command line or the config
  file
           Specify a programmer using the -c option and try again

On the "Tools" menu choose "Programmer:" and specify AVRISP mkII; be sure that you've also chosen the appropriate "Board:" entry for the Uno.

I fixed it. I just reinstalled the drivers.


Where Can I Find a 12v Solder-less Breadboard Power Supply? I am trying to find a 12v input and 12v output breadboard power supply but I can't find one. I am making an arduino-controlled lock but the Arduino cannot power the lock strike by itself so I need to use a seperate power supply. The link to make things clearer:
http://www.instructables.com/id/Arduino-RFID-Door-Lock/#step0

There is nothing special about a "breadboard power adapter" that isn't served by a normal regulated supply. Simply use wires or a barrel jack or some other connector to connect any regulated supply to the breadboard as desired.

They sell 5V/3.3V breadboard supplies on eBay for $3-$5 shipped from China. Buy one and rewire/modify it to bypass the voltage regulator