Sending data through esp8266 using arduino I'm trying to send GPS data using esp8266 using Arduino board. I've used neo-6m receiver and esp8266-01 module. Below is my program using AT commands. The program is successfully compiled and loaded to the Arduino board, but the only output it gives on serial monitor is a simple begin. None of the AT commands are being executed. Not even the module connects to wi-fi. I can't point the error in my code. Please help me find the possible error.
Thank you

#include <TinyGPS++.h>
#include <SoftwareSerial.h>

TinyGPSPlus gps;

String ssid = "JioFi_244DB1D";

String password = "q52fq74c9s";

SoftwareSerial esp(6,7);

SoftwareSerial ss(8,9);

char Lat[12], Lon[12], alt[12],ch;

byte NOS;

byte l;

String webpage;

void reset(){

  esp.println("AT+RST");

  delay(1000);

  if(esp.find("OK"))

    Serial.println("Module Reset");

    }

    void ConnectWifi(){

      esp.println("AT+CIPMUX=1");

      esp.println("AT+CWMODE=1");

      String cmd = "AT+CWJAP=\""+ssid+"\",\""+password+"\"";

      esp.println(cmd);

      delay(4000);

      if(esp.find("OK"))

      Serial.println("Connected!");

      else {

        ConnectWifi();

        Serial.println("Connecting..");

        }

      }

void setup(){

  esp.begin(9600);

  Serial.begin(9600);

    Serial.println("begin");

  reset();

  ConnectWifi();

  esp.println("AT+CIFSR");

  while(esp.available()>0){

  if(esp.find("STAIP"))

  {Serial.println("IP Address:");

  while(esp.available()>0)

  {ch=esp.read();

  Serial.print(ch);}

  }}}

void loop() {

    ss.listen();

    delay(2000);

    while(ss.available()>0)

    {

    gps.encode(ss.read());

    {

      if(gps.location.isValid()){

           // dtostrf(gps.location.lat(),1,6,Lat);

      //dtostrf(gps.location.lng(),1,6,Lon);

      webpage = "<!DOCTYPE html><form method = \"post\" action =\"http://localhost/php/esppost.php\">Latitude:<\label><input type=number id = \"latitude\" name= \"latitude\" readonly value=";

        //                L = Lat.length();

      l= webpage.length();

      esp.println("AT+CIPSEND=0,");

      esp.print(9+l+5);

      esp.println(webpage);

      esp.print(gps.location.lat(),6);

      esp.print("\">");

      delay(500);

      webpage = "Longitude:<input type = \"number\" id = \"Longitude\" name = \"Longitude\" readonly value =\"";
      l=webpage.length();

      //L = Lon.length();

      esp.println("AT+CIPSEND=0,");

                        esp.print(9+l+5);

      esp.println(webpage);

      esp.print(gps.location.lng(),6);

      esp.print("\">");

      }

      else

      webpage="Location Invalid";

      l=webpage.length();

      esp.println("AT+CIPSEND=0,");

      esp.print(l+2);

      esp.println(webpage);

      delay(500);

      if(gps.altitude.isValid()){

      dtostrf(gps.altitude.meters(),1,6,alt);

      webpage = "Altitude:<\label><input type = number id=\"Altitude\" name=\"Altitude\" readonly value=";

      l=webpage.length();

      //L= alt.length();

      esp.println("AT+CIPSEND=0,");

      esp.print(9+l+2);

      esp.println(webpage);

      esp.print(gps.altitude.meters(),6);

      esp.print("\">");

      }

     if(gps.satellites.isValid()){

        NOS= gps.satellites.value();

        webpage= "<lable for = \"NOS \"> Number of Satellites:<\label><input type=number id=NOS name= NOS readonly value =";

        l= webpage.length();

        esp.println("AT+CIPSEND=0,");

        esp.print(2+l+22);

        esp.println(webpage);

        esp.print(gps.satellites.value());

        esp.print(">");

        delay(500);

     }}

    esp.println("AT+CIPCLOSE");

      }
}

SoftwareSerial can't listen on two instances. There is a .listen() function to switch between SoftwareSerial instances.

The esp8266 AT firmware doesn't wait until you listen on the SoftwareSerial instance. If there is a connection to the server it sends +IPD and data. If the SoftwareSerial instance doesn't listen the information about client connection is lost.

You must listen to esp8266 all the time, so you can't use two SoftwareSerial instances.

You could use the RX pin of Uno to receive data from GPS module over hardware Serial.


Debouncing a limit switch in Arduino ISR with delays I have a limit switch attached to an arduino Mega 2650 for motion control. The limit switch's two Normally Open contacts are connected to an Arduino Pin and ground, such that when the Limit Switch is engaged, the Arduino Pin gets short circuited to ground.

As expected, I have bouncing issues with this setup. I confirmed it using counters in my ISRs. Finally, I wrote the following code that seems to reliably identify whether my limit switch is engaged or disengaged at any given point in time.

const int lsOuterLeftIn = 18; // lsOuterLeftIn is my Limit Switch
const int LED = 9;
volatile bool lsEngaged = false; // flag for limit switch engaged
void setup() {
    pinMode(lsOuterLeftIn, INPUT_PULLUP);
    pinMode(LED, OUTPUT);
    attachInterrupt(digitalPinToInterrupt(lsOuterLeftIn), ISR1, FALLING);
    attachInterrupt(digitalPinToInterrupt(lsOuterLeftIn), ISR2, RISING);
}
void  loop() {
    if (lsEngaged) digitalWrite(LED, HIGH);
    else digitalWrite(LED, LOW);
}
void ISR1(){
    delay(100);
    lsEngaged = (digitalRead(lsOuterLeftIn));
}
void ISR2(){
    delay(100);
    lsEngaged = (digitalRead(lsOuterLeftIn));
}

But, here is my problem. I came upon this Arduino documentation page, and it says

"Since delay() requires interrupts to work, it will not work if called inside an ISR. "

But, I do make use of delay() inside ISRs and it seems to work, what is going on? Do I have a situation where things are working at the moment, but could break easily because the delay() function could malfunction on me as the documentation says?

What you can do (and is anyway far better than waiting in interrupt context), is to have a volatile variable, which you set in the interrupt (say to 1) and in the main loop you check it: once it is set, you execute the delay and then read the value.

Alternatively, if you can change the sensor, just trade the mechanical switch for an optical end run sensor. If your moving object has steady movement, you will not get any bounces from the optical coupler. Then you can just poll it.


How to call class A's method from class B? I wish to access methods and fields, as well as change them, of class A from class B. Since the main Arduino sketch is not a class, but a list of fields and methods, I created a separate MainClass with a method printStuff() that I want to call from class DoClass. This is how I go about it:

The main sketch:

#include "MainClass.h"
MainClass m;
void setup() {
  m.setup();
}
void loop() {
  m.loop();
}

MainClass.h:

/*
  MainClass.h
*/
#ifndef MainClass_h
#define MainClass_h
#include "Arduino.h"
class MainClass
{
  public:
    MainClass();
    void setup();
    void loop();
    void printStuff();
};
#endif

MainClass.cpp:

/*
  MainClass.cpp
*/

#include "Arduino.h"
#include "MainClass.h"
#include "DoClass.h"
MainClass::MainClass()
{
  d DoClass(this);
}
void MainClass::setup(){
  Serial.begin(9600);
}
void MainClass::loop(){
  d.callMainClassFunct();
}
void MainClass::printStuff(){
  Serial.println("printing stuff");
}

DoClass.h:

/*
  DoClass.h
*/
#ifndef DoClass_h
#define DoClass_h

#include "Arduino.h"
#include "MainClass.h"
class DoClass
{
  public:
    DoClass(MainClass m);
    void callMainClassFunct();
  private:
    MainClass _m;
};
#endif

DoClass.cpp:

/*
  DoClass.cpp
*/

#include "Arduino.h"
#include "MainClass.h"
#include "DoClass.h"

DoClass::DoClass(MainClass m)
{
  _m = m;
}

void DoClass::callMainClassFunct(){
  _m.printStuff();
}

This produces a myriad of errors. Each time I change something, a new kind of error appears, as though I was in a vicious cycle. Clearly, I am unfamiliar with C++. It would greatly help me if you could alter my code so that it works, keeping in mind that I would like to both access methods and fields of class MainClass from class DoClass and change those fields from class DoClass.

For reference, in Java, I would achieve the same in the following way:

MainClass.java:

public class MainClass{
    DoClass d;

    public MainClass(){
        d = new DoClass(this);
}

    public void setup(){

}

public void loop(){
    d.callMainClassFunct();
}

public void printStuff(){
    Serial.println("print stuff");
}

}

DoClass.java:

public class DoClass{
       MainClass _m;
       public DoClass(MainClass m){
          _m = m;
       }
       public callMainClassFunct(){
         _m.printStuff();
}

}

Passing this to the constructor od DoClass passes the value of the reference pointing to MainClass instantitated in the main sketch file. Then, by prepending the name of the instantiated object (in this case, "m"), followed by a dot, I can simply access and change all values of that object from DoClass (provided those methods and fields are visible to DoClass, which is the case here).

I have posted before about this issue, but did not receive any answers to my specific question and could not comment because I do not have enough reputation. Thank you to those who tried to answer me, but the answers did not pertain to my specific question. This time I have included more information to show my problem more clearly. Thank you in advance for your help.

In your Java version, you define MainClass like this (my comments added):

public class MainClass{ // Define a new Class
    DoClass d;          // Add a member variable to the class
    public MainClass(){
        d = new DoClass(this); // Initialise the member variable
    } // MainClass()
} // MainClass

In your C++ you don't do the same thing - but you should! The class needs a DoClass member so that you can use it in other MainClass functions:

// MainClass.h
...
#include "DoClass.h" // Need the .h here - remove it from the .cpp
class MainClass
{
  public:
    MainClass();
    void setup();
    void loop();
    void printStuff();
  private:
    DoClass _d; // Create a private member variable to use
};

and

// MainClass.cpp
MainClass::MainClass() : // MainClass constructor (note colon)
           _d(*this) // Initialise member
{
} // MainClass::MainClass()

Now, you want DoClass to be able to use MainClass, so you passed it into DoClass's constructor. But DoClass cannot have a MainClass inside it - MainClass already has a DoClass inside it! Infinite impossibility! So you need DoClass to merely contain a reference to the MainClass that it sits inside. That's the C++ unary & operator (different from the binary & operator), which is used similar to the pointer * operator:

// DoClass.h
...
// Need to advise compiler MainClass exists...
// but can't #include MainClass.h! Infinite loop!
class MainClass;

class DoClass
{
public:
    DoClass(MainClass &m); // Reference to MainClass
    void callMainClassFunct();
private:
    MainClass &_m; // Reference to MainClass
};

and

// DoClass.cpp
DoClass::DoClass(MainClass &m) : // DoClass constructor - note colon
         _m(m) // Initialise member variable
{
}


ESP8266 constantly reconnects So, my ESP8266 now has this problem where every three seconds it goes offline for a split second and the light blinks as it comes back. It seems to be constantly resetting... I recieved this problem when I had it connected to a power brick in my pocket, and I am pretty sure it happened because of static. I would have bought a protective case for it but it appears that I csn only find 3D printed parts but I currently do not own a 3D printer. I am wondering how I can fix it. If I try to re-flash it the re-flash fails because it disconnects before the flashing finishes.

I managed to fix the problem. I have a PC with Ubuntu 16.04 and I tried to re-flash it using Ubuntu's ESPTool, which was why it was failing. I noticed it failed constantly at a certain point. To fix it, I re-flahed the firmware with this python script, and it was successful.


Which is better millis() or timer? I want to create a 30 minutes delay in my program (Arduino).

which is better millis() or timer for this purpose?

please give me an example to clarify my doubt ...

Thanks.

It depends on your need:

1. No other activities / main power

If during those 30 minutes (I guess), the MCU does not have to do anything else (except maybe handling some short interrupts), than you can use a delay. You can use this if your power source is an adapter, but you waste a lot.

Advantage: Easy to program
Disadvantage: Power will continue to be used.

2. No other activities / battery

If you have the same conditions as above, but using a battery, than as Juraj mention, use the sleep functionality of the Arduino. You need an (external) real time clock or other circuitry to activate the wakeup signal after 30 minutes.

Advantage: Very less power used during the 30 minute delay
Disadvantage: Slightly more programming

3. Other activities

If you want to do now (or later) other code to be executed during the 30 minute wait, use millis(). For example, when you want to extend your project using other libraries that needs a faster than 30 minute response.

Advantage: You can do other tasks meanwhile
Disadvantage: More power usage, slightly more programming


LCD not working with Arduino Uno I am a new learner on Arduino. I am trying to learn how to control the LCD. I looked in the article, "Hello World!", and followed the instructions but it did not work (I checked it many times). The result I got is shown below (the text is not showing).

Please help me. Any help is appreciated.

Here is my code:

    #include <LiquidCrystal.h>
    LiquidCrystal lcd(12, 11, 5,4,3,2);

    void setup() {
      // set up the LCD's number of columns and rows:
     lcd.begin(16, 2);

    lcd.print("hello, world!");
    }

    void loop() {
      // set the cursor to column 0, line 1
      // (note: line 1 is the second row, since counting begins with 0):
      lcd.setCursor(0, 1);
      // print the number of seconds since reset:
      lcd.print(millis() / 1000);
    }

There are 3 things you can try.

1.
If you have any male pins, solder those to the lcd screen, then stick it in the breadboard. After that you can stick the wires in the breadboard appropriately. The first time I tried this the wires were either touching or not connected enough to the lcd screen.

2. Double check all the connections made. This also happened to me, just make sure all the wires are in their right places.

3. Have you tried adjusting the potentiometer? Thats what its there for. Try turning it slowly both directions to adjust the background and letter brightness.

From the looks of the picture, number 3 may be your problem. Try that step first, and if it doesn't work you can try the other two. Hope this helps!


Missing character when introducing delay in the code I am using the following code for reading any incoming message, and doing something after decoding the incoming string. There is a delay of 10sec in the code. When this delay is not introduced in the code, it is working nice. In this case, the output is like below.

+CIEV: "MESSAGE",1

+CMT: "+919080404532",,"2018/02/09,19:30:51+06"
This is an incoming test message

When the delay is introduced, I am unable to see the message on the serial monitor, and subsequent action is not taken by the code. The output is like below.

+CIEV: "MESSAGE",1
+CMT: "+919080404532",,"2018/02/09,1

It is clear that, I am missing some character in serial monitor. If delay is reduced to 400 ms, the output is like below.

+CMT: "+919080404532",,"2018/02/09,19:30:51+06"
This is an incoI am working other job

I checked the following, but did not get any improvement.

Serial.flush and mySerial.flush
Increased both hardware, and software aerial buffer size
used if (!mySerial.available() before delay
Changed baud rate for both
Instead of of Serial.readString(), I used Serial.read() character by    character inside function loop

Without use of the delay, it is working nice. I Think you guys are experienced, and can sort out the problem easily.

//while Introducing any delay in function loop, incoming message cant be read
//working with power failure but with serial monitor
#include <SoftwareSerial.h>
SoftwareSerial mySerial(9, 10);  // TX-Pin11, RX-Pin10
String str="";
void updateSerial()
{
  delay(2000);
  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 setup()
{
  Serial.begin(9600);
  mySerial.begin(9600);
  modemsetup();
}

void loop()
{
 Serial.println("I am working other job");
 //delay(10000);            //If you give this delay, then incoming message cant be read
 smstask();
}

void smstask()
{
if(mySerial.available())
{
str=mySerial.readString();
Serial.println(str);
int bra = str.indexOf('@');
int ket = str.indexOf('#');
String str1=str.substring(bra+1,ket);

if(str1=="server")
{
Serial.println(str);
int i=random(1,500);
String str2=(String)i;
String str3="@deviceA#"+str2;
mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
updateSerial();
mySerial.println("AT+CMGS=\"+917602304567\"\r"); // Replace x with mobile number
updateSerial();
mySerial.println(str3);// The SMS text you want to send
updateSerial();
mySerial.println((char)26);// ASCII code of CTRL+Z
updateSerial();
mySerial.println("AT+CMGD=1,4"); // AT Command to receive a live SMS
updateSerial();
}
}

}

void modemsetup()
{
  for(int i=0;i<3;i++)
  {
  mySerial.println("AT");          //Once the handshake test is successful, it will back to OK
  updateSerial();

  mySerial.println("AT+CSQ");      //Signal quality test, value range is 0-31, 31 is the best
  updateSerial();

  mySerial.println("AT+CCID");    //Read SIM information to confirm whether the SIM is plugged
  updateSerial();

  mySerial.println("AT+CREG?");    //Check whether it has registered in the network
  updateSerial();

  mySerial.println("AT+SNFS=0");  //Adjust to earphone mode(AT+SNFS=1 is microphone mode)
  updateSerial();

  mySerial.println("AT+CRSL=2");  //Adjust volume, volume range is 0-15, maximum:15
  updateSerial();

  mySerial.println("AT+CMGF=1");
  updateSerial();

  mySerial.println("AT+CMGD=1,4");
  updateSerial();
  }

  mySerial.println("AT+CMGS=\"+917602304567\"\r");
  updateSerial();

  mySerial.println("I am SMS from GSM Module");
  updateSerial();

  mySerial.println((char)26);// ASCII code of CTRL+Z
  updateSerial();

}

If serial data is coming in, and your code is doing a delay, the incoming data is stored in a buffer (of 64 bytes). But if you wait too long, the buffer will fill-up. Once it's full, any further incoming serial data isn't stored, and will be lost.

In your third output example, you get exactly 63 characters. Which is the maximum size a 64-byte cyclic buffer can store.


How to properly run 4 DC motors with an Arduino? I am working on a project where I have 4 DC motors that is controlled by 2 L293D motor drivers.  2 of the motors act as the wheels of the robot, and the other 2 act as a mop.

The Arduino board is powered through the USB port.  The DC motors are powered by the L293D motor driver through the 5V pin on the Arduino.  Alongside the motors, an ultrasonic sensor and a water sensor is also using the 5V pin.

This is what the robot should be doing:
The robot will move forward.  If it senses an obstacle through the ultrasonic sensor, it will turn right.  If it senses water through the water sensor, the robot will stop moving and the mop will start spinning.  After cleaning the water spillage, it will move forward again, just like what it did before.

It seems like the motors are not getting enough power, because whenever I place it on the floor, it doesn't move.

The base / platform of the robot is a plywood, which is heavy for the robot, and also which I think is a factor that affects the spinning of the wheels.

I also have a 9V battery, which I think could power the motors, but I don't know how to connect it.  How am I supposed to connect it to the L293D motor driver? I think, I should connect the positive side of the 9V battery to the VCC 2 pin of the L293D motor driver. But, where should I connect the negative side of the 9V battery?

With out knowing the demands of the motors (how much current they need under a given load) it is difficult to answer your question.  But, in most Arduino designs:

Motors are powered independently of the Arduino.  And when Arduino Uno is powered through its USB port it should be realized that most common USB power sources are only obliged to offer up to 500mA of current.
The motor's power source likely needs to be capable of providing several Amps. A common 9 Volt battery only contains about 500mAh and will likely drain in 10s of minutes if it works at all.

Consider the power pack used in common portable electric power tools.  This should give you a perspective of the type of power you will need in order to create a robot with multiple motors.


How to turn two LED's on and off with one button? I was wondering how to write a code that would do this, WITHOUT using IF and ELSE: when the button is pressed, one LED is on and the other one is off, but when the button is not pressed, the LED that was on turns off and the other one turns on.

Just use the return value of digitalRead (which is 1 or 0) as the input to digitalWrite:

int btnVal = digitalRead(3);
digitalWrite(4, btnVal);      // On when button is HIGH
digitalWrite(5, 1 - btnVal);  // Off when button is HIGH

Or using boolean instead:

bool btnVal = digitalRead(3);
digitalWrite(4, btnVal);      // On when button is HIGH
digitalWrite(5, !btnVal);     // Off when button is HIGH


Reading serial.print data with unknown characters python I've got some simple python code working to read the serial.print data that is being sent from my Arduino Uno. It seems to be receiving the values correctly and printing them fine, however it is not receiving it exactly as I expected and I cant find a way to get rid of the extra characters.

Here is what the output looks like, with the 'b's and the apostrophes which shouldn't be there:

  b'0 L/hour'

  b'0 L/hour'

  b'0 L/hour'

  b'0 L/hour'

  b'0 L/hour'

  b'64 L/hour'

  b'648 L/hour'

  b'168 L/hour'

  b'8 L/hour'

My python code is as follows:

import serial
arduino = serial.Serial('COM1', 9600, timeout=.1)

while True:
    data = arduino.readline()[:-2]  # the last bit gets rid of the new-line chars
    if data:
        print(data)

and the arduino code:

volatile int  flow_frequency;  // Measures flow meter pulses
unsigned int  l_hour;          // Calculated litres/hour
unsigned char flowmeter = 2;  // Flow Meter Pin number
unsigned long currentTime;
unsigned long cloopTime;

void flow ()                  // Interruot function
{
   flow_frequency++;
}

void setup()
{
   pinMode(flowmeter, INPUT);
   Serial.begin(9600);
   attachInterrupt(0, flow, RISING); // Setup Interrupt
                                     // see http://arduino.cc/en/Reference/attachInterrupt
   sei();                            // Enable interrupts
   currentTime = millis();
   cloopTime = currentTime;
}

void loop ()
{
   currentTime = millis();
   // Every second, calculate and print litres/hour
   if(currentTime >= (cloopTime + 1000))
   {
      cloopTime = currentTime;              // Updates cloopTime
      // Pulse frequency (Hz) = 7.5Q, Q is flow rate in L/min. (Results in +/- 3% range)
      l_hour = (flow_frequency * 60 / 7.5); // (Pulse frequency x 60 min) / 7.5Q = flow rate in L/hour
      flow_frequency = 0;                   // Reset Counter
      Serial.print(l_hour, DEC);            // Print litres/hour
      Serial.println(" L/hour");

   }
}

is it the arduino side or the python side that is adding the extra characters? I want to remove the "b" and apostrophes...

This is not an answer, but you have a insidious little problem in your code that can be easily solved disabling interrupts before using flow_frequency:

  if(currentTime >= (cloopTime + 1000))
   {
     cloopTime = currentTime;              // Updates cloopTime
       // Pulse frequency (Hz) = 7.5Q, Q is flow rate in L/min. (Results in +/- 3% range)
      noInterrupts();
      int flow_copy = flow_frequency;
      flow_frequency = 0;                   // Reset Counter
      interrupts();
      l_hour = (flow_copy * 60 / 7.5); // (Pulse frequency x 60 min) / 7.5Q = flow rate in L/hour

The reason is that you need to freeze flow_frequency so it doesn't change while you are using it. If an interrupt comes while your are using flow_frequency, you will end up with a value that's a mixed of old and new.

Solution: Copy the values updates inside the ISR before using them. Disable interrupts before doing it and reenable after that.

Reason: High level operations like flow_frequency++ and flow_frequency=0 are not atomic. At machine level they are composed of multiple machine instructions, which can be interrupted at any time, leaving things in an undeterminated state.


Motor control using arduino board I want to control 2 dc motors using the arduino board directly. One motor must rotate clockwise and the other counter clockwise. The directions  doesn't change only the speed of each motors. Can this be done without any shield? Them motors may need a higher voltage than the arduino can provide. If I link the arduino board to a power source of about 15 V (the board is arduino mega limits between 6 and 20 ) and I use "analog.write()" function can I output more than 5 volts(the internal voltage)?

Simplest way to do this is two MOSFETs (one per motor, because you don't need to change direction), and some miscellaneous passives, and a flyback diode for each motor.

See this tutorial for wiring diagrams and details.


RGB Not displaying Red when using LCD I was testing my RGB (common anode) on its own playing with colours and got the red, green to work as desired.

However, when I connected my LCD board to my Arduino Uno as well as the RGB (using the same code prior and same output pins so I know the code isn't the issue) the RGB no longer displays red.

I assume it has something to do with the fluctuating voltage/current after I've put in the LCD but I cant work out how to resolve it. When its meant to be red it's just nothing, doesn't light up, green however still works.

#include <LiquidCrystal.h>
#define COMMON_ANODE
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
int SelectCounter = 0;
int hours = 0; // start hours
int minutes = 0; //start min
int seconds = 5; //start seconds
int redPin = A1;
int greenPin = 2;
int bluePin = 3;
int digitposition = 0;
int readkey;
int speaker = A5;
int buttonPin = A4;
int buttonPushCounter = 0;   // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0;

void setup() {
pinMode(speaker, OUTPUT);
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
pinMode(buttonPin, INPUT);
Serial.begin(9600);
}

void loop() {
noTone(speaker);
setColor(0, 0, 255); // red

....... }

void trigger() {
  lcd.clear(); // clears the screen and buffer
 lcd.setCursor(6,0);
 lcd.println("MUM:      ");
 lcd.setCursor(4, 1); // set timer position on lcd for end.
 lcd.println("WAKE UP!    ");
 tone(speaker, 10);
 setColor(0, 255, 0);  // green
 delay(500);
 digitalWrite(A1, HIGH);
 digitalWrite(2, HIGH);
 digitalWrite(3, HIGH);
 noTone(speaker);
 delay(500);
 lcd.display();
 }

void setColor(int red, int green, int blue)
{
  #ifdef COMMON_ANODE
   red = 255 - red;
   green = 255 - green;
   blue = 255 - blue;
 #endif
  analogWrite(redPin, red);
  analogWrite(greenPin, green);
  analogWrite(bluePin, blue);
}

Only the pins with a ~ next to it are PWM pins. The pin connected to the red led, pin A1, does not support PWM, so analogWrite will not have the desired effect.


Can you help me combining these sensor sketches as one in Arduino I want to combine these three sketches into one.

RAIN SENSOR:

int rainPin = A0;
int greenLED = 6;
int redLED = 7;
// you can adjust the threshold value
int thresholdValue = 500;

void setup(){
  pinMode(rainPin, INPUT);
  pinMode(greenLED, OUTPUT);
  pinMode(redLED, OUTPUT);
  digitalWrite(greenLED, LOW);
  digitalWrite(redLED, LOW);
  Serial.begin(9600);
}

void loop() {
  // read the input on analog pin 0:
  int sensorValue = analogRead(rainPin);
  Serial.print(sensorValue);

  if(sensorValue < thresholdValue){
    Serial.println(" - It's wet");
    digitalWrite(greenLED, LOW);
    digitalWrite(redLED, HIGH);
  }
  else {
    Serial.println(" - It's dry");
    digitalWrite(greenLED, HIGH);
    digitalWrite(redLED, LOW);
  }
  delay(500);
}

LIGHT SENSOR:

int ldrPin = A0;
int greenLED = 6;
int redLED = 7;
// you can adjust the threshold value
int thresholdValue = 500;

void setup(){
  pinMode(ldrPin, INPUT);
  pinMode(greenLED, OUTPUT);
  pinMode(redLED, OUTPUT);
  digitalWrite(greenLED, LOW);
  digitalWrite(redLED, LOW);
  Serial.begin(9600);
}

void loop() {
  // read the input on analog pin 0:
  int sensorValue = analogRead(ldrPin);
  Serial.print(sensorValue);

  if(sensorValue < thresholdValue){
    Serial.println(" - light");
    digitalWrite(greenLED, LOW);
    digitalWrite(redLED, HIGH);
  }
  else {
    Serial.println(" - dark");
    digitalWrite(greenLED, HIGH);
    digitalWrite(redLED, LOW);
  }
  delay(500);
}

SMOKE SENSOR:

int smokeD0 = A5;
int greenLed = 11;
int redLed = 12;
// Your threshold value
int sensorThres = 300;

void setup() {
  pinMode(smokeD0, INPUT);
  pinMode(greenLed, OUTPUT);
  pinMode(redLed, OUTPUT);
  digitalWrite(greenLed, LOW);
  digitalWrite(redLed, LOW);
  Serial.begin(9600);
}

void loop() {
  int analogSensor = analogRead(smokeD0);
  Serial.println(analogSensor);

  // Checks if it has reached the threshold value
  if (analogSensor < sensorThres)
  {
    Serial.println(" - Smoke");
    digitalWrite(redLed, LOW);
    digitalWrite(greenLed, HIGH);
  }
  else
  {
    Serial.println(" - No Smoke");
    digitalWrite(redLed, HIGH);
    digitalWrite(greenLed, LOW);
  }
  delay(100);
}

I want to combine those codes as one with only two outputs:

the greenLED and;
the redLED.

Variable renaming

Rename thresholdValue in the first two sketches to rainSensorThreshold, and lightSensorThreshold respectively, and sensorThres to smokeSensorThreshold in the third sketch.

Rename sensorValue in the first two sketches to rainSensorValue, and lightSensorValue respectively, and analogSensor to smokeSensorValue in the third sketch.

Change the Analog pin
Use A1 (or some other analog input other than A0 or A5) for ldrPin in the second sketch, for example:
int ldrPin = A0;

Consistant LED pins
Use the same pins in the third sketch, as are used in the first two sketches, for the two LEDs and note the change in case:
int greenLed = 11;
int redLed = 12;

to
int greenLED = 6;
int redLED = 7;

Recompile each sketch
To check that the each sketch still works, recompile each one separately.
Combine the code
Finally... Splice the code together appropriately, keeping the three parts separate:

Global variables
setup()
loop()


Does the StringObject.reserve() function prevent memory fragmentation/leaks? I'm currently writing and testing a professional Arduino application, I'm aware of the dangers of using the String class, so I began to implement C-style strings in some places, but it's just way harder using them to receive data from a Software Serial port that's variable in size and needs some manipulation.

I've upgraded from an Arduino Uno to a Leonardo so my current minimum SRAM usage is 1325 bytes (51%)

Here's the relevant part of my code:

String serialContents;
char emailChar[SIZEOF_ARRAY][SIZEOF_CHAR];

void setup(){
  serialContents.reserve(70);
  SerialOne.begin(9600);
}

void loop{

  if (SerialOne.available() > 0) //something is there to be read
  {
    serialContents = SerialOne.readStringUntil('\n'); //make a string of the characters coming on serial
  }

  if (serialContents.length() >= 60)
  {
   serialContents = ""; //ignore serial data
  }
 else{
  serialContents = cutString(serialContents); //some String manipulation, no adding only cutting
  serialContents.replace("@", "%40");
  serialContents.toCharArray(emailChar[count], 31);
  serialContents = ""; //String reset
}

So my question is, does something like this make my code unstable? Does the
reserve() function help at all?

Edit: Here's the cutString() function

String cutString(String request) {

  int points = request.indexOf(':');

  if (request.substring(0, points) == "CHECKOUT")
  {
    modoPedido[count] = 'o'; //char array
  }
  else if (request.substring(0, points) == "CHECKIN")
  {
    modoPedido[count] = 'i';
  }

  request = request.substring(points + 1);

  return request;
}

Reserving space will help reduce memory fragmentation, but much of what else you are doing is swamping that small improvement you have made.

The biggest area of concern is your cutString function, which you have omitted from your code above.  Passing a String as a parameter, modifying it, and then returning it again, ends up in new String objects being created and destroyed multiple times, which will make a mess of your heap.

Instead you should pass a String object by reference, and modify that object in-place. No need to return anything.

void cutString(String &theString) {
    // Modify theString here.
}

Of course, what you do in cutString could cause more problems - you should include that function in your code above so we can check it out.


Protocol options for data exchange between Arduino and ESP8266 I have a device built with an Arduino uno:

Arduino software installed on an Arduino uno
can be controlled via serial commands
can be controlled via physical buttons and sensors
on any button/sensor state change it writes the current state to serial
if no message has been sent within 5 seconds, it sends a no-change serial message

What is needed:

Use an ESP8266 to provide a bridge between current Arduino software and MQTT / web
I can program the ESP8266 as a web server, MQTT client, etc with the Arduino IDE or Lua (but I prefer the Arduino IDE since I can reuse parts of the code to generate / interpret communication).
the ESP8266 will handle everything that is required for wifi / web / MQTT; without the MQTT module the Arduino part will work stand-alone, only the remote control will be missing.
I would like to make minimal changes to the Arduino code (or none, if possible). Any changes would involve extensive re-testing, which I try to avoid.
the ESP8266 can be missing in some installs.

What options I found:

Serial

ESP8266 can read the serial output and be a bridge between web/MQTT and serial, will store the current state in memory to be sent when requested to avoid polling the device every time.

One of the benefits is no code changes / testing required for the Arduino part.

I2C

Make the Arduino the I2C master and the ESP8266 the slave (or the other way around) and implement bi-directional communication. Got the idea by reading this thread.

Some other information about the serial commands:

A data packet (command or state description) consists of 1 to 20 characters, with a possible peak of 20 packets in 5 seconds, and an average of one packet every 3 seconds. If needed, I can make this send 5 unsigned integers instead of alphanumeric characters.

If more than the I2C / serial pins are needed I can upgrade to an Arduino Mega (so the number of free pins is not an issue).

Are there any other options for this? (protocols, pre-made libraries for serial communication, etc). I'm trying not to reinvent the wheel..

Thank you for your time!

Most I2C tutorials made each Arduino a slave and master, but this approach is better, because each Arduino is either a master or a slave (not both) and no switching is needed. That makes things easier.

I2C is better than serial, because you can add more Arduinos in the same bus.

I have implemented I2C between two Arduinos and it's not more complicated that reading/writing to the serial port (which you have already done). And I bet you can generalize your serial port code to work with both serial and I2C comms.

This is my example (just a proof of concept). The slave Arduino controls a some pins, a temp. sensor and a watchdog under orders from the master Arduino. If slave doesn't receive a beat in time, it reset the master Arduino.

Master code

#include <Wire.h>

#define CMD_SENSOR    1
#define CMD_PIN_ON    2
#define CMD_PIN_OFF   3
#define CMD_LUMEN     4
#define CMD_BEAT      5

const byte SLAVE_ADDRESS = 42;
const byte LED = 13;

char buffer[32];

void setup ()
{
  Serial.begin(9600);
  Serial.println("Master");

  Wire.begin ();

  pinMode (LED, OUTPUT);
  digitalWrite(LED, HIGH);
  delay(1000);
  digitalWrite(LED, LOW);

  Wire.beginTransmission (SLAVE_ADDRESS);
  Serial.println("Send LED on");
  Wire.write (CMD_PIN_ON);
  Wire.write (2);
  Wire.write (10);
  Wire.endTransmission();
  int x = Wire.requestFrom(SLAVE_ADDRESS, 1);
  Serial.print("status=");
  Serial.println(x);
}  // end of setup

void loop ()
{
  Serial.println(".");
  Wire.beginTransmission (SLAVE_ADDRESS);
  Wire.write (CMD_SENSOR);
  Wire.endTransmission();
  int x = Wire.requestFrom(SLAVE_ADDRESS, 1);
  Serial.print("Disponibles = ");
  Serial.println(x);
  int temp = (int) Wire.read();
  Serial.println(temp);

  Wire.beginTransmission (SLAVE_ADDRESS);
  Wire.write (CMD_LUMEN);
  Wire.endTransmission();
  Wire.requestFrom(SLAVE_ADDRESS, 2);
  int light = Wire.read() << 8 | Wire.read();
  Serial.print("Light=");
  Serial.println(light);

  Wire.beginTransmission (SLAVE_ADDRESS);
  Wire.write (CMD_BEAT);
  Wire.endTransmission();
  Wire.requestFrom(SLAVE_ADDRESS, 1);

  delay (5000);
}  // end of loop

Slave code

/*
   Esclavo I2C

   Recibe los siguientes comandos
   <- 1° byte -> <- 2° byte -> <- 3° byte ->
   CMD_SENSOR
   CMD_PIN_ON    n° de pin     duracion en segundos
   CMD_PIN_OFF   n° de pin
   CMD_LUMEN
   CMD_BEAT

   Cada comando recibe una respuesta, ya sea el valor pedido
   o un status.
*/
#include <max6675.h>
#include <Wire.h>

typedef struct {
  int pin;
  unsigned long off;
} PIN_PGMA;

/*
   Lista de pines que se pueden activar via CMD_PIN_ON.
*/
#define PIN_LUMEN   A0
#define PIN_LED      2
#define PIN_RESET    3
PIN_PGMA pgma[] = {
  {PIN_LED, 0},
  {PIN_RESET, 0}
};
const int pgmaSize = sizeof(pgma) / sizeof(PIN_PGMA);

#define CMD_SENSOR    1
#define CMD_PIN_ON    2
#define CMD_PIN_OFF   3
#define CMD_LUMEN     4
#define CMD_BEAT      5

#define ST_OK         0
#define ST_BAD_PIN    1
#define ST_TIME_0     2
#define ST_BAD_LEN    3

#define MY_ADDRESS  42

//  Maximo tiempo de espera entre comandos CMD_BEAT. Pasado
//  ese tiempo, se activa el PIN_RESET.
//  En milisegundos.
#define BEAT_INTERVAL 10000
unsigned long lastBeat;
//  Largo del reset en milisegundos.
#define RESET_LENGTH  250
byte cmd = 0;
byte status = 0;

int thermoDO = 11;
int thermoCS = 12;
int thermoCLK = 13;

MAX6675 thermocouple(thermoCLK, thermoCS, thermoDO);

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

  pinMode(PIN_LUMEN, INPUT);
  analogRead(PIN_LUMEN);

  for (int i = 0; i < pgmaSize; i++) {
    pinMode(pgma[i].pin, OUTPUT);
    digitalWrite(pgma[i].pin, LOW);
  }
  lastBeat = millis();

  Wire.begin (MY_ADDRESS);
  Wire.onReceive (receiveCommand);
  Wire.onRequest (sendAnswer);
}

void loop()
{
  unsigned long now = millis();

  //  Baja la linea de RESET si no ha recibido un beat ultimamente.
  unsigned long diff = now - lastBeat;
  if (diff > BEAT_INTERVAL) {
    resetPin();
  }

  //  Recorre la lista de pines y apaga aquellos cuyo tiempo termino.
  for (int i = 0; i < pgmaSize; i++) {
    if (pgma[i].off > 0 && pgma[i].off <= now) {
      Serial.print("off pin="); Serial.println(pgma[i].pin);
      pgma[i].off = 0;
      digitalWrite(pgma[i].pin, LOW);
    }
  }
}

// called by interrupt service routine when outgoing data is requested
void sendAnswer() {
  byte temp;
  int  lightReading;

  switch (cmd) {
    case CMD_SENSOR:
      temp = thermocouple.readCelsius();
      Wire.write(temp);
      break;
    case CMD_LUMEN:
      lightReading  = analogRead(PIN_LUMEN);
      Wire.write(lightReading >> 8);
      Wire.write(lightReading % 0xFF);
      break;
    case CMD_PIN_ON:
    case CMD_PIN_OFF:
    case CMD_BEAT:
      Wire.write(status);
      status = ST_OK;
      break;
  }
  cmd = 0;
}

// called by interrupt service routine when incoming data arrives
void receiveCommand (int howMany) {
  cmd = Wire.read ();
  status = ST_OK;
  switch (cmd) {
    case CMD_PIN_ON:
      cmdPinOn();;
      break;
    case CMD_PIN_OFF:
      cmdPinOff();
      break;
    case CMD_BEAT:
      lastBeat = millis();
      break;
  }
}  // end of receiveEvent

void cmdPinOff() {
  if (Wire.available() != 1) {
    status = ST_BAD_LEN;
  } else {
    int pin = Wire.read();
    int i = searchPin(pin);
    if (i < 0) {
      status = ST_BAD_PIN;
    }
    else {
      pgma[i].off = 0;
      digitalWrite(pin, LOW);
    }
  }
}

int searchPin(int pin) {
  int i = pgmaSize - 1;
  while (i >= 0 && pgma[i].pin != pin) {
    i--;
  }
  return i;
}

/*
 * Programa el encendido y duracion del RESET.
 */
void resetPin() {
  if (digitalRead(PIN_RESET) == LOW) {
    unsigned long now = millis();

    int i = searchPin(PIN_RESET);

    pgma[i].off = now + RESET_LENGTH;
    lastBeat = now;
    digitalWrite(PIN_RESET, HIGH);
  }
}

void cmdPinOn() {
  if (Wire.available() != 2) {
    status = ST_BAD_LEN;
  } else {
    int pin = Wire.read();
    int len = Wire.read();

    int i = searchPin(pin);
    Serial.print("pin="); Serial.print(pin); Serial.print(",index="); Serial.println(i);
    if (i < 0) {
      status = ST_BAD_PIN;
      Serial.println("bad pin");
    } else {
      if (len == 0) {
        status = ST_TIME_0;
        Serial.println("ban len");
      }
      else {
        pgma[i].off = millis() + len * 1000;
        digitalWrite(pin, HIGH);
        Serial.println("ok");
      }
    }
  }
}


(noob) 2 servos for robot (head & chest) movement at different speeds at once I have an Arduino Uno and two Hi-tec Servos HS-40 & 5055 digital that I'm using for a basic robot build. I'm trying to have 1 servo(HS-40) turn the head back and forth (left to right) slightly faster than other servo (HS-5055) controlling the upper torso. I would like to have each servo working at the same time but not at the same speed without waiting for 1 servo to complete it's movement. I tried a sketch with a delay of 45-50 which seems to work fine for the movement speed and 0-75 degrees is ideal for the head travel and 0-65 degrees for the torso travel. I would like to have this movement to be repeated continuously so the robot mimics like his is looking side to side or left to right naturally. Please help as I tried many sketches but can't find one that works like this. I tried modifying other codes but can't get them work. Any help will be greatly appreciated.
How do modify this code so just the second servo runs at 40 which will slow down just enough? Also this is not my code, but it's one that seems to be close to what I'm trying to do.
#include <Servo.h>

Servo servo1;
Servo servo2;

int i = 0;

void setup() {
  servo1.attach(8);
  servo2.attach(9);

}

void loop() {
  for (i = 0; i < 70; i++) {
    servo1.write(i);
    servo2.write(i);
    delay(50);
  }
  for (i = 70; i > 0; i--) {
    servo1.write(i);
    servo2.write(i);
    delay(50);
  }

}

Heres a little sketch you can try.  It uses timing to accomplish the different servo speeds.  It won't give you the exact servo travel each loop but it sounds like you might not mind if it randomly is off by a few degrees each loop.
#include <Servo.h>
Servo servo1;
Servo servo2;
int i = 0;
void setup() {
  Serial.begin(9600);
  servo1.attach(8);
  servo2.attach(9);
}

int sweep_time = 3500; // 70 * 50ms = 3500

int head_degrees = 75; // sweep degrees for the head to move
int body_degrees = 65; // sweep degrees for the body to move

int millis_per_head_move = sweep_time / head_degrees;
int millis_per_body_move = sweep_time / body_degrees;

void loop() {
  int i = 0; int j = 0;
  unsigned long now_millis = 0;
  unsigned long start_sweep = millis(); // mark the time when we start the first sweep

  while ( millis() - start_sweep < sweep_time ) {  // keep moving first sweep until sweep time has elapsed
    now_millis = millis() - start_sweep;
    if (now_millis % millis_per_head_move == 0 ) servo1.write(i++);
    if (now_millis % millis_per_body_move == 0 ) servo2.write(j++);
    delay(1);
  }
  Serial.print(i); Serial.print(" "); Serial.println(j);

  start_sweep = millis();  // mark the time when we start the second/back sweep
  while ( millis() - start_sweep < sweep_time ) {  // keep moving second sweep until sweep time has elapsed
    now_millis = millis() - start_sweep;
    if (now_millis % millis_per_head_move == 0) servo1.write(i--);
    if (now_millis % millis_per_body_move == 0) servo2.write(j--);
    delay(1);
  }
  Serial.print(i); Serial.print(" "); Serial.println(j);
}


Confusion receiving I2C data from magnetic sensor So, I've found the address of my device using a I2C device scanner. I then looked up the datasheet for a magnetic sensor I am trying to grab data from.

I'm now trying to communicate with the device by following the 'Example Measurement' section in the data sheet.

Here is my code so far...

#include <Wire.h>
#define address 0b110000 // find the actual address, it is at 0x30, which is 0b00110000

void setup() {
  Serial.begin(9600);
  Wire.begin(address);
}

void loop() {
  int x, y, z;

  Wire.requestFrom(0b00110000, 1); // START condition?, starts with a 0 to indicate a WRITE request
  if(Wire.available() > 0) {
    Serial.println("1");
    Wire.read();
  }
  Serial.println(Wire.read());
  Wire.write(0b00000111);
  if(Wire.available() > 0) {
    Serial.println("2");
    Wire.read();
  }
  Wire.write(0b00000001);
  if(Wire.available() > 0) {
    Serial.println("3");
    Wire.read();
  }
  Wire.requestFrom(0b00110000, 1); // write request
  if(Wire.available() > 0) {
    Serial.println("4");
    Wire.read();
  }
  Wire.write(0b00000110);
  if(Wire.available() > 0) {
    Serial.println("5");
    Wire.read();
  }
  Wire.requestFrom(0b10110000, 1); // READ request
  if(Wire.available() > 0) {
    Serial.println("6");
    Wire.read();
  }
  // not sure what to do for the 7th cycle???
  // am I even doing the previous correct?
  Wire.endTransmission(address);
  delay(1000);
}

The numbers in each of the if statements represent the cycle within the 'Example Measurement' section of the datasheet, I'm never able to read data from the device and I am sure that I am doing something wrong.

I appreciate any help! This is my first time ever trying to understand I2C, and I've just been staring at this datasheet for too long without getting anywhere.

This is how you send a byte to your slave:

  Wire.beginTransmission(SLAVE_ADDRESS);
  Wire.write(someByteValue);
  Wire.endTransmission();

You must sandwich the writes between a beginTransmission/endTransmission. Output buffer is 32 bytes long, so keep things short.

Wire.write() doesn't write; just put thing in an output buffer, waiting for your endTransmission().

If you need an answer (said, a byte), first you said how many bytes you want and then read them:

  byte pin;
  Wire.requestFrom(SLAVE_ADDRESS, 1);
  if (Wire.available() == 1) {
    pin = Wire.read();
  }

Your are Wire.read()ing, but you are not capturing the return value!

Disclaimer: after requestFrom, you have to be prepared to wait for the data (it may be not inmediatly available). Also, data may arrive in chunks.


Arduino DUE samples per second with the DAC I want to know how many samples per second the arduino due DAC can generate, I need to generate an ultrasonic signal (40Khz), the arduino due is not going to do anything else that generate this signail for a very short period of time.

According to the datasheet:

  2-channel 12-bit 1 msps DAC

So it's possible to generate 1 million samples per second. Of course that kind of speed would need DMA to drive it smoothly.

Assuming you want to generate a sinewave at 40KHz you have to first ask yourself what resolution (time-wise) you want from that sinewave, since that's the frequency that you need to generate samples for. For instance, if you want 100 samples in your sine wave you'd need to generate those at 4Msps, which you can't. At 10 samples per cycle you'd have 400Ksps which is more manageable, but the quality of the sinewave would be pretty poor.

Or, if you don't need a sinewave, if a square wave would do, just use a normal digital IO pin. You can generate MHz then.


Arduino Ethernet Shield: May I connect it to a PC connected to the internet via wifi? I have an Arduino Ethernet shield.

May I connect it to a machine that´s connected wirelessly to the internet in order to get the arduino into the internet?

Or do I need to connect it only to a router?

Assuming an Ethernet port on the PC, the Ethernet shield can be connected to it using an Ethernet crossover cable:

(source: Wikipedia)

Many recent PC network interfaces have automatic cross-over (Auto MDI-X), with which even a regular (straight) Ethernet patch cable will work.

This merely addresses the physical Ethernet connectivity.

For actually routing IP packets between the Arduino and the rest of the Internet, some software router or software bridge is required to run on the PC. Several open source routing products exist, especially for Linux and FreeBSD, but that is outside the scope of this StackExchange.

Finally, the Ethernet shield does not need a router, it an as well be hooked up to an Ethernet switch or hub.


Atmega168 breaking out of ISR I wrote a code to handle an ISR triggered by UART input. I'm looking for 2 characters or more. I can handle extra characters and garbage values, but problem arises when I get less than 2 chars, specially when an empty string is sent to the atmel. The UART_receive() on the atmel gets stuck at: while ( !(UCSR0A & (1<<RXC0)) );

Is there any way I can break out of this? The code is posted below:

unsigned char USART_Receive_string(unsigned char *x, unsigned char size)
{
unsigned char i = 0;

if (size == 0) return 0;            // return 0 if no space

while (i < size - 1) {              // check space is available (including additional null char at end)
    unsigned char c;
    while ( !(UCSR0A & (1<<RXC0)) );  // wait for another char - WARNING this will wait forever if nothing is received
    c = UDR0;
    if (c == '\0') break;           // break on NULL character
    x[i] = c;                       // write into the supplied buffer
    i++;
}
x[i] = 0;                           // ensure string is null terminated

return i + 1;                       // return number of characters written
}

The actual ISR in question is posted below. It reads the value, sets a flag, and exits as soon as possible.

ISR(USART_RX_vect)
{
    len = USART_Receive_string(uart_string,4); //makes space for 2 character and "\0"
    UART_flag = 1;
}

The the buffer is set up in main()

unsigned char uart_string[20];

As a fundamental principle of design you should not be expecting to receive multiple characters in the ISR.

The interrupt fires when a character has been received, so that is all your program should count on finding.  You can if you really want to poll the UART when you are done reading the first character and see if another has arrived, but there would generally not be time for that to have happened and you definitely should not be waiting for it in the ISR.  Rather, if the ultimate consuming code needs multiple characters, then that should hold off executing dependent code until multiple invocations of the ISR have resulted in the collection of the needed number of characters.

Things can get a little more complicated on parts with multi-stage UART FIFOs, but that is not the case here.


Using Leonardo as keyboard: add wake and sleep functions I want to use a Leonardo with USB chip to emit some commands via USB port to a digital piano computer (running Windows 7) for various functions. I've gotten the Leonardo to emit page up and page down functions using a simple project I found on the web. What I need now is the following set of functions: left arrow, right arrow, F11, wake, and sleep. What I need help with is:

where is the complete list of functions available with keyboard.press?
are wake and sleep among those available?
if they aren't, what header file could be modified to include them?

Thank you for any suggestions.

It turns out there is a library that can be added to compile the media and system functions for USB keyboard connection into the Leonardo, as well as other Arduino modules. It is available through 'tools','library manager'; it is HID-project by NicoHood. There is an example program called "system example" at github to test it for for wake and sleep. It works perfectly.
I expect it'll work for the other functions too.


esp8266 + octocoupler relay: WDT reset when using AC current I'm trying to switch on bulb via 4 channel 5V optocoupler relay controller from ESP8266 using WIFI Access point. All my connections looking fine and i can able to connect WIFI SoftAP and send signal to ESP8266 01. Even i can able to switch the Relay from NO to NC or other way around. Only when a connect 240V AC current to relay for powering the bulb, i'm getting following error from ESP

21:11:34.312 ->  ets Jan  8 2013,rst cause:4, boot mode:(1,7)
21:11:34.312 ->
21:11:34.312 -> wdt reset

If i use 12V DC power to light the led via relay its working fine. if again use 240V power to relay to light bulb i'm get same error again.

I have already tried using ceramic capacitor for decoupling to avoid noise from AC. Still no luck. Please advice. I'm very new and naive at handling electronics.

Adding the circuit as well.

Update: After further testing, I can see following behaviour,
If i connect AC bulb to relay and turn it on. Then by provide a long gap before turning it off makes the ESP stable for longer time.

Even better, if i turn off/on my mobile wifi between each time i turn on or off the AC bulb then ESP is always stable.

Adding my code as well.

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

/* Set these to your desired credentials. */
const char *ssid = "*****";
const char *password = "*********";

ESP8266WebServer server(80);

const int led = 2;  //GPIO2

/* Just a little test message.  Go to http://192.168.4.1 in a web browser
 * connected to this access point to see it.
 */
void handleRoot() {

  int size=1000;
  char temp[size];

  int sec = millis() / 1000;
  int min = sec / 60;
  int hr = min / 60;

  snprintf ( temp, size,

"\

Status: Light ON

\

Turn ON

\

\

Turn OFF

\
  \
  ",

    hr, min % 60, sec % 60
  );
  server.send ( 200, "text/html", temp );

}

void setup() {
    delay(1000);
    Serial.begin(115200);
    Serial.println();
    Serial.print("Configuring access point...");

    /* You can remove the password parameter if you want the AP to be open. */
    WiFi.softAP(ssid, password);

    IPAddress myIP = WiFi.softAPIP();
    Serial.print("AP IP address: ");
    Serial.println(myIP);

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

  //URLs available to query
    server.on("/", handleRoot);
  server.on ( "/on", turnON );
  server.on ( "/off", turnOFF );
    server.begin();
    Serial.println("HTTP server started");

}

void turnON(){

  digitalWrite ( led, HIGH );

  int size=1000;
  char temp[size];

  int sec = millis() / 1000;
  int min = sec / 60;
  int hr = min / 60;

  snprintf ( temp, size,

"

Turn OFF

",

    hr, min % 60, sec % 60
  );

  server.send ( 200, "text/html", temp);

}

void turnOFF(){

  digitalWrite ( led, LOW );

  int size=1000;
  char temp[size];

  int sec = millis() / 1000;
  int min = sec / 60;
  int hr = min / 60;

  snprintf ( temp, size,

"

Turn ON

",

    hr, min % 60, sec % 60
  );

  server.send ( 200, "text/html", temp);

}

void loop() {
    server.handleClient();
}

To prevent EMI and to save the relay contacts, you could switch the relays at AC zero-crossing. Add some kind of zero-crossing detection to you project and before switching a relay, wait for a zero-crossing and then wait just before the next zero crossing (about 9500 microseconds at 50 Hz AC).

Simple is to use a current sensor to detect zero-crossing. Current AC wave should be aligned with the voltage wave, if there is no shift in power factor.


Arduino Timer with increase time button I have an Arduino project to do, which requires a countdown timer(which I've already done). I connected a push button, and when I press that button I need it to increase my countdown timer by +10 seconds.

Can anyone help me with adding the code for this button?

Here is the code so far(I declared the button, but I don't know if it's any good):

#include <LiquidCrystal.h>

int buttonPin = 7;
int buttonState = 0;
int seconds = 30; // count seconds
int minutes = 0; // count minutes
int hours = 0; // count hours
const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
//initialize the library with the numbers of the interface pins
LiquidCrystal lcd(rs, en, d4, d5, d6, d7); // pins connected to LCD

void setup()
{
  lcd.begin(16, 2); //set up the LCD's number of columns and rows
  pinMode(buttonPin, INPUT);
}
void loop()
{
  buttonState = digitalRead(buttonPin);
  lcd.setCursor(1, 0);
  lcd.print ("Sosire in:");
  lcd.setCursor(6, 1);
  lcd.print(":");
  lcd.setCursor(9, 1);
  lcd.print(":");

  seconds--;
  delay(1000);

 if (seconds < 0)
  {
    minutes--;
    seconds = 59;
  }
 if (minutes < 0)
  {
    hours--;
    minutes = 59;
  }
 if (hours < 0)
  {
    hours = 0;
    minutes = 0;
    seconds = 30;
  }
 if (minutes > 9)
  {
    lcd.setCursor(7, 1);
    lcd.print(minutes);
  }
 else
  {
    lcd.setCursor(7, 1);
    lcd.print("0");
    lcd.setCursor(8, 1);
    lcd.print(minutes);
    lcd.setCursor(9, 1);
    lcd.print(":");
  }

 if (seconds > 9)
  {
    lcd.setCursor(10, 1);
    lcd.print(seconds);
  }
 else
  {
    lcd.setCursor(10, 1);
    lcd.print("0");
    lcd.setCursor(11, 1);
    lcd.print(seconds);
    lcd.setCursor(12, 1);
    lcd.print(" ");
  }

 if (hours > 9)
  {
    lcd.setCursor(4, 1);
    lcd.print(hours);
  }
 else
  {
    lcd.setCursor(4, 1);
    lcd.print("0");
    lcd.setCursor(5, 1);
    lcd.print(hours);
    lcd.setCursor(6, 1);
    lcd.print(":");
  }
 if (seconds == 0)
  {
    lcd.clear();
    lcd.print("Este in statie");
    delay(5000);
    lcd.clear();
  }

}

I don't fully understand your program, but I hope to give some guidelines/tips:

Instead of using all kind of different variables, with hour, minutes and seconds, with with only one variable that keeps the time. E.g. a long integer value that contains 24 * 60 * hours + 60 * minutes + seconds as one value. E.g. 12:34:56 will be 24 * 60 * 12 + 60 * 34 + 56 = 19,376.
Subtracting one or 10 seconds will be as easy as subtracting a value 1 or 10.
To calculate back to seconds, minutes and hours, use 3 formulas (assuming time is the time value):

int hours   = (int) time / 60 / 24;
int minutes = (int) (time - hours * 60 * 24) / 60;
int seconds = time % 60;

Keep the code to display the LCD separate, probably it's easier to update every digit every second. You probably change it every second, or when the button has been pressed, which is very slow for a MCU.
When using a button (you already put it in a variable), just remove 10 seconds, and update the time.
However, check also the Blink Without Delay example on the Arduino website, since when you press a button, high likely the button will bounce and one press may result in several times 10 seconds will be subtracted.
And as said above, use good and English variable names, and English comments (except the GUI text to be displayed... O zi buna).


Enabling pins of Arduino Due with direct port manipulation I want to enable pin 13 on my SAM3X8E using direct port manipulation. On this chip the pin is bit 27 in port B, so I used PIOB->PIO_PER = 1<<27; to enable this pin, but it doesn't work. This pin keeps at 3.08V, the default value of non-initialized pins.

Here's my complete code:

#include <asf.h>

int main (void) {
  // Insert system clock initialization code here (sysclk_init()).
  board_init();
  sysclk_init();
  delay_init(sysclk_get_cpu_hz());
  PIOB->PIO_PER = 1<<27;
  PIOB->PIO_OER = 1<<27;
  while(1) {
    REG_PIOB_ODSR = 1<<27;
    delay_ms(1000);
    REG_PIOB_ODSR = 0<<27;
    delay_ms(1000);
  }
}

Can anyone tell me how I can get this to work?

I suggest the following test:  Use REG_PIOB_SODR = 1<<27; to set the bit, and  REG_PIOB_CODR = 1<<27; to clear it.  If that works ok, see about enabling synchronous data output via the port's PIO_OWSR register.  (If it doesn't work ok, perhaps review section 31.6, “I/O Lines Programming Example”, on page 629 of Atmel document 11057, the Cortex datasheet.)

Section 31.5.5, “Synchronous Data Output”, on page 623 says in part:

  After reset, the synchronous data output is disabled on all the I/O lines as PIO_OWSR resets at 0x0.

I imagine that writes to REG_PIOB_SODR and  REG_PIOB_CODR should have effect after you enabled output by setting bits in PIOB->PIO_PER and PIOB->PIO_OER, which you did.  However, with the bit in PIO_OWSR being clear, synchronous data output isn't available, so writes to REG_PIOB_ODSR have no effect.


ATmega328P - Problem using timer 2 for tone generation I'm simply trying to use timer 2 for tone generation and what I get is a very faint and strange tone (almost like its modulated somehow as there is a "pulsing" to it). Here's my simple code:

#include <Arduino.h>

#define SPEAKER_PORT PORTC
#define SPEAKER_BIT 2

void setup()
{
  pinMode(A2, OUTPUT);

  TCCR2A = _BV(WGM21);  // CTC mode
  TCCR2B = _BV(CS20);   // clk/1

  OCR2A = 200;  // 8-bit timer, so keep less than 256
  bitSet(TIMSK2, OCIE2A);  // enable OCR2A interrupt
}

void loop()
{
  // NOP
}

ISR(TIMER2_COMPA_vect)
{
  SPEAKER_PORT ^= _BV(SPEAKER_BIT);
}

Any obvious mistakes? Thanks for your help!

I tried the code on an Uno and as you say, it does sound odd.

By my calculations, the frequency is 40kHz (16MHz/(200 x 2)), which is above the threshold of hearing. The sound we are actually hearing is probably the 3rd or 5th harmonic, at a reduced intensity and perhaps subject to jitter.

I tried changing

TCCR2B = _BV(CS20);   // clk/1

to

TCCR2B = _BV(CS21);   // clk/8

which should mean that the frequency is now 5kHz (16MHz/8/(200 x 2)).

It sounds cleaner.


Using an Arduino as a lithium ion charge controller I have a trinket that I'm going to be powering off of a small lithium ion battery. I was also considering adding a small solar panel to the mix, and using the solar panel to charge the battery. I'm wondering if I can use the trinket itself as a smart charge controller to charge and monitor the battery.

If you are going to design your own battery management system here are a few issues you will need to deal with:

You need to understand the methods to determine the End Of Charge (EOC).  This could be monitoring cell temperature, measuring cell voltage or current for patterns, or integrating current over time (coulomb counter).  Different battery chemistries usually dictate which approach to take.
You need to check with the specific battery manufacturer to determine what charge rate you should use for this specific battery.  Knowing the chemistry is good.  But it is usually best to use the charge rate data from reputable manufactures.
Some batteries can not be completely drained.  If not already part of the LION battery, you will need to design a protection circuit to cut the battery off before this happens.
For such batteries, you need to add a trickle charging circuit in case the battery has been overly discharged.  Such a circuit only allows a small amount of current in.  The current is usually so small that normal monitoring is not necessary.  This is a last resort procedure built into most good chargers to recover overly discharged LION batteries.

...this is not a complete list. These are some of the issue which might be considered when designing a secondary battery charger.  There is a lot more good information about batteries here if you would like to research this subject in greater depth.


ESP8266 PHP Web Server I need my ESP8266 web server to load my website files with .php extensions. So far I managed to load .htm .css and .js files from my SD card, but when I upload PHP files on my SD card, they won't run. How can I do that?

It sounds like you are trying to put a PHP file on an SD card that the ESP8266 will serve itself.

This is not possible, as no one has, and probably never will, port PHP to the Espressif 8266 platform.

Your device can serve .htm .css and .js files because it's just a matter of streaming the file content to the client. But PHP requires that an application on the server run the PHP code, and then send the resulting output to the client.


UPDATE: Fault in processing code - doesn't receive correct data from Arduino I am receiving data from an LDR which I am inputting into processing. The data seems to be received to Arduino correctly and I have looked at the data being sent via the serial monitor and it all seems correct. However, the data that is being received in processing doesn't reflect the data received by the LDR so I think I have done something wrong here but not sure what as I am fairly new to this all. (Please see image for what is printing in the processing serial monitor).

Any help identifying where I have gone wrong would be so so helpful!

ARDUINO CODE

int rval=0;
int lightval;

//Recorded minimum and maximum values
int minval=0;
int maxval=950;

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

void loop()
{
  rval = analogRead(1);
  //Serial.println(rval);
  rval=constrain(rval,minval,maxval);
  lightval=map(rval,minval,maxval,0,255);
  //Serial.println(lightval);
  Serial.write(lightval);
}

PROCESSING CODE

import processing.serial.*;

Splash paintsplash;
Serial port;

float value=0;

void setup()
{
  size(600,600);
  smooth();
  background(255);
  paintsplash= new Splash();
  port=new Serial(this, Serial.list()[6],9600);
  //printArray(Serial.list());
}

void draw()
{
  paintsplash.display();
  paintsplash.splash();
  delay(200);

  if(0<port.available())
  {
    value=port.read();
  }

  println(value);

  if(value<=75)
  {
    fill(255,137,132);
  }

  else if(value>75 && value<=125)
  {
    fill(32,78,95);
  }

  else
  {
    fill(183,215,216);
  }
}

PROCESSING CLASS - PAINT_SPLASH

class Splash
{
  float x;
  float y;
  float size;

  Splash()
  {
    x=0;
    y=0;
    size=int(random(35));
  }

  void display()
  {
    //fill(255,137,132);
    noStroke();
    ellipse(x,y,size,size);
  }

  void splash()
  {
  float xcord=int(random(600));
  float ycord=int(random(600));
  pushMatrix();
  translate(xcord,ycord);

     for ( float i =3; i < 29; i ++)
     {
       float splashX = x + random(100);
       float splashY = y + random(100);

       ellipse(splashX,splashY,size-i,(size-i+random(3)));
     }

   popMatrix();
  }
}

You're sending your lightval twice - once as a textual representation of the number, and once as a character representing the lower 8 bits:

Serial.println(lightval);
Serial.write(lightval);

For example:

Q308
R304
Q306

If you take the 308 and AND it with 255 you get 52.  52 as an ASCII character is R.

So you print 308, including a newline, then you print "R".  Then you print 304, which would be 48 after ANDing with 255 - which of course is a Q.


make Arduino tell when the Python program stops reading from the Serial (crash, etc) Here's the Arduino code:

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

  pinMode(7, INPUT_PULLUP);
}

void loop() {
    int val = digitalRead(7);
    if (val == HIGH) {
        Serial.print("1");
    } else {
        Serial.print("0");
    }
    Serial.println("");  // new line

}

Python code:

import time
import serial

# setup Arduino USB communication
try:
    arduinoSerialData = serial.Serial('com3', 9600)

except: # not connected/damaged
    pass

while True:
    if arduinoSerialData.inWaiting() > 0:
        datastr = arduinoSerialData.readline()
        print datastr
        time.sleep(1)

WHat I want to add is, if Python program exits, or crashes, let the Arduino know somehow. More specifically turn on a LED in pin 8.

There is no way to know if the connection has closed or not, you can only know if the connection was working at some point in the past.

Your communication protocol as shown is only half duplex (i.e., it's only one way - the Arduino sends to Python but never the other way around) which simplifies things somewhat.

There are a number of strategies you can employ in your case, and any number of them can be combined to create a system as robust (and complex) as you like.

First you would need to make your protocol full duplex.  This is, you need your Python program to be able to send information to the Arduino.  Since you aren't doing that at the moment the implementation of it can be in any way you like.

One method you can use is called Keepalive.  In this system the Python program will periodically send an "I am here" message to the Arduino.  The Arduino receives these messages and remembers when the last one was (hint: use the millis() function).  If a message hasn't been received for more than a pre-defined timeout period the link is assumed to be dead.

Another method which is good if you are sending data very regularly from the Arduino to the Python program is to use a system of acknowledgements.  In this situation every bit of data sent to the Python program is followed by the Python replying with an "I got that" message.  If the Arduino doesn't get that response after sending its data within a certain timeout period (can be much shorter than for a keepalive timeout) then the link is assumed to be dead.

Wrapped around both these methods you can add an "I have arrived" and an "I am leaving" message.  These are sent by the Python program when it starts and just before it's about to exit so the Arduino knows when the link should be alive and when it shouldn't.  If it gets an "I am leaving" message then it knows that it shouldn't care whether it gets any acknowledgement or keepalive messages, so it doesn't need to think about timeouts. Only after it has received an "I have arrived" message should it start caring.

So for instance your protocol, with all these things implemented, might look like this (>> = message from Arduino to Python, << is message from Python to Arduino):

>> 1
>> 1
>> 1
>> 0
>> 0
>> 1
<< A    - I have arrived
>> 1
<< Y    - Yes, I got that
>> 1
<< Y    - Yes, I got that
>> 0
<< Y    - Yes, I got that
<< K    - keepalive - we know the link is alive and working.
>> 0
<< Y    - Yes, I got that
>> 1
<< Y    - Yes, I got that
(Program crashes now.)
>> 1
*no Y received - assume connection is closed*
>> 1
... etc ...

In this instance the 0 and 1 are what you are sending at the moment.  A is an "I have Arrived" message, Y is a "Yes I got that" message, K is a "Keepalive" message, and if the program had exited cleanly an L would have been an "I am Leaving" message.

Keeping the messages simple (single characters) means it's really easy for the Arduino to parse those messages and work out what is going on.

There is a certain amount of balancing act to be performed when implementing your system between how often you are sending data and how long you are willing to wait for a valid response or message to flag the connection closed.

Expanding your existing example program to incorporate these messages might look like:

unsigned long lastKA = 0;
unsigned long lastSent = 0;
boolean isConnected = false;

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

  pinMode(7, INPUT_PULLUP);
}

void loop() {

    // Check the timeouts if we are connected
    if (isConnected) {

        // First check to see if the Keepalive timeout has passed
        if (millis() - laskKA > 5000) { // 5 second keepalive timeout)
            isConnected = false;
        }

        // If we have sent data...
        if (lastSent > 0) {
            // ... check that we got a response in time
            if (millis() - lastSent > 100) { // 100ms Y timeout
                isConnected = false;
            }
        }

    }

    // If we are connected then send some data
    if (isConnected) {

        int val = digitalRead(7);
        if (val == HIGH) {
            Serial.print("1");
        } else {
            Serial.print("0");
        }
        Serial.println("");  // new line

        // and set the timer for the response
        lastSent = millis();
    }

    // Now process incoming messages.
    if (Serial.available()) {
        int c = Serial.read();

        // If the message is an A then turn on the connection and
        // treat it as a Keepalive as well.
        if (c == 'A') { // Arrived
            isConnected = true;
            lastKA = millis();

        // If it's a Leaving message then turn off the connection.
        } else if (c == 'L') { // Leaving
            isConnected = false;

        // If it's a Keepalive then reset the timer.
        } else if (c == 'K') { // Keepalive
            lastKA = millis();

        // A Y acknowledgement will disable the sent timer.
        } else if (c == 'Y') { // Yes
            lastSent = 0; // Cancel the sent timer
        }
    }
}


Getting different numbers after sending an unsigned int 8-9 times between Arduinos via Serial I am trying to transfer unsigned int values between 2 Arduinos. When sending 61805 for the first 8-9 times, I am getting 61805.  But after then after these numbers: 61937 28013 61937.
Sender's code:
unsigned int s = 0;

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

void loop()
{
  s = 61805;
  Serial.write(highByte(s)) ;
  Serial.write(lowByte(s));
}

Receiver's code:
unsigned int upperByte, lowerByte, r=0,p=0;

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

void loop ()
{
  if (Serial.available() > 1)
  {
    upperByte = Serial.read();
    lowerByte = Serial.read();
  }

  r = (upperByte << 8) + lowerByte;
  Serial.println(r);
}

There's no flow control on the Uno and Nano serial and you are sending fast enough that bytes are being dropped, and there's no way your protocol or lack of one demarcates separate messages (separate numbers).
This will become more clear if you write your numbers in hexadecimal:

Dec
Hex

61805
0xf16d

61937
0xf1f1

28013
0x6d6d

61937
0xf1f1

Adding a delay between messages can serve to separate the messages if the receiving side makes use of a timeout and can prevent the receiving side from being overwhelmed with data.
If you don't want to use time to slow down and separate your data, you can change what is sent instead.  One idea is to have the receiver actively request data when it's ready to receive some. The receiver should expect only entire messages between requests, and if anything gets garbled, it can just read whatever data has come in and throw it out before the next request.
Your messages can also be separated by some characters that aren't part of the messages themselves.  A common way to do that is just to encode your numbers as separate text lines, the line terminator \n serving as the separator between messages.
I have not tested these yet, but here are some very minimal modifications to your code that approach having a protocol with fewer of these problems:
Sender:
void setup () {
  Serial.begin(9600);
}

void loop() {
  // await message request
  while(Serial.read() != '.') {
  }

  //
  const unsigned int s = 61805;
  Serial.write(highByte(s)) ;
  Serial.write(lowByte(s));
}

Receiver:
void setup() {
  Serial.begin(9600);
}

void loop () {
  // request message
  Serial.write('.');

  // await two-byte response
  const unsigned long request_sent = millis();
  while (Serial.available() < 2 && millis() - request_sent < 1000) {
  }

  if (Serial.available() != 0) {
    if (Serial.available() == 2) {
      // two byte response receive
      const unsigned upperByte = Serial.read();
      const unsigned lowerByte = Serial.read();
      const unsigned r = (upperByte << 8) + lowerByte;
      Serial.println(r);
    }  else {
      // Something went wrong, too or too few bytes received;
      // throw them out and start over.
      delay(100);
      while (Serial.read() != -1) {}
    }
  }
}

It's a long way from doing it properly, but it should behave at least better than what you started with.  There's a lot to designing even simple protocols.  Typically there are start and end frame bytes, a checksum or CRC, a message number counter, etc.


Init a calss inside a class I'm building a monitoring IP class, IPmonitoring, that using an SPIFFS class that I wrote, flashLOG. Inside IPmonitoring I have 2 instances of flashLOG (code below).
My sketch have several instances of IPmonitoring for several servicesI wish to monitor. I Wish that connectionLOG and disconnectionLOG have unique and automated names.
For example if I'm monitoring a service called MQTT its connect and disconnect log will be MQTT_discolog.txt and MQTT_conlog.txt. In my code below, filename1 and  filename2 are consts.
class IPmonitoring
{
private:
        char *_IP;
        char *_nick;

        flashLOG connectionLOG;
        flashLOG disconnectionLOG;

public:
        IPmonitoring(char *IP, char *nick, char *filename1 = "/conlog.txt", char *filename2 = "/disconlog.txt")
            : connectionLOG(filename1), disconnectionLOG(filename2)
        {
                _IP = IP;
                _nick = nick;
        }

EDIT1 - example how to use class
my goal is that filename1 for example will be MQTTbroker_connlog.txt meaning a combination of _nick and a suffix,
IPmonitoring MQTT_service("192.168.3.200","MQTTbroker");

void setup()
{
MQTT_service.start();
}

void loop()
{
MQTT_service.loop();
}

Judging from your example usage, you want the filenames to be built by
the IPmonitoring constructor. However, since that class cannot know in
advance how much space is needed for the file names, you are left with
two choices:

Let those file names be data members: arrays of char of some fixed
size. This will impose a limit on the maximum file name length.

Allocate the arrays dynamically at construction time.

Here is a tentative implementation of the second approach:
class IPmonitoring
{
private:
    const char *_IP;
    const char *_nick;
    const char *connectionLOG_filename;
    const char *disconnectionLOG_filename;
    flashLOG connectionLOG;
    flashLOG disconnectionLOG;

    // Return a dynamically allocated string with the concatenation
    // of `a' and `b'.
    const char *str_concat(const char *a, const char *b)
    {
        char *s = new char[strlen(a) + strlen(b) + 1];
        strcpy(s, a);
        strcat(s, b);
        return s;
    }

public:
    IPmonitoring(const char *IP, const char *nick)
        : _IP(IP), _nick(nick),
        connectionLOG_filename(str_concat(nick, "_connlog.txt")),
        disconnectionLOG_filename(str_concat(nick, "_disconnlog.txt")),
        connectionLOG(connectionLOG_filename),
        disconnectionLOG(disconnectionLOG_filename)
    {}

    ~IPmonitoring(){
        delete[] connectionLOG_filename;
        delete[] disconnectionLOG_filename;
    }
};

Note the destructor, which is needed to avoid memory leaks, unless all
the instances of the class are statically allocated (which would be good
to avoid memory fragmentation). You may want to implement a copy
constructor and a copy assignment operator, as per the rule of
three.


Do all serial ports on an Arduino MEGA 2560 have the potential to "brick" attached items when being flashed? I was browsing through the hookup guide for SparkFun's OBD-II UART breakout and found something particularly worrying written half way down in a quite casually presented way:

  Keep in mind when you upload this to your board, you will want to disconnect the OBD-II board RX line from the Arduino TX-0, to prevent issues during code upload, such as bricking the OBD-II board.

For my money I think bricking your device should come with a more stark warning than one stuffed part way down a guide starting with "keep in mind" and continuing with "issues". Nonetheless it caught my attention as I tend to build sealed boxes that aren't sprawled in front of a keyboard ready to be rewired any time a re-flash might happen.

Is the real risk here the fact that all of the flashed data would stream past the RX pin of the UART board and potentially accidentally send a 'self-destruct' signal? (Also I'm not sure a system is really up to scratch if you can accidentally tell it to kill itself.)

Surely the programming port is not the one being borrowed by the UART hookup? On a MEGA 2560, using a different serial port, is this still a risk or is that only on boards with one serial port?

In the Sparkfun example the Arduino Uno is used. The Uno has only one hardware serial port, and that is used to upload a sketch and for the serial monitor. Pin 0 (RX) and pin 1 (TX) can be overriden for something else. However, then you must know what you are doing, and connect and disconnect modules as required.

The Arduino Leonardo and (Pro) Micro use a USB CDC implementation and have a unused hardware serial port at pin 0 and 1.

The Arduino Mega 2560 uses the hardware serial port at pin 0 and 1 to upload a sketch, just as the Uno. However, the three other hardware serial ports are not used, and you are free to use them.

If you use an unused hardware serial port for the OBD-II, there is no risk at all. You can use that port and nothing else messes with that port.

If you use a serial port that is also used to upload a sketch, or a software implementation of a serial port, you probably are going to make a mistake some day, and there is a risk to send the wrong data to the wrong hardware.

[ADDED]
I see that the example code in the SparkfunHookup Guide uses the Arduino Uno and SoftwareSerial on pin 2 and 3. That is independent of the hardware serial port. The SoftwareSerial is something that should be used as a last resort, since it almost completely takes over the Arduino board. It's good to have SoftwareSerial, but try to avoid it.
If you do want to use an Arduino Uno, perhaps the AltSoftSerial can be used. The AltSoftSerial works okay for 9600 baud as long as no other code uses too much time in interrupts and no one else uses TIMER1.


How do I send a string from an Arduino Slave using SPI? I have an Arduino Uno acting as a master with 3 Arduino Nano's acting as a slaves.

Looking at this example:
http://www.gammon.com.au/forum/?id=10892, it tells me how to send a string from the master to the slave, but I didn't see any examples sending a string from the slave to the master device. I was able to successfully send and receive digits to/from the master and slave, but I couldn't figure out how to send strings from the slave to the master based on the example.

My understanding is that SPI communications can only send information byte by byte, so am I supposed to convert my string into a byte format before putting that into the SPDR variable so that it can be sent back to the master?

In any case, would I be able to get some pointers on how to send strings from the slave to the master?

Thanks in advance.

Remember the master controls the transmission (provides the clock), however it can be done. For example:

Master

// master

#include <SPI.h>

void setup (void)
{
  Serial.begin (115200);
  Serial.println ("Starting");

  digitalWrite(SS, HIGH);  // ensure SS stays high for now

  // Put SCK, MOSI, SS pins into output mode
  // also put SCK, MOSI into LOW state, and SS into HIGH state.
  // Then put SPI hardware into Master mode and turn SPI on
  SPI.begin ();

  // Slow down the master a bit
  SPI.setClockDivider(SPI_CLOCK_DIV8);

}  // end of setup

void loop (void)
{
  char buf [20];

  // enable Slave Select
  digitalWrite(SS, LOW);
  SPI.transfer (1);   // initiate transmission
  for (int pos = 0; pos < sizeof (buf) - 1; pos++)
    {
    delayMicroseconds (15);
    buf [pos] = SPI.transfer (0);
    if (buf [pos] == 0)
      {
      break;
      }
    }

  buf [sizeof (buf) - 1] = 0;  // ensure terminating null

  // disable Slave Select
  digitalWrite(SS, HIGH);

  Serial.print ("We received: ");
  Serial.println (buf);

  delay (1000);  // 1 second delay
}  // end of loop

In this example the master initiates a transmission by sending 0x01 to the slave. Then it gets bytes back until a 0x00 byte (signifying the end of the string). The delayMicroseconds is there to give the slave time to respond.

Slave

// Slave

void setup (void)
{

  // have to send on master in, *slave out*
  pinMode(MISO, OUTPUT);

  // turn on SPI in slave mode
  SPCR |= bit(SPE);

  // turn on interrupts
  SPCR |= bit(SPIE);
}  // end of setup

volatile char buf [20] = "Hello, world!";
volatile int pos;
volatile bool active;

// SPI interrupt routine
ISR (SPI_STC_vect)
{
  byte c = SPDR;

  if (c == 1)  // starting new sequence?
    {
    active = true;
    pos = 0;
    SPDR = buf [pos++];   // send first byte
    return;
    }

  if (!active)
    {
    SPDR = 0;
    return;
    }

  SPDR = buf [pos];
  if (buf [pos] == 0 || ++pos >= sizeof (buf))
    active = false;
}  // end of interrupt service routine (ISR) SPI_STC_vect

void loop (void)
{

}  // end of loop

The slave does everything inside the ISR. The arrival of the 0x01 byte makes it reset its "pointer" to the start of the buffer. After that it responds with another byte from the buffer until it has reached the terminating 0x00 byte.


Directly powering a single 32x16 RGB LED matrix (without external PSU) All the guides I've found suggest to use an external PSU to power an RGB matrix like this.

However I know it is possible to blink the LEDs at high rates (eg. 2ms) and still give the impression to the eyes they are fully on. I've verified this myself on a small 4x4 matrix, but I am not sure if the same can be done with these bigger matrices.

In my case I could tolerate reduced brightness and color space, but I'd like to power the matrix with the Arduino's 5V pin directly.

When powered through USB, the total current consumption is limited to 500mA by the USB interface. If you are using the power connector, the total current is limited by the on board 5V regulator to 1A.

The board will also require some current, so you can draw around 400mA, if powered through USB or 900mA, if powered through the connector; from the 5V pin.

While the matrix on average may not draw than 300 - 400mA, the voltage regulator can overheat and shut off temporarily, and you will never be able to reach 900mA. The regulator is linear, so any extra voltage you supply will result in waste heat.

It is best to get a buck converter or power the matrix externally. You won't be wasting as much power, and avoiding possible thermal shutoff.


DFROBOT I2C 16x2 Arduino LCD Display Module I2C communication interface What is the proper connection to the I2C communication interface (e.g., JST Jumper 4 Wire Assembly) of the DFROBOT I2C 16x2 Arduino LCD Display Module (SKU:DFR0063)? I wish to connect 4 wires assembly directly to it.

Here is schema how to connect it and example how to use it, also link to needed library. Hope this helps.

https://www.dfrobot.com/wiki/index.php/I2C/TWI_LCD1602_Module_(SKU:_DFR0063)

Anyway - I2C is prettty standardized interface, so googling any I2C schema for your type of Arduino will work as for connection - just connect SDA (A4) to SDA, SCL (A5) to SCL, GND to GND and VCC to VCC as writen on the module interface.

There are also lots of correct results for googling the module name - just google SKU:DFR0063 and you get many of correct links. On first page every second link contains link for the library, those others just refers to the manufacturer in text.


Error: request for member 'RGB' in 'redLed' , which is of non-class type 'int' My 10 year old received great gift from older brother (Crate Creations) and I am trying write the program and getting this error. It looks to me that I matched the required code word for word symbol for symbol but I just can't figure out what I did wrong:

void loop () {

  for (float x = 0; x < PI; x = x + 0.00001) {
    RGB[0] = power * abs(sin(x * (CommonMathVariable)));
    RGB[1] = power * abs(sin((x + PI/3) * (CommonMathVariable)));
    RGB[2] = power * abs(sin((x + (2 * PI) / 3) * (CommonMathVariable)));
    ambientLight = analogRead(ldrPin);
    if (ambientLight > 600) {

    analogWrite (redLed.RGB[0]);
    analogWrite (greenLed.RGB[1];
    analogWrite (blueLed.RGB[2];

  }

I get this error:

request for member 'RGB' in 'redLed' , which is of non-class type 'int'

Probably you didn't spot commas:

    analogWrite (redLed,   RGB[0]);
    analogWrite (greenLed, RGB[1]);
    analogWrite (blueLed,  RGB[2]);

The function analogWrite takes two arguments, separated by commas. You were missing some brackets as well.


Counter using Ultrasonic Sensor (self.arduino) I am doing a pretty simple arduino project that uses a Parallax Ping Ultrasonic Sensor to increment a counter when an object moves past the desired distance. (object leaves, counter goes up, object comes back, this loops forever). My problem is now that every time i run this.. the serial monitor just shows me Count: 1 over and over again and does not increment.
Any help would be appreciated!

example of what i want the Serial Monitor to write:
Count:0
Count:1
Count:2 ....

What it is currently doing:
Count:0
Count:0
Count:0

const int pingPin = 7;

void setup() {
  // initialize serial communication:
  Serial.begin(9600);
}

void loop()
{
  // establish variables for duration of the ping,
  // and the distance result in inches and centimeters:
  long duration, inches, cm, count;

  // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  pinMode(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingPin, LOW);

  // The same pin is used to read the signal from the PING))): a HIGH
  // pulse whose duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  pinMode(pingPin, INPUT);
  duration = pulseIn(pingPin, HIGH);

    // convert the time into a distance
  inches = microsecondsToInches(duration);
  cm = microsecondsToCentimeters(duration);
// count = 1;

 if (inches > 5)
{
  Serial.print("Count: ");
  Serial.print(count);
  Serial.print('\n');
  delay(1000);
        count++;

}

}

long microsecondsToInches(long microseconds)
{
  return microseconds / 74 / 2;
}

long microsecondsToCentimeters(long microseconds)
{

  return microseconds / 29 / 2;
}

Count is a local variable - it gets re-created afresh every time the loop() runs.

Either make it global, or make it static.

These two options look like this:

Global

long count = 0;

void loop()
{
  // establish variables for duration of the ping,
  // and the distance result in inches and centimeters:
  long duration, inches, cm;

Static

void loop()
{
  // establish variables for duration of the ping,
  // and the distance result in inches and centimeters:
  long duration, inches, cm;
  static long count = 0;

Both will do the same job, but the static form is preferred since it is always better to keep a variable's scope as narrow as possible.  It is also important to provide a start value for the counter to begin from (0 in this case) otherwise the starting value will be unknown.


Arduino Nano gives 7V on the 5V PIN! I have an Arduino Nano which is Powered by an external Power supply. This is connected with VIN and GND. The voltmeter says, there are 12,12 V

I have some components connected on the 5V PIN, which altogether draw max. 100mA
Since some of the components are not working anymore, I started measuring...

I have disconnected everything, but the Arduino Nano Power supply. (12,12V)

When I now measure GND and the 5V PIN, the Voltmeter says 6,97V! I guess this is why my components are giving up.

But why are there 6,97 Volts all of the sudden?
Is my Arduino broken now?
Can I fix this?
How can this happen?

Of course the 5V regulator on the nano can be faulty. Another possibility is the 5V decoupling capacitor. If it goes open circuit the regulator will oscillate and the mean output voltage will be near half the input voltage. Most regs have a minimum decoupling cap value specified.


Arduino slave with 2 masters sharing the same I2C Bus? Consider a scenario where two (or more) master devices (the NodeMCU's, in this case) share an I2C bus with one (or more) slave device(s), like thus:

Would this be a feasible setup?  In other words,  could both masters request (not simultaneously) from the slave?

The situation you describe is called MultiMaster. It is normally done in hardware using the I2C peripheral in the MCU. However the ESP8266 doesn't have one (or if it does, it's not used), and uses bit-banging to implement I2C in software. If you can add MultiMaster functionality to the ESP8266's Wire library then possibly yes, you could do it.

Another option is to have some other communication channel between the two masters (it could be as simple as a wire with a pullup resistor - see below) so that only one master communicates at a time.

Electrically there is no problem with your setup - I2C is a fully open-drain system (or should be implemented as such - hence the pullup resistors needed on the SCL and SDA pins), so multiple devices can drive the lines at the same time. It's just that if they do you will get data corruption and communication won't happen.

Example: Semaphore Wire Implementation

Connect any two GPIO pins together with a wire. Add a pullup resistor to the wire (10kΩ should suffice).
Both GPIO pins are set to INPUT.

When a master wants to send it first reads the GPIO pin:

If it is HIGH then it is "clear to send". So it sets the GPIO to OUTPUT and pulls the line LOW.
If it is LOW then it waits for a random amount of time and tries again.

Once communication is finished the master sets the GPIO pin to INPUT again.


No power from Breadboard Power Supply Module Components

Breadboard Power Supply Module IM120525004
1 kOhm resistor
Green LED
Arduino Nano
LiPo 7.4V battery

LED Lights Up Fine with USB power from the Arduino

LED Does Not Light Up with power from the Supply Module

What am I doing wrong?

The Lipo battery is brand new and is charged as the terminals showed about 7.6V on my multimeter. This is confirmed by the LED on the supply module itself lighting up fine.
I think I can smell just a little bit of burn whenever the supply module is connected and there is power in the circuit.
The positive jumper wire is connected to the 5V VCC pin on the Arduino, not the VIN pin on the Arduino, not that it matters, because if I remove the Arduino from the breadboard the LED still does not light up

I'm not surprised you can smell burning. You have the power supply connected backwards.

You see that little + and - symbol next to the ON/OFF jumper? That's the polarity of the two runs of pins. You have the + row connected to the - rail of your breadboard (blue) and the - row connected to the (red) positive rail.

Turn the power supply around 180° and connect it to the other end of the breadboard - the rails will be the other way around then.


Powering a Tiny Arduino Project I'm trying to build a tiny project. After I program the board, to power the dev board - how can I power it to run the code?

Question:

I was curious as to how I would be able to power the ATtiny85 USB Mini Dev Board by using a 90mAh 3.7V LiPo battery which is connected to a TP4056 5V micro USB Lipo battery charger? The power is regulated to 5V by a  3v to 5v 1a USB Charger DC-DC Converter feeding the 5V pin on the ATtiny85.
If now, how else can I power the ATtiny85 USB Mini Dev Board with a rechargeable battery?

New Circuit

Old Circuit

Final Circuit

The old circuit will not work as you expect. While the ATtiny85 can run happily with 2.7 to 5.5V in this setup it expects 5V. I assume this is due to the high CPU clock setting. To run stable at a high CPU clock it requires 4.5V.

The VIN pin is connected to a linear regulator that has a 2V drop-out. Thus the supplied voltage has to be at least 2V about the target voltage. That is why the shopping page states a 5V (direct) or 7-35V (regulated at VIN) power supply.

Your LiPo charger already has a boost converter built in that boosts the battery voltage (3.0 - 4.2V) to 5V. No need to use a separate DC-DC boost converter here.

Just connect OUT+ to 5V and you are done.