text:
Error : stray '\' in program
I got this error in the following program:
#include <SoftwareSerial.h>
#include <dht.h>
dht DHT;
int a;
String temp;
String humid;
SoftwareSerial esp(0, 1);
#define SSID "abcd"
#define PASS "99999999"

void sendAT(String cmd) {
  Serial.print("SEND=");
  esp.println("cmd");
  Serial.println("cmd");
}

boolean connectwifi() {
  Serial.println("AT+CWMODE=1");
  delay(2000);
  Serial.println("AT+CWLAP");
  String cmd="AT+CWJAP="\"abcd"\",\"99999999"\";
  sendAT(cmd);
  delay(5000);
  if (Serial.find("ERROR")){
    Serial.println("Recieved:Error could not connect");
    return false;
  }
  else{
    Serial.println("Wifi connected \n");

  }
  cmd="AT+CIPMUX=0";
  sendAT(cmd);
  if(Serial.find("Error")){
    esp.print("RECIEVED ERROR");
    return false;
  }
}

  void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  esp.begin(115200);
  send("AT");
  delay(5000);
  if(Serial.find("OK")){
    Serial.println("Recieved:OK\n ESP ready to send data\n");
    connectwifi();

  }

}

  void loop() {
  // put your main code here, to run repeatedly:
  a=DHT.read11(5);
  temp=DHT.temperature;
  humid=DHT.humidity;
  Serial.println("temperature: ");
  Serial.println(temp);
  Serial.println("humidity: ");
  Serial.println(humid);
  Serial.print("\n");
  updateTS(temp,humid);
  delay(3000);

}

void updateTS(String T, String H){
  String cmd="AT+CIPSTATRT=\"TCP\",\"api.thingspeak.com\",80";
  sendAt(cmd);
  delay (2000);
  if (Serial.find("Error")){
    Serial.print("Recieved :Error\n EXIT1");
    return;
  }
  cmd="GET/update?key=CJWN3VJZCQVTJD2J&field1="+T+"&field2+"+H+"\r\n";
  Serial.println("AT+CIPSEND=");
  Serial.println(cmd length());
  if (Serial.find(">")){
    esp.print(">");
    esp.print(cmd);
    Serial.println(cmd);
    }
    else{
      sendAT("AT+CIPCLOSE");
    }
    if (Serial.find("Error")){
      Serial.println("Recieved: Error \n EXIT2");
    }
    Serial.println();
}
    }
}

The error message displayed is:
arduinoo_sketch:21: error: stray '\' in program

   String cmd="AT+CWJAP="\"abcd"\",\"99999999"\";

   ^

arduinoo_sketch:21: error: stray '\' in program

arduinoo_sketch:21: error: stray '\' in program

C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino:21:47: warning: missing terminating " character

   String cmd="AT+CWJAP="\"abcd"\",\"99999999"\";

                                               ^

arduinoo_sketch:21: error: missing terminating " character

   String cmd="AT+CWJAP="\"abcd"\",\"99999999"\";

   ^

C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino: In function 'boolean connectwifi()':

arduinoo_sketch:22: error: expected ',' or ';' before 'sendAT'

   sendAT(cmd);

   ^

C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino:24:26: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   if (Serial.find("ERROR")){

                          ^

C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino:34:25: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   if(Serial.find("Error")){

                         ^

C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino: In function 'void setup()':

arduinoo_sketch:44: error: 'send' was not declared in this scope

   send("AT");

            ^

C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino:46:22: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   if(Serial.find("OK")){

                      ^

C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino: In function 'void loop()':

arduinoo_sketch:64: error: 'updateTS' was not declared in this scope

   updateTS(temp,humid);

                      ^

C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino: In function 'void updateTS(String, String)':

arduinoo_sketch:75: error: 'sendAt' was not declared in this scope

   sendAt(cmd);

             ^

C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino:77:26: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   if (Serial.find("Error")){

                          ^

arduinoo_sketch:83: error: expected ')' before 'length'

   Serial.println(cmd length());

                      ^

C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino:84:22: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   if (Serial.find(">")){

                      ^

C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino:92:28: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

     if (Serial.find("Error")){

                            ^

C:\Users\lenovo\Documents\Arduino\arduinoo_sketch\arduinoo_sketch.ino: At global scope:

arduinoo_sketch:97: error: expected declaration before '}' token

     }

     ^

exit status 1
stray '\' in

Syntax highlighting should have given you a hint.

Offhand, I spotted that where it says String cmd="AT+CWJAP="\"abcd"\",\"99999999"\";
it should say String cmd="AT+CWJAP="\"abcd"\",\"99999999\"; - before I saw the error messages - the compiler caught it - so just chase down each line indicated in the error messages.

By properly formatting your code (ctrl-T in the IDE), you realize what is wrong with your code... In
  String cmd = "AT+CWJAP="\"abcd"\",\"99999999"\";
               sendAT(cmd);

See how sendAT(cmd); is indented as if it was part of the previous line? It means you have some trouble with the quotes.

At least one example is here:
String cmd="AT+CWJAP="\"abcd"\",\"99999999"\";

You probably meant
String cmd="AT+CWJAP=\"abcd\",\"99999999\"";

This is a pretty trivial issue, you should be able to fix it simply by proofreading your sketch carefully.


text:
How to speed application up (if possible)
I have an ARD 2560, which I communicate with through a special written Delphi 7 program (USB handling is done in the D-7 program).
I use the command syntax:
<REG> <COMMAND) <:> <NUMBER> <CR>

where
REG is  A - K (the registers in the ARD 2650)
COMMAND can be a 2-chars command, but mostly 1-char commands.
EG:  AR:255<cr>  // AR configures DDRA to out- or in-put , depending on the parameter - (here 255 / 0xff) .

AI:0<cr>  Read port A input (actually return content of ARD2560 port A input register)

AO:<number><CR>   Send Number to port A (and return result to D-7 ).

......

All those command are valid for Reg A to Reg K.
The response time from transmit (d7) to I ("D/7") get the answer is approx. 1 1/2 second. I have a feeling that my code is a big, big kludge (it actually works), but I would like any advice(s) to to improve code // speeding it up.
If I drop the line:
 if (char (pport[0] == '*' ))  // '*' can be 'A' to 'K'

The response time increases to appr. 2 seconds.
(sorry that there are no comments!)
Here's the code:
#include <Esplora.h>

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

void loop()
{

  String chr;

  if (Serial.available() > 0)
  {
    String pport = Serial.readStringUntil(':');
    {
      String pos = Serial.readStringUntil('\n');

      if (char (pport[0] == 'A' ))        /* A */
      {
        if (pport == "AR")
        {
          DDRA = pos.toInt();
          DOCRLF("//AR+", pos.toInt());
        }
        else
        if (pport == "AI")
        {
          if (DDRA == B00000000)
          {
            Serial.print(PORTA);
            chr = "//AI";
          }
          else
          {
            chr ="//AI-";
          }
          DOCRLF(chr , pos.toInt());
        }
        else
        if (pport == "AO")
        {
          if (DDRA == B11111111)
          {
            PORTA = pos.toInt();
            chr = "//AO+";
          }
          else
          {
            chr = "//AO-";
          }
          DOCRLF(chr, pos.toInt());
        }
        else
        if (pport == "AU")
        {
          Serial.print(PORTA);
          DOCRLF("//AU+", pos.toInt());
        }
        else
        if (pport == "ABW")
        {
          PORTA = pos.toInt();
          DOCRLF("//ABW+", pos.toInt());
        }
        else
        if (pport == "ABR")
        {
          Serial.print(PORTA);
          DOCRLF("//ABR+", pos.toInt());
        }
      }
      else
      if (char (pport[0] == 'B' ))        /* B */
      {
        if (pport == "BR")
        {
          DDRB = pos.toInt();
          DOCRLF("//BR+", pos.toInt());
        }
        else
        if (pport == "BI")
        {
          if (DDRB == B00000000)
          {
            Serial.print(PORTB);
            chr = "//BI+";
          }
          else
          {
            chr = "//BI-";
          }
          DOCRLF(chr, pos.toInt());
        }
        else
        if (pport == "BO")
        {
          if (DDRB == B11111111)
          {
            PORTB = pos.toInt();
            chr = "//BO+";
          }
          else
          {
            chr = "//BO-";
          }
          DOCRLF(chr, pos.toInt());
        }
        else
        if (pport == "BU")
        {
          Serial.print(PORTB);
          DOCRLF("//BU+", pos.toInt());
        }
        else
        if (pport == "BBW")
        {
          PORTB = pos.toInt();
          DOCRLF("//EBW+", pos.toInt());
        }
        else
        if (pport == "BBR")
        {
          Serial.print(PORTB);
          DOCRLF("//BBR+", pos.toInt());
        }
      }
      else
      if (char (pport[0] == 'C' ))        /* C */
      {
        if (pport == "CR")
        {
          DDRC = pos.toInt();
          DOCRLF("//CR+", pos.toInt());
        }
        else
        if (pport == "CI")
        {
          if (DDRC == B00000000)
          {
            Serial.print(PORTC);
            chr = "//CI+";
          }
          else
          {
            chr = "//CI-";
          }
          DOCRLF(chr, pos.toInt());
        }
        else
        if (pport == "CO")
        {
          if (DDRC == B11111111)
          {
            PORTC = pos.toInt();
            chr = "//CO+";
          }
          else
          {
            chr = "//CO-";
          }
          DOCRLF(chr, pos.toInt());
        }
        else
        if (pport == "CU")
        {
          Serial.print(PORTC);
          DOCRLF("//CU+", pos.toInt());
        }
        else
        if (pport == "CBW")
        {
          PORTC = pos.toInt();
          DOCRLF("//CBW+", pos.toInt());
        }
        else
        if (pport == "CBR")
        {
          Serial.print(PORTC);
          DOCRLF("//CBR+", pos.toInt());
        }
      }
      else
      if (char (pport[0] == 'D' ))        /* D */
      {
        if (pport == "DR")
        {
          DDRD = pos.toInt();
          DOCRLF("//DR+", pos.toInt());
        }
        else
        if (pport == "DI")
        {
          if (DDRD == B00000000)
          {
            Serial.print(PORTD);
            chr = "//DI+";
          }
          else
          {
            chr = "//DI-";
          }
          DOCRLF(chr, pos.toInt());
        }
        else
        if (pport == "DO")
        {
          if (DDRD == B11111111)
          {
            PORTD = pos.toInt();
            chr = "//DO+";
          }
          else
          {
            chr = "//DO-";
          }
          DOCRLF(chr, pos.toInt());
        }
        else
        if (pport == "DU")
        {
          Serial.print(PORTD);
          DOCRLF("//DU+", pos.toInt());
        }
        else
        if (pport == "DBW")
        {
          PORTD = pos.toInt();
          DOCRLF("//DBW+", pos.toInt());
        }
        else
        if (pport == "DBR")
        {
          Serial.print(PORTE);
          Serial.println("//DBR+");
        }
      }
      else
      if (char (pport[0] == 'E' ))        /* E */
      {
        if (pport == "ER")
        {
          DDRE = pos.toInt();
          DOCRLF("//ER+", pos.toInt());
        }
        else
        if (pport == "EI")
        {
          if (DDRE == B00000000)
          {
            Serial.print(PORTE);
            chr = "//ER+";
          }
          else
          {
            chr = "//ER-";
          }
          DOCRLF(chr, pos.toInt());
        }
        else
        if (pport == "EO")
        {
          if (DDRE == B11111111)
          {
            PORTE = pos.toInt();
            chr = "//EO+";
          }
          else
          {
            chr = "//EO-";
          }
          DOCRLF(chr, pos.toInt());
        }
        else
        if (pport == "EU")
        {
          Serial.print(PORTE);
          DOCRLF("//EU+", pos.toInt());
        }
        else
        if (pport == "EBW")
        {
          PORTE = pos.toInt();
          DOCRLF("//EBW+", pos.toInt());
        }
        else
        if (pport == "EBR")
        {
          Serial.print(PORTE);
          DOCRLF("//EBR+", pos.toInt());
        }
      }
      else
      if (char (pport[0] == 'F' ))        /* F */
      {
        if (pport == "FR")
        {
          DDRF = pos.toInt();
          DOCRLF("//FR+", pos.toInt());
        }
        else
        if (pport == "FI")
        {
          if (DDRF == B00000000)
          {
            Serial.print(PORTF);
            chr = "//FI+";
          }
          else
          {
            chr = "//F1-";
          }
          DOCRLF(chr, pos.toInt());
        }
        else
        if (pport == "FO")
        {
          if (DDRF == B11111111)
          {
            PORTF = pos.toInt();
            chr = "//FO+";
          }
          else
          {
            chr = "//FO-";
          }
          DOCRLF(chr, pos.toInt());
        }
        else
        if (pport == "FU")
        {
          Serial.print(PORTF);
          DOCRLF("//FU+", pos.toInt());
        }
        else
        if (pport == "FBW")
        {
          PORTF = pos.toInt();
          DOCRLF("//FBW+", pos.toInt());
        }
        else
        if (pport == "FBR")
        {
          Serial.print(PORTF);
          DOCRLF("//FBR+", pos.toInt());
        }
      }
      else
      if (char (pport[0] == 'G' ))        /* G */
      {
        if (pport == "GR")
        {
          DDRG = pos.toInt();
          DOCRLF("//GR+", pos.toInt());
        }
        else
        if (pport == "GI")
        {
          if (DDRG == B00000000)
          {
            Serial.print(PORTG);
            chr = "//GI+";
          }
          else
          {
            chr = "//GI-";
          }
          DOCRLF(chr, pos.toInt());
        }
        else
        if (pport == "GO")
        {
          if (DDRG == B11111111)
          {
            PORTG = pos.toInt();
            chr = "//GO+";
          }
          else
          {
            chr = "//GO-";
          }
          DOCRLF(chr, pos.toInt());
        }
        else
        if (pport == "GU")
        {
          Serial.print(PORTG);
          DOCRLF("//GU+", pos.toInt());
        }
        else
        if (pport == "GBW")
        {
          PORTG = pos.toInt();
          DOCRLF("//GBW+", pos.toInt());
        }
        else
        if (pport == "GBR")
        {
          Serial.print(PORTG);
          DOCRLF("//GBR+", pos.toInt());
        }
      }
      else
      if (char (pport[0] == 'H' ))        /* H */
      {
        if (pport == "HR")
        {
          DDRH = pos.toInt();
          DOCRLF("//HR+", pos.toInt());
        }
        else
        if (pport == "HI")
        {
          if (DDRH == B00000000)
          {
            Serial.print(PORTH);
            chr = "//HI+";
          }
          else
          {
            chr = "//HI-";
          }
          DOCRLF(chr, pos.toInt());
        }
        else
        if (pport == "HO")
        {
          if (DDRH == B11111111)
          {
            PORTH = pos.toInt();
            chr = "//HO+";
          }
          else
          {
            chr = "//HO-";
          }
          DOCRLF(chr, pos.toInt());
        }
        else
        if (pport == "HU")
        {
          Serial.print(PORTH);
          DOCRLF("//HU+", pos.toInt());
        }
        else
        if (pport == "HBW")
        {
          PORTH = pos.toInt();
          DOCRLF("//HBW+", pos.toInt());
        }
        else
        if (pport == "HBR")
        {
          Serial.print(PORTH);
          DOCRLF("//HBR+", pos.toInt());
        }
      }
      else
      if (pport == "RA")
      {
        int aport = (pos.toInt());

        if (aport > -1 && aport < 16)
        {
          Serial.println (" OK ");
        }
      }
      else
      if (pport == "KO")
      {
        Serial.print("//KO+");
        if (DDRA == B11111111)
        {
           Serial.print("A");
        }
        else
        {
           Serial.print("a");
        }
        if (DDRB == B11111111)
        {
           Serial.print("B");
        }
        else
        {
           Serial.print("b");
        }
        if (DDRC == B11111111)
        {
           Serial.print("C");
        }
        else
        {
           Serial.print("c");
        }
        if (DDRD == B11111111)
        {
           Serial.print("D");
        }
        else
        {
           Serial.print("d");
        }
        if (DDRE == B11111111)
        {
           Serial.print("E");
        }
        else
        {
           Serial.print("e");
        }
        if (DDRF == B11111111)
        {
           Serial.print("F");
        }
        else
        {
           Serial.print("f");
        }
        if (DDRG == B11111111)
        {
           Serial.print("G");
        }
        else
        {
           Serial.print("g");
        }
        if (DDRH == B11111111)
        {
           Serial.print("H");
        }
        else
        {
           Serial.print("h");
        }
        Serial.println();
      }
    }
  }
}

void DOCRLF (String txt, int vval)
{
  Serial.print(txt);
  Serial.println(vval);
}

You wrote: “readStringUntil('\n')”. Your problem looks to me like a timeout in readStringUntil(). Are you sure your Delphi program does send that LF character? And your serial port driver does not convert it to CR?

First check which commands take so much time, 1.5 seconds is a lot for a CPU. When knowing what statements take so much time, you can pinpoint how to improve the performance, high likely it's only one statement (or several times the same statement).

why 9600 baud rate? CR is \r not \n. \n is LF

This is not really a proper answer to your question. As I mentioned in
a comment, I believe your actual problem is the Delphi program not
sending the LF character you sketch expects. Instead, I am giving here a
coding style suggestion: do not repeat yourself.
Whenever you find yourself coding with copy-paste, you should try to
simplify the program using arrays and/or loops. Below is a suggested
alternative version of your loop(), with most of its redundant
repetitive repetitions removed:
struct port_t {
    volatile uint8_t *ddr;
    volatile uint8_t *port;
};

static const port_t ports[] = {
    { &DDRA, &PORTA },
    { &DDRB, &PORTB },
    { &DDRC, &PORTC },
    { &DDRD, &PORTD },
    { &DDRE, &PORTE },
    { &DDRF, &PORTF },
    { &DDRG, &PORTG },
    { &DDRH, &PORTH },
    { NULL,  NULL   },  // there is no port I
    { &DDRJ, &PORTJ },
    { &DDRK, &PORTK },
    { &DDRL, &PORTL }
};

void loop()
{
    // Read the command line.
    if (Serial.available() == 0) return;
    String pport = Serial.readStringUntil(':');
    String pos = Serial.readStringUntil('\n');

    // The "KO" command reads all ports.
    if (pport == "KO") {
        Serial.print("//KO+");
        for (char port_id = 'A'; port_id <= 'H'; port_id++) {
            if (*ports[port_id - 'A'].ddr == 0xff)
                Serial.print(port_id);
            else
                Serial.print(tolower(port_id));
        }
        Serial.println();
        return;
    }

    // Identify the port to act on.
    char port_id = pport[0];
    if (port_id < 'A' || port_id > 'L' || port_id == 'I') {
        Serial.println(F("Error: unknown port."));
        return;
    }
    port_t port = ports[port_id - 'A'];

    // Perform the requested action.
    String command = pport.substring(1);
    String chr = String("//") + port_id + command;
    if (command == "R") {
        *port.ddr = pos.toInt();
        DOCRLF(chr + "+", pos.toInt());
    } else if (command == "I") {
        if (*port.ddr == 0)
            Serial.print(*port.port);
        else
            chr += "-";
        DOCRLF(chr , pos.toInt());
    } else if (command == "O") {
        if (*port.ddr == 0xff) {
            *port.port = pos.toInt();
            chr += "+";
        } else {
            chr += "-";
        }
        DOCRLF(chr, pos.toInt());
    } else if (command == "U" || command == "BR") {
        Serial.print(*port.port);
        DOCRLF(chr + "+", pos.toInt());
    } else if (command == "BW") {
        *port.port = pos.toInt();
        DOCRLF(chr + "+", pos.toInt());
    }
}

I wanna thank you. As a newbie to C (C++)  in Arduino programming I wanted to do it in a way  you just showed me.  Using "ARRAYS"  but I did not know how to. (A little easier in Delphi- I think ). ANyway I want to give you a very special "Thanks  a lot" for 2 reasons.   1: You showed me at  way to solve the problem and 2: by supplying a code example.

@ Juraj:   DARN - I need to update my basics.  Thanks a lot for correcting (always thougt that '\n'  == CR.) Now I'm wiser (a least a little !)

I changed the '/n' to '\r'  added  LF to to the D-7 tx-routine (now transmits  + CRLF . That totally improved the speed on the old "KLUDGE"- version. Responsetime is no > 1.sec (I can' measure to be precise.)   Added my "missing" rutines (void Setup() + DOCRLF(..) ) to the new version, compiled , corrected a typo , compiled again- and VOILA - it worked.  Much faster than before - response time again far under 1  sec (unmeasured) .  I am very ,very pleased.  Thank you to both of you.

@KristianSander, you can set faster baud rate. try 115200 baud or more

@Juraj:  I will set the Baud-rate later, when the D-7 program is improved. There is a speed increase (opimizing code) there,  too .

source: Stack Exchange

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

sort: votes


text:
How do I improve Bluetooth communication?
How do I improve Bluetooth communication?
You will see, in this image using the Bluetooth monitor application, in order to receive the "ON" response, I had to repeatedly send the "O" character:

The code that I'm using now is this:
#include <SoftwareSerial.h>
const int RX_PIN = 0;
const int TX_PIN = 1;
char c = 'F';
boolean activar = false;

SoftwareSerial blueTooth(RX_PIN, TX_PIN);
void setup ()
{
  Serial.begin(9600);
  blueTooth.begin(9600);
}

void loop ()
{
  if(Serial.available() > 0){
    c = Serial.read();
    if(c == 'O'){
      activar = true;
      Serial.println("ON");
    }
    if(c == 'F'){
      activar = false;
      Serial.println("OFF");
    }
  }
  if(activar){
     detectarObstaculos();
  }
}

void detectarObstaculos(){

}

How could I improve the response time?

Why are you using software serial on pins 0 and 1? How do you expect to work alongside hardware serial which also uses pins 0 and 1?

I see it on a tutorial (http://www.instructables.com/id/Add-bluetooth-to-your-Arduino-project-ArduinoHC-06/)
Is that the problem then?

The (unused) bluetooth SoftwareSerial object is conflicting with the HardwareSerial object on the same pins that you are using. One or the other. Make your mind up.

Instructables is full of crap. It should be deleted from the internet.

Ugh, so the tutorial was bad .... I see. @Majenko, I will change my pins then

No need to change your pins. Just delete the SoftwareSerial since you're not actually using it.

@TwoDent That tutorial doesn't even mention software serial. And it isn't in the code either.

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


text:
Expected ')' before ';' token Error
Me and my friend have a project to do and we can't seem to figure out why the code we used for our Arduino Nano Board isn't compiling giving us the Expected ')' before ';' token Error
Here is the code:
// connect motor controller pins to Arduino digital pins
// motor one
int enA = 10;
int in1 = 9;
int in2 = 8;
// motor two
int enB = 5;
int in3 = 7;
int in4 = 6;

void setup()
{
  // set all the motor control pins to outputs
  pinMode(enA, OUTPUT);
  pinMode(enB, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
  pinMode(in3, OUTPUT);
  pinMode(in4, OUTPUT);
}
void demoOne()
{
  // this function will run the motors in both directions at a fixed speed
  // turn on motor A
  digitalWrite(in1, HIGH);
  digitalWrite(in2, LOW);
  // set speed to 200 out of possible range 0~255
  analogWrite(enA, 200);
  // turn on motor B
  digitalWrite(in3, HIGH);
  digitalWrite(in4, LOW);
  // set speed to 200 out of possible range 0~255
  analogWrite(enB, 200);
  delay(2000);
  // now change motor directions
  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);
  digitalWrite(in3, LOW);
  digitalWrite(in4, HIGH);
  delay(2000);
  // now turn off motors
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
}
void demoTwo()
{
  // this function will run the motors across the range of possible speeds
  // note that maximum speed is determined by the motor itself and the operating voltage
  // the PWM values sent by analogWrite() are fractions of the maximum speed possible
  // by your hardware
  // turn on motors
  digitalWrite(in1, LOW);
  digitalWrite(in2, HIGH);
  digitalWrite(in3, LOW);
  digitalWrite(in4, HIGH);
  // accelerate from zero to maximum speed
  for (int i = 0; i ; 256; i++)
  {
    analogWrite(enA, i);
    analogWrite(enB, i);
    delay(20);
  }
  // decelerate from maximum speed to zero
  for (int i = 255; i (&gt);= 0; --i)
  {
    analogWrite(enA, i);
    analogWrite(enB, i);
    delay(20);
  }
  // now turn off motors
  digitalWrite(in1, LOW);
  digitalWrite(in2, LOW);
  digitalWrite(in3, LOW);
  digitalWrite(in4, LOW);
}
void loop()
{
  demoOne();
  delay(1000);
  demoTwo();
  delay(1000);
}

We could really use some help.

Well, for example for doesn't have four parts but three
for (int i = 0; i ; 256; i++) // => for (int i = 0; i < 256; ++i)

Next one doesn't look much better:
for (int i = 255; i (&gt);= 0; --i) // =>  for (int i = 255; i >= 0; --i)

There might be more, but these are really obvious. Like you copied it from some website with some characters translated into the html entities.

Thank you very much,yes indeed we copied the code from a website,thank you for helping us!

If this answer solves your issue and was useful please up vote and accept it


text:
Send data before raising edge of a Clock
I'm trying to control a LED strip that has a custom protocol (developed above of I2C).
But in my tests i was successful figuring out how it works :
You set Clk to zero , you send a bit in the data line , then you set Clk to high. Based on the pixels number , i should send 16bits for each color (Red Green Blue).
I was able to generate a Clock signal at 8MHz with this code :
const byte Clock = 9;
const byte Data = 10;

void setup ()
{
 pinMode (Clock, OUTPUT);
 pinMode (Data, OUTPUT);
 digitalWrite(Data, HIGH);
 TCCR1A = bit (COM1A0);
 TCCR1B = bit (WGM12) | bit (CS10);
 OCR1A =  0;
 }

 void loop ()
 {
 ...
 }

My questions :
How could i send data at that specific time when the clock is at zero ?
Note that using digitalWrite() function was not working due to the frequency limitation of that function.
Thanks for any helpful information.

@Nick Gammon : i think i have to mention you :p

That sounds more like SPI than I2C to me. You can change the clock polarity and the sampling edge by changing the SPI mode.

The SPI sends bytes separated with a small time interval , is't possible to send multiple bits with no time interval ?

When you have a synchronous clock there is no concept of "time interval". Time is irrelevant. That's why you have a clock signal. Only the change of signal level in the clock is relevant. If you have something that requires data at precise times with no variance in the timing then you don't have a clock signal, and the communication is asynchronous (like UART).

I meant a delay between transfer of bytes

Unless you have a very very strange device then nothing cares about delays. SPI doesn't even have the concept of bytes.

That is the whole point of a protocol being synchronous. It's all synchronised by the clock signal. Data is read when the clock changes from LOW to HIGH (or the other way around for some devices). It doesn't care when that change happens. On that it does happen.

However if you gave us a clue what this LED strip and its protocol actually are then we would be in a better position to help you. Without that we're just pissing in the wind.

Thank you for this clear and simple clarification of how SPI works , i'm sure SPI is the choice to go with , the above code turns on all the LEDs with high intensity since data is always at 1. Now i'll try to instantiate an SPI communication with the LEDs and see how it works.

There are some strange protocols out there though. Can you please share the device and datasheet that you are working with?

There's no indication about the version number of the driver , i've attached pictures to the post ,i've tried to debug and test to see the Driver pinout (attached also)...

Are there no numbers on any of the chips?

Nothing , some mask is covering all the chips

After a night of continuous tests i figure out how to control correctly the LED strip using the following :
1- To apply any RGB value (a pixel) you have to send a compete frame of data to all the pixels. In my strip i have 12 pixels ,so to turn for example the first pixel into red , i have to send 11 zero pixels then the red pixel.
2- The delay and timing as mentioned above by @Majenko was the key, you just set the data and pulse the clk , that easy.
3- the protocol used isn't SPI or I2C , it's a custom protocol based on a custom driver developed by a private company (not a driver for general use or market , it was dev for a big wall lighting project).
#define setPin(b) ( (b)<8 ? PORTD |=(1<<(b)) : PORTB |=(1<<(b-8)) )
#define clrPin(b) ( (b)<8 ? PORTD &=~(1<<(b)) : PORTB &=~(1<<(b-8)) )
#define Data 7
#define Clk 9

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

void loop() {
int i, j, k, q, r, lim_j, lim_i;
int red, green, blue;
for(k=0; k<12; k++)
{
r= k%3;
lim_j = 2 - r;
q = k/3;
lim_i = 3 - q;
Serial.print(lim_i); Serial.println(lim_j);
clrPin(Clk);
delayMicroseconds(5);
setPin(Clk);
delayMicroseconds(5);

for(i=0; i<4; i++)
{
  for(j=0; j<3; j++)
  {
    if(i==lim_i && j==lim_j)
      one_pixel(1200, 0, 0);
    else
      one_pixel(0, 0, 0);
  }
}
clrPin(Clk);
delay(1000);
}
}

int one_pixel(int red, int green, int blue)
{
rapid_serialize(red);
delayMicroseconds(5);
rapid_serialize(green);
delayMicroseconds(5);
rapid_serialize(blue);
delayMicroseconds(5);
clrPin(Clk);
}

inline void rapid_serialize (uint16_t color) //just a copy for now , not a pointer
{
uint16_t bit_shift = 32768;
while (bit_shift)
{
 clrPin(Clk);
 bit_shift = bit_shift>>1;
  if ((bit_shift & color) == 0)
      clrPin(Data);
  else
      setPin(Data);
 delayMicroseconds(5);
 setPin(Clk);
 delayMicroseconds(5);
  }
 }

It sounds like you have some misconceptions.
In order to work with clocked signals like in SPI, you set your data line(s) to the desired value, and then raise the clock signal from low to high. The receiving device detects the low to high transition and reads the state of the data lines.
If you did it in the other order (switch the clock signal from low to high, then set the data pin(s).) then the receiver would detect the clock rising edge and try to read the data value before it was set correctly.
With a clock line like in your setup, the communication doesn't rely on fixed timing. The clock line tells the receiver when the data is available, and you can use whatever clock timing you want (up to the max speed supported by the hardware.)

Absolutely right , i figure out the solution after a nightmare of testing.
The problem was actually with the LED driver ,it's not working with any common serial protocol.
Thanks for the help

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


text:
How to get data out of loop?
hi i wrote a code(i modified it actually, please forgive me, im in a mess please help me if you can) for my esp8266 to serial communicate with at tiny 85 ,it will monitor switch state and publish accordingly. now i want to write a code where it wont publish but whenever the serial is available i want it to directly take it and digital write in void callback.
//ItKindaWorks - Creative Commons 2016
//github.com/ItKindaWorks
//
//Requires PubSubClient found here: https://github.com/knolleary/pubsubclient
//
//ESP8266 Simple MQTT light controller

#include <PubSubClient.h>
#include <ESP8266WiFi.h>

int LED3 = 12;
int LED4 = 14;
int LED2 = 13;
int LED1 = 15;

bool switch1;
bool switch2;
bool switch3;
bool switch4;
char data ;
// the number of the pushbutton pin

//EDIT THESE LINES TO MATCH YOUR SETUP

#define MQTT_SERVER "192.168.0.223"
const char* ssid = "TACHYON_HOME";
const char* password = "qwertyui";

//LED on ESP8266 GPIO2

char* lightTopic = "/test/light1";
char* lightTopic1 = "/test/light2";
char* lightTopic2 = "/test/light3";
char* lightTopic3 = "/test/light4";

WiFiClient wifiClient;
void callback(char* topic, byte* payload, unsigned int length);
PubSubClient client(MQTT_SERVER, 1883, callback, wifiClient);

void setup() {
  //initialize the light as an output and set to LOW (off)
  Serial.begin(9600);
  pinMode(LED3 , OUTPUT);
  pinMode(LED4 , OUTPUT);
  pinMode(LED1 , OUTPUT);
  pinMode(LED2 , OUTPUT);

    delay(100);

    // We start by connecting to a WiFi network

    Serial.println();
    Serial.println();
    Serial.print("Connecting to ");
    Serial.println(ssid);

    WiFi.begin(ssid, password);

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

    Serial.println("");
    Serial.println("WiFi connected.");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());

}

void loop(){
  //reconnect if connection is lost
  if (!client.connected() && WiFi.status() == 3) {reconnect();}

  //maintain MQTT connection
  client.loop();

  //MUST delay to allow ESP8266 WIFI functions to run
  delay(10);
   if (Serial.available()>0) /* If data available at serial port, enter if loop */
  {
    data = Serial.read(); /* Read data present at serial port */
    /* Print string with \r\n */
    Serial.print(data); /* Print data received */
    if (data == 'q') {
      client.publish(lightTopic,"1");

    }
else  if (data == 'w') {
      client.publish(lightTopic,"0");
    }
 else  if (data == 'e') {
      client.publish(lightTopic1,"1");
    }
    else if (data == 'r') {
      client.publish(lightTopic1,"0");

    }
     else if (data == 't') {
      client.publish(lightTopic2,"1");

    }
     else if  (data == 'y') {
      client.publish(lightTopic2,"0");

    }
     else if (data == 'u') {
      client.publish(lightTopic3,"1");

    }
     else if  (data == 'i') {
      client.publish(lightTopic3,"0");

    }

  }
}

void callback(char* topic, byte* payload, unsigned int length)
{
  //convert topic to string to make it easier to work with
  String topicStr = topic;

  //Print out some debugging info
  Serial.println("Callback update.");
  Serial.print("Topic: ");
  Serial.println(topicStr);

 if(topicStr.equals(lightTopic)){

   if(payload[0] == '1'){
      digitalWrite(LED1 , HIGH);
    }

    else if (payload[0] == '0'){
      digitalWrite(LED1 , LOW);
    }
 }
 if(topicStr.equals(lightTopic1)){

   if(payload[0] == '1'){
      digitalWrite(LED2 , HIGH);
    }

    else if (payload[0] == '0'){
      digitalWrite(LED2 , LOW);
    }
 }
 if(topicStr.equals(lightTopic2)){

   if(payload[0] == '1'){
      digitalWrite(LED3 , HIGH);
    }

    else if (payload[0] == '0'){
      digitalWrite(LED3 , LOW);
    }
 }
  if(topicStr.equals(lightTopic3)){

   if(payload[0] == '1'){
      digitalWrite(LED4 , HIGH);
    }

    else if (payload[0] == '0'){
      digitalWrite(LED4 , LOW);
    }
  }

}

void reconnect() {

  //attempt to connect to the wifi if connection is lost
  if(WiFi.status() != WL_CONNECTED){
    //debug printing
    Serial.print("Connecting to ");
    Serial.println(ssid);

    //loop while we wait for connection
    while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
    }

    //print out some more debug once connected
    Serial.println("");
    Serial.println("WiFi connected");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
  }

  //make sure we are connected to WIFI before attemping to reconnect to MQTT
  if(WiFi.status() == WL_CONNECTED){
  // Loop until we're reconnected to the MQTT server
    while (!client.connected()) {
      Serial.print("Attempting MQTT connection...");

      // Generate client name based on MAC address and last 8 bits of microsecond counter
      String clientName;
      clientName += "esp8266-";
      uint8_t mac[6];
      WiFi.macAddress(mac);
      clientName += macToStr(mac);

      //if connected, subscribe to the topic(s) we want to be notified about
      if (client.connect((char*) clientName.c_str())) {
        Serial.print("\tMTQQ Connected");
        client.subscribe(lightTopic);
        client.subscribe(lightTopic1);
        client.subscribe(lightTopic2);
        client.subscribe(lightTopic3);

      }

      //otherwise print failed for debugging
      else{Serial.println("\tFailed."); abort();}
    }
  }
}

//generate unique name from MAC addr
String macToStr(const uint8_t* mac){

  String result;

  for (int i = 0; i < 6; ++i) {
    result += String(mac[i], 16);

    if (i < 5){
      result += ':';
    }
  }

  return result;
}

//////////////////i want to write some thing like///////////////////////////////////////
////////////////////////////////
if(topicStr.equals(lightTopic1)||Serial.available()>0){

   if(payload[0] == '1'|| data =q){
      digitalWrite(LED2 , HIGH);
    }

    else if (payload[0] == '0'|| data = w){
      digitalWrite(LED2 , LOW);
    }
/////////////////////////////////////////

so, what is your question?

how to do that i tried it but it isnt working its only taking data from mqtt but not from the switch state

Please, be more specific about what you want to achieve. And show your code! You wrote “I wrote a code for my esp8266”, yet the code you are showing is visibly not something you wrote. You also wrote you want “a code where it wont publish”: if it won't publish, then what interactions should it have with the MQTT server? Should it do MQTT at all? If not, why are you showing a sketch that is al about MQTT?

sorry i modified this code correction i want it to monitor the switches and turn off devices with mqtt and without mqtt too. i want it to control relays even when the network is off.

your post still says that you wrote the code

So you want your program to react to both MQTT and serial messages. You
wrote this snippet:
if (topicStr.equals(lightTopic1) || Serial.available() > 0) {
    if (payload[0] == '1' || data = q) {
        digitalWrite(LED2, HIGH);
    }
    else if (payload[0] == '0' || data = w) {
        digitalWrite(LED2 , LOW);
    }
    // ...
}

Other than a couple of syntactic problems (you mean data == 'q', not
data = q), the logic is not appropriate. This is because:

The test payload[0] == '1' only makes sense in the context of
parsing an MQTT message, otherwise payload cannot be meaningfully
defined.
For the same reason, the test data == 'q' only makes sense in the
context of parsing a serial command.

Since MQTT and serial use completely different commands, you will have
to handle them independently. You can keep the MQTT callback as is, and
implement the parser for the serial commands. Maybe something like:
if (Serial.available()) {
    char command = Serial.read();
    Serial.print(command);  // echo to the serial port
    switch (command) {
        case 'q':
            digitalWrite(LED1, HIGH);
            break;
        case 'w':
            digitalWrite(LED1, LOW);
            break;
        // ...
    }
}

Alternatively, use an if ... else if ... chain if you are not
comfortable with the switch syntax.
I personally would rather store the topic names, LED pins and serial
commands in an array of structs, and loop through the array in both the
MQTT callback and the serial parser. But I assume that may be too
advanced for your current programming level, so maybe just stick with
the simple, albeit verbose solution.

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


text:
Problem using 2 motors
I would like both the motors to spin the attached wheels forward when I push the joystick forward and vice versa. When the joystick is still, the motors should stop spinning. At the moment, when I push the joystick on x-axis and my x variable increases both motors spin, but when I push it in the opposite direction and x decreases, only motor A spins. Additionaly when I connect the arduino to the power (usb cable to my pc), motor B spins for approx 1 second and then stops.
This is the circuit I have (sorry for a lack of schematic, let's hope this wonderful drawing is enough):

The code:
int MotorAA = 7;
int MotorAB = 8;

int MotorBA = 11;
int MotorBB = 12;

int x = 0;

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

  pinMode(MotorAA, OUTPUT);
  pinMode(MotorAB, OUTPUT);

  pinMode(MotorBA, OUTPUT);
  pinMode(MotorBB, OUTPUT);

  digitalWrite(MotorAA, LOW);
  digitalWrite(MotorAB, LOW);

  digitalWrite(MotorBA, LOW);
  digitalWrite(MotorBB, LOW);
}

void loop() {
  x = analogRead(A0);
  Move();
  Serial.println(x);
}

void Move() {
  if (x == 0){
    return;
  }

  if (x > 520)
  {
    digitalWrite(MotorAA, HIGH);
    digitalWrite(MotorAB, LOW);

    digitalWrite(MotorBA, HIGH);
    digitalWrite(MotorBB, LOW);
  }
  else if (x < 480)
  {
    digitalWrite(MotorAA, LOW);
    digitalWrite(MotorAB, HIGH);

    digitalWrite(MotorBA, LOW);
    digitalWrite(MotorBB, HIGH);
  }
  else{
    digitalWrite(MotorAA, LOW);
    digitalWrite(MotorAB, LOW);

    digitalWrite(MotorBA, LOW);
    digitalWrite(MotorBB, LOW);
  }
}

How much current are the motor pulling?  Powering DC motors off the Arduino board is usually a recipe for smoke.  The 5V pin is not there to power your project.  You need to power the motors separately.

@Delta_G Thank you for answering. I've connected the motor driver module to the usb charger with 5V and still the same. When I connected the meter between the motor driver and the motor it showed ~0,12A.

@jsotola Good point, I'll update the post. I would like the motors to spin the attached wheels forward when I push the joystick forward and vice versa. When the joystick is still, the motors should stop spinning.

isolate the area of failure ... swap the A lines with the B lines ... does the problem stay with the motor? ... does it move ? .... switch the motors ... does the problem follow the motor? .... that kind of testing will allow you to determine where the failure is occuring

@jsotola Strangely enough, when I left only the ground and power connected to the driver, motor B acts the same. I thought that without powering the motor a and b pins on the driver, it shouldn't move.

the motor will turn only if IA and IB are different ... you can remove the Arduino .... plug the L9110s into the breadboard .... connect all four inputs to ground ... connect the motors .... now connecting any one of the four inputs to V+ should run one of the motors .... test all of the four inputs, one at a time

@jsotola I did what you said and I think there's a problem with the pin B-IA, which when connected to power doesn't spin the engine. I've looked at the module and saw that there's some solder missing(I think?) on R5 image could this be the cause?

The Arduino can definitely not power that many motors. The Arduino's max output current is 0.1A and you might be drawing around 0.5A. Use an external battery like a LiPo battery for the motor controller.
NOTE: Please watch out! Drawing that many amps from Arduino can kill it! So please use the LiPo or normal batteries!


text:
Is it possible to implement old AVR library onto arduino (specifically, NodeMCU esp8266)
I am a Computer Engineering Undergrad, currently in a cryptography(computer security) course, and I was assigned to do projects about implementing µNaCl library onto Arduino. I currently own a nodemcu esp32 which serves as my device, and I have been searching for µNaCl libraries on the web, but the only thing I found was µNaCl library for AVR devices (based on the makefile of the library, i can see that it's designed for atmega128 and atmega2560). So my question is, is it possible to implement some library meant for AVR on my nodemcu? I mostly do my job with arduino libraries, and have never experimented with avr libraries on arduino, and especially considering my nodemcu is not using atmega-based architecture either, I kinda doubted it. And is the solution to my problem (if it's not possible to use avr based library on arduino) to go purchase a atmega128/atmega2560 and code on atmel studio?
Library: https://munacl.cryptojedi.org/atmega.shtml
Sorry for the long question, kinda desperate here.

That's hard to say without knowing the code, that you want to port. It should be possible, though it might mean rewriting the whole library. Please provide a link to the AVR library, that you are talking about.

the only link to the library i found was in the form of tarball packages so i guess it still needs to be 'make'-d on linux system, but here it goes https://munacl.cryptojedi.org/atmega.shtml
i'll edit the post, thanks @chrisl

nvm sorry it was dumb, there are C files in the zip so you can still look for it without actually making the file first

Why not give it a try? The tarball contains two optimized versions of the library (optimized for size and speed) with some functions implemented in AVR assembly, but also a version in pure C. It could be that it doesn't work on an ILP32 target, but it shouldn't be too hard to just try.

use the original version, not the AVR version

It just looks like normal C code, nothing too hardware (or OS) specific, therefore it shouldn't be too hard to port.  Maybe there's some difficult parts I didn't see, but I checked a few files.


text:
Problem with using pure C code to program default UART (UART0) in Arduino Mega
Can I code default serial port in Arduino Mega (USART0, I assume) in pure C? I mean to set up it and configure directly by ATmega's registers?
I'm asking because I'm trying to do it and I have a problem. Below is code which I use and Arduino doesn't transfer anything...
#include <avr/io.h>

#define F_CPU 16000000
#define BAUD_RATE 9600
#define MY_UBRR (F_CPU+BAUD_RATE*8UL)/(16UL*BAUD_RATE)-1

void setup() {

    UART_Init(MY_UBRR);
}

void loop() {
    UART_Transmit('a');

 }

void UART_Init(unsigned char ubrr)
{
   UBRR0H = (unsigned char)(ubrr >> 8);
   UBRR0L = (unsigned char)ubrr;
   UCSR0B = (1<<RXEN0) | (1<<TXEN0);
   UCSR0C = (1<<USBS0) | (1<<UCSZ00);
}

 void UART_Transmit(unsigned char data)
 {
    while(!(UCSR0A & (1<<UDRE0)))
    UDR0 = data;
 }

That code I created following the datasheet for ATmega 2560. It has been compiled and programmed but doesn't work at all...
Please give me any advice. It's important for me use just C code in that case.

You forgot the semicolon after while(!(UCSR0A & (1<<UDRE0))).

About it compiling with a missing ';': The reason it did is because it is still syntactically correct C. Indenting the "UDR0 = data;" statement should make it clear why.

I tried your program on an Uno, and it worked as expected once I fixed
three problems:

Removed #define F_CPU 16000000. This is not a big issue, but it
fixes a warning about that constant being already defined by the
Arduino environment.
Added the UCSZ01 bit to UCSR0C in order to work in 8-bit mode
instead of the uncommon 6-bit mode.
Added the semicolon after while(!(UCSR0A & (1<<UDRE0))).

Note also that there is no point in loading UBRR0 in two steps. You
can just UBRR0 = ubrr and trust the compiler to do the right thing.

I suggest to use existing code and copy that or use that.
This is the Arduino HardwareSerial : HardwareSerial.cpp
You can find more code at avrfreaks.net. Click on "Projects", search for "uart" and "usart" and try to find code that is compatible with the ATmega2560. Some projects have buffers and many functions, others are very simple.
The result might not be compatible with other Arduino code (for example with interrupts). Why do you not want to use the Arduino Serial library ?


text:
Powering a DC motor with an external battery
I'm working on a project where i need to control a 6 volt motor with an Arduino. The motor that I'm using requires 6 volts so I'm using a 9 volt with a voltage divider to get those 6 volts. My problem is that when I use the external power, the motor keeps spinning and ignores the input from the Arduino. If I use a 5 V battery and draw the 5 V from the Arduino, it works fine. I made sure that the voltage divider sends out 6 volts and the current code should have the motor not spinning. Here is the circuit: Motor Schematic.
What could I do to make the motor take the input from the Arduino?
Note: The schematic isn't like my actual circuit. In reality I have 6 V power supply instead of a 9 V and a voltage divider. I also am using a motor that requires 6 volts, while the one in the schematic requires 5 V.

The circuit appears to have 1KΩ in series with 2KΩ for the voltage divider, and it shows a 9V battery supplying power.  Is that how things actually are, or do you have some other resistor and some other power supply?   Also,  Please edit your question to include the motor part number and/or specifications, such as its rated current and its KV number

Neither a 9v transistor radio battery nor a voltage divider are suitable for powering a motor.

Im not using a 9v battery in the actual circuit, its just all that was available on circuits.io

Still, the voltage divider is a bad idea.

Your schematic is bad - the motor is connected betveen base and power, emitor is connected to ground.That keeps the transistor open, and B-E voltage is like 0.7V, rest is for the motor to rotate.
More over the transistor is open, so if you send pulses from pin 3, they are shortcuted to ground thru the transistor, not affecting the motor at all.
Switch the wires to Base and to Colector (lines 48 and 49) and it should work better.
(Still I would not use divider 9->6 volts, losing a lot of power constantly, I would rather change the PWM little down (and have it relatively fast, 1kHz or more) and the motor should be OK, if effective voltage ther would be under 6V - so the PWM under like 66% HIGH. Also shortcutting pin3 to ground with resistor is not optimal, the resistor should be between pin3 and Base.)

Switching the base and collector worked great! Thanks so much for the help

Good :) So can you mark it as solution?

In power application like motor driver you can not use voltage divider for step down the voltage because resistor drop the voltage when current flowing from the resistor increase. You can used voltage regulator or buck converter. The motor will work fine. Even you can use 9V battery and control the speed of dc motor using PWM. you use the following schematic both will work fine. The 2n2222 is the general purpose npn transistor which is used for power amplification. The arduino board can not provide large current at output pins to drive motors directly having a current rating more than 250mA.
In above schematic the LM2596 buck converter is used which current rating is about 3A. and you can adjust the desired output voltage.

The second option which shows in schematic is to use 6V battery.


text:
How to connect Wi-Fi shield ESP-12E-ESP8266-UART-WIFI-Wireless-Shield with Arduino
I have bought this shield from ebay and now I don't know how to use it, ESP 12E ESP8266 UART WIFI Wireless Shield for Arduino UNO R3 Bouclier Sans filfr:

There are no instructions in the box or anywhere on internet for this board. The only description I found everywhere is this:

Description:

Standard pin interface to achieve full compatibility with the pitch Arduino Uno, Mega and so on. (Unless the standard size Arduino, such
  as Nano, Mini)
3.3V power supply using advanced chip (with the official expansion board power chip CC3000 same), so 3.3V Arduino board provided more
  accurate, so ESP8266 as official CC3000 chip work as normal, there is
  no gap.
It leads to a WiFi module power supply / service interface to facilitate developers to extend the power supply and maintenance.
Onboard ESP8266-12 stable industrial grade serial WiFi module, using an enhanced PCB antenna, signal better.
You can quickly switch DIP switch ESP8266-12 industrial grade WiFi stable operation mode (such as operating mode and upgrade mode)
  module, integrated serial chip, quickly flashing the firmware.
Built-in 5V to 3.3V TTL level converter to prevent high-pressure Arduino TTL level of the WiFi module damage.
Onboard ESP8266-12 stable industrial grade WiFi module with a metal shield, immunity to interference.
Onboard ESP8266-12 standard pitch leads to a stable industrial grade WiFi module all interfaces, enabling developers to easily
  develop deep.
Use stackable design, it can continue to accumulate above the other modules, easy to use.
Onboard four LED displays the status of ESP8266, namely PWR, DFU, AP, STA

What should be the board settings for this?
I am new to electronics please help me how can I connect this with Arduino.

I presume you plug it into the Arduino, as it is a shield. Are you asking how to code for it?

yes I need some generic library so I can run simple code for that device, I have code

Very often the seller list example code and libraries, did you try those?

thry didnt list anything and I didn't found anything anywhere, I searched lot, I search same device on ebay and other sites but nothing found in description

Nice board, but I'm also puzzled why you bought it if you don't know what to do with it. Did you have something in mind when you got it? More background is required. If you have code, post it. Describe what it does, what it doesn't do and what you're trying to but can't achieve. The possibilities with this board are really endless

I just want to create server on this device which I can achive by running any simple code but I am not able to upload code on the device code is not matter just want to run any code on that device but I am getting error while uploading and not sure what should be setup because seller didnt gave more information about device, I am still working on that trying to flash firmware and trying other things, i'll post here if I found something,

I have exactly that very board you mentioned into your article. It is a fake board. You said one has to disconnect the 2 transistors which lead to the pins 0 and 1. Okay. This makes sense, because they apparently are blocking the upload process from the IDE's serial COM Port.

From @Peter: What do you mean by the changing of the switches? Please could you explain it perhaps with a little drawing again? Thank you in advance you will be doing myself and others a favour. Have a good time. Peter

Hello, I've got the same shield, as in exactly the version on your picture. with the 'Shia1d' and the 'KXK' above 3 & 4 from DIP switch.
Did any of the below answers help you out? I was following claus' blog post and another post from claus

Changing baud rate and flashing firmware through debug ports seemed easy. But when connecting to Arduino, it only acts as access point and can't seem to be able to talk to the shield from Arduino.

There are some fake Modules on eBay! Only after changing the wiring can you use them. The fake modules have the wrong text printed on it.

Moer info $ tech

instead of

More info & tech

But when you change the wiring you can use the shield!
The two transistors which are connected to Arduino board pin 0 and 1 have to disconnected. Also the connection to the switches 1 and 2 have to change. Then you can stack ESP-12 shield on the Arduino. You can now flash the Arduino Uno when you switch off (switch 1 and 2) With the old wiring you can't use it because the transistors are wrong connected.
The voltage divider is need for 3,3 V ESP-12 RX pin

The two transistors which are connected to Arduino board pin 0 and 1 have to disconnected. Also the connection to the switches 1 and 2 have to change. Than can you stack ESP-12 shield on arduino. You can now flash the Arduino Uno when you switch off (switch 1 and 2) With the old wiring you can't use it because the transistors are wrong connected. https://lh3.googleusercontent.com/-1jOVVFXLXgQ/WIImhPhDVTI/AAAAAAAAAV8/VNd8nN_h7MMx8o-MWcf8ozXq8BSljZ_8ACJoC/w530-h707-p-rw/ESP-12%2Bfake.jpg

The voltage divider is need for 3,3 V  ESP-12 RX pin.https://plus.google.com/photos/photo/105750023979112812523/6378417390811089410?icm=true

Just to add to Andreas' answer, this is what the shield's circuit looks like at the board level:

For connecting to a 3.3v Arduino I found the neatest solution was:

Remove all the components from the area above
add 2 small bits of wire to short the areas shown in green above
Switch the DIP switch so 1&2 are towards 'ON' (to connect serial to D0/D1) and 3&4 are 'OFF' (to disable the bootloader)
Use with your Arduino on D0/D1 at 115200 baud

(You may have to flash you own ESP8266 command firmware using the debug port and a USB-TTL converter, in which case setting 3&4 to 'ON' and resetting the ESP8266 will stick it into bootloader mode. If you're doing this you can also send AT+UART_DEF=9600,8,1,0,0 to put the ESP8266 into 9600 baud mode permanently if you're using an Arduino that can't handle the higher baud rates)

Same Shield here, the most useful guide I've found is https://www.espruino.com/arduino-esp8266
The DIP switches are:
Switch  Function
SW1 Connect ESP8266 TX to pin D0
SW2 Connect ESP8266 RX to pin D1
SW3 Enable bootloader mode
SW4 Use DFU LED to show serial activity (?)

For connection to the Arduino, just stack the shield over the Arduino board.

(source: robotshop.com)

I just managed to get mine working and wrote a blog article about it.
Long story short:

Set all DIP switches "off"
configure the ESP8266 to use 9600 baud using the AT command "AT+UART_DEF=9600,8,1,0,0"
connect debug ports RX/TX to Arduino pins of your choice (not being pin 0 and 1)
Use the WiFiEsp Lib and tell it to use "your" pins and 9600 baud

A search on the designer's name turned up a few posts by people working with this board. This post was the most useful one I found. I don't have this shield and haven't tested this poster's instructions, but it seems worth trying:

Hi! Finally back here, more enlightened! :D I have finally done some
  stuff with the 8266 shield. I just wanted to share it with you all.
  Since I know I wanted all this before I started. I write all this a
  little bit as a "for dummies" just to make sure every step is
  included. So to be more precise, I use a Arduino uno with a (se
  below).
1: (identifying) The shield is a "ESP8266 ESP-12E UART WIFI Wireless
  Shield for Arduino UNO R3" (from Ebay). Since there seems to be none
  documentation about this board, hopfully this will help you. I think
  there was some pictures before on this thread. On my board it states:
"Arduino ESP8266 Wifi shield. Version 0.9 by WangTongze." (and 1.0..
  I've got two)
Here is a good link to identify which ESP8266 module you got if you
  want to know exacly what you got (if it is a different wifi board) :
  wiki/doku.php?id=esp8266-module-family
There a 4 DIP switches on this board are numbered from 1-4. To be
  honest I really don't know what 1 and 2 is. But my guess is that you
  can use TTL levels on TX & RX opposed to 3.3 which the 8266 module
  uses directly. These two are always set to DOWN for me. Second though,
  if so, I might set them to UP when using Arduino. I usually play
  around with the board with a USB to 232 converter when testing. The
  other two, 3-4, are connected to GPIO 0 and something else xD. I
  really doesn't matter really. All I know, that I set these to UP to
  start a firmware update. Here is a good link that might be somewhat
  equal to what the shield has implemented.
http://blog.falafel.com/how-to-wire-the ... ogramming/
2: (using Arduino with the shield) So everywhere, including this
  thread states that Arduino UNO doesn't handle the software emulated
  serial very good at high speeds. That is true :D So I got it to work
  perfectly with a baud rate 9600. What I did was to find a firmware
  that has default baud rate 9600 from AI thinker. I never really got
  the baud change to work. AT+CIOBAUD=9600 never got stuck after a reset
  (rst button och a AT+RST). And the other AT+IPR=9600 broke the
  firmware. If someone got this to work, please write here in this
  thread!!
Here is a link: http://wiki.aprbrother.com/wiki/Firmware_For_ESP8266
The only wiring I did to make it work, is to connect the tx and rx to
  Arduino's pins. (rx->tx and tx->rx). According to this example:
  http://allaboutee.com/2014/12/27/esp826 ... d-circuit/ connect to pins
  2 and 3. The tx and rx from the 8266 shield are located on the left
  down side. There are other pins you can use also.
3: (flashing a firwmware) To set the board on flash mode, put the DIP
  switches to 3-4 to UP, press the 'ESP-RST' button. When flashing is
  done, set these to DOWN and press the 'ESP-RST'. Maybe there is a way
  to flash a firmware with the Arduino, but I finally bought a "FT232RL
  3.3V 5.5V FTDI USB to TTL Serial Adapter Module for Arduino Mini Port T". There is a picture here: http://blog.falafel.com/how-to-wire-the
  ... ogramming/. I use this flash software:
https://github.com/Stadslab/ESP8266_exa ... te%20Ready
Because you can't really do any setting with it and it has worked 100%
  of all time for me and my use.
So to connect the FT232RL to the 8266 board:
(pins down) from left to right you have: dtr, rx, tx, vcc,cts and gnd
  and on the wifi shield from left to right: txd, rxd, 5v, gnd, 3v3.
  rx->txd, tx->rxd, gnd->gnd, vcc-> 3v3. Remeber that the FT232RL board
  has a jumper to change the voltage. You should use 3.3v. But for me I
  had some problems flashing, so I actually the the voltage to 5v and
  then connect the vcc to 5v connector on the wifi board. Never had any
  problems after that.

In addition to Andreas' answer, I believe he is correct about the general wiring of the 2 pins #0, #1 for some cheap clones.
I got mine to talk to the serial monitor (Arduino) by jumpering over the shield pins directly to the header pins next to the ESP-12E module.
This is at 115200 baud and Both NL and CR on the serial monitor.


text:
Connecting multiple boards to Arduino Uno r3
How can I connect the Arduino RFID RC 522 and SD card adapter to one Arduino Uno R3? As each library takes specific pins in Arduino for MOSI, MISO, CLK. So I have conflict in the pins, how can this be solved?


text:
Reducing static on button reading
I have a very simple code for a controller I'm working on for a robot.
void setup() {
  // put your setup code here, to run once:
  pinMode(3,INPUT);
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  Serial.println(digitalRead(3));
}

The only problem is that I can't get a constant reading on switches because when I flick the switch I will get a constant stream of 1s, but when I flick the switch off I get a sporadic stream of ones and zeros. I have noticed though that if I put my finger on the USB port leading from my Arduino Nano I get a constant stream of 1s when on and zeros when off.
Does anyone have a recommendation to get around this problem or simulate touch on the USB port?

Is the GND correctly connected? Sounds like that's your problem

It sounds more like you have no pullup or pulldown resistor wired. When using pinMode(pin, INPUT_PULLUP), you are activating the Arduinos internal pullup resistor.

Sounds like you need a pull-down resistor.
If a CMOS input like and Arudino digital input isn't attached to anything it will "float", bouncing between 1 and 0.
Attach a 10k resistor between the input pin and ground (before the switch). That way, if the switch is off/open, the resistor pulls the input to ground.
If the switch is on/closed, it feeds +5V into the pin, overwhelming the resistor.
(Note that you can instead use a pull-up resistor, and then have the switch connect to ground instead of +5 volts. When you do this the input is reversed {HIGH if the switch is not pressed and LOW if the switch is pressed.} There is an internal pull-up resistor on the digital input pins that you can connect by using the setting INPUT_PULLUP instead of INPUT when you configure the pin with the pinMode() function. That way you don't need an extra resistor.)
Also note that in addition to needed a pull-up or pull-down resistor, you may need to debounce your switch. You can do this by writing your code that detects switch presses to ignore changes for 100 ms or so. This avoids the rapid on/off/on/off jitter you often get from switches as their contacts transition from open to closed (or closed to open.)


text:
I can't get code transferred to my Arduino Mini Pro
About 3 years ago Sparkfun had a sale on Arduino Minis, so I bought 6 of them (3 x 3.3 V @ 16 MHz and 3 x 5 V @16 MHz). I used two of them for separate projects (everything worked flawlessly) then stored the rest. Then last night I grabbed one of the 5 V and 3.3 V Minis and tried to upload the Blinking LED program to them. But I kept getting this error:
avrdude: stk500_recv(): programmer is not responding

I'm getting similar results on all of these computers: Mac OS X 10.10, Mac OS X 10.7, and Windows 7. I tested with default drivers and I tried installing fresh drivers based on the HardwareID's of the devices. I used both the newest version of Arduino IDE and a few older versions.
I've tried two different USB devices: Sparkfun Basic FTDI and a Generic USB to Serial PL2303 similar to this one. They both produce the same error, however the FTDI seems to be somewhat able to communicate since the RX & TX lights are flashing as well as the Arduino LED. With PL2303, the LED is lit constantly.
While searching last night, I found a few forums where people suggested things like hitting the reset button and selecting different Arduino boards in the IDE.

How did you store them?

@Majenko I stored them in the original box & antistatic case they came in from Sparkfun. The FTDI I stored in a plastic drawer where I organize the rest of my electronics.

Can you show how you wire the USB interfaces up?

The FTDI is a direct connection (BLK->BLK, CTS->GND, 5V->VCC, TX->RX, RX->TX, GRN->GRN) and the PL2303 I had to make jumpers from (GND->GND, RX->TX, TX->RX, 5v->VCC)

I don't know what BLK and GRN are, nor why CTS would be connected to GND...

Here, I took this from the Sparkfun website. They advertised it as a direct connection, and the first two projects I coded worked perfectly using this method.

BLK and GRN aren't pins I suspect you mean GND and DTR respectively.

Things have changed in the three years since you last used your FTDI board.
Most importantly avrdude has changed.
You will most likely find that you can program your boards perfectly fine using Arduino IDE 1.0.1.
What has changed is that avrdude has been modified to counter a change in the FTDI drivers. It used to be that the FTDI drivers would pulse the DTR line when the port was opened, but that stopped happening with newer drivers. So AVRDude started asserting the DTR line instead. However it doesn't pulse it, it just holds it low.
The problem with that is if the DTR is connected direct to the RESET pin the main chip is held in reset mode all the time instead of it just being reset briefly to reset the board.
The "fix" is to place a 100nF capacitor between DTR and RESET instead of directly connecting it. That converts the steady low into a short pulse which resets the board and enters the bootloader.

Thank you! That worked for my 3.3v. One small correction though, there is an inline SMD capacitor on the Mini board between reset and DTR, I needed to connect the 100nf in series rather than bypassing it and going directly to the RESET pin.
Also, this trick didn't seem to work with my 5v board. Is there a different configuration I need for that Arduino?

For programming a Pro Mini, I find the CP2104 adaptor works better than the FTDI or PL2303 based units, on both Mac and PC. You can find the CP2104 adaptor from many sources, such as TxHang Electronic:
http://www.ebay.com/itm/USB-2-0-TTL-UART-6PIN-Module-Serial-Converter-CP2104-STC-PRGMR-Replace-CP2102-/200958955841?hash=item2eca165141
(You may need to install CP2104 software drivers on some platforms)
This is how I wire them together:

CP2104_________PRO MINI

DTR------------DTR
3.3V--------- - * NOT USED (VCC)
5V --------- - -* NOT USED  (VCC)
TXD------------RXD
RXD------------TXD
GND-----------GND

Note: * While you may be able to power your (unloaded) Pro Mini from your CP2104 adaptor, it's better to use a separate supply that is appropriate for the version of the Pro Mini you use. Good luck. /DerrickA


text:
Error on UNOr3--> avrdude: ser_open(): can't open device "/dev/ttyUSB0": No such file or directory ioctl("TIOCMGET"): Inappropriate ioctl for device
When I try to upload my program on the Arduino Uno Chinese clone, It says
 -> avrdude: ser_open(): can't open device "/dev/ttyUSB0": No such file or directory
ioctl("TIOCMGET"): Inappropriate ioctl for device

My Arduino Programmer: ArduinoISP
My Arduino Software version: 1.6.8
My OS: Linux Mint

Can you help me fix this error?

What is the serial port of your arduino?

My Serial port is /dev/ttyUSB0 . I am using Linux Mint .

if you do ls /dev/ttyUSB0 does it show something? If so, are you a member of the dialout group_

Run from a terminal: test -w /dev/ttyUSB0 || echo Error - if it tells you Error you don't have permission to access the device. If it tells you nothing then your permissions are fine.

@frarugi87, when I type  'ls /dev/ttyUSB0' , it shows me a message -> /dev/ttyUSB0

@Majenko , I typed your command, it shows nothing. It executes well.

You may have done this, but...  Did you install the Linux serial port driver for the serial-port-chip on the Arduino Uno?  Also, might you have more than one USB device emulating a serial port plugged into your computer?  That is, do you see /dev/ttyUSB0, /dev/ttyUSB1, ... ect?

"Arduino UNO chinese clone"...  Also consider the possibility of your Arduino containing a counterfeit serial-port-chip (FTDI chip).  There are versions of the FTDI Windows Driver that will reset counterfeit FTDI chip USB ID's to an unusable value. And other versions of the Driver that will inject extra characters (I think "COUNTERFEIT") into the serial stream.

@frarugi87 Hi, I encountered the same problem and I did your command and received No such file or directory  answer from the terminal. However I was formerly able to run programs, even "blink".

@Marine1 look at the dev folder, and see if you have a ttyUSB peripheral..

This could be any number of different problems.  Here are several common causes:

You have multiple USB serial port devices connected to your computer. Try using the command ls -l /dev/ttyUSB* to check if your computer thinks there are more than one terminal USB device.  Disconnect all of them, then only connect the Arduino Uno.  Then repeat the check.
You do not have permissions.  This is tricky to check as Linux offers a flexible but complicated root, group and user permission paradigm.  You should NOT make a habit of this, but, for a quick check, you can try running the Arduino application as root and check if you can upload a sketch to the Arduino Uno.
You have a counterfeit FTDI chip on your Arduino Uno that has been rendered useless by certain versions of the Windows FTDI Driver.  The USB IDs can get reset to useless values.  I believe the current FTDI Windows Driver no longer does this.
You did not install the Linux FTDI driver.  A driver is a program to abstract the hardware from the application.  In this way, different hardware can be treated the same by the application, simplifying the application.  However, the wrong driver/hardware combination may not work as expected.

FTDI drivers are not a separately installed item on most Linux distributions in the way they are with Windows.  Generally they would only need to be manually added to a very odd Linux such as might be found on an embedded or special purpose system or a custom build from scratch - the code has been part of the kernel source effectively forever and will be built and shipped as an automatically loading module in any ordinary full-featured Linux.

Don't run arduino IDE as root to test if permissions is at fault here. Run this command instead: sudo chown root:YOURUSERNAME /dev/ttyUSB0 to give yourself access to the tty device

I had the same problem and solved with the suggestion of ndemou:
sudo chown root:YOURUSERNAME /dev/ttyUSB0

This is a bad idea, in particular on a typical dynamically configured linux with udev or similar managing /dev nodes you will have to do it every time you connect the device.  Add your user to the appropriate group instead, which is a lasting fix.

@Greenonline - please don't make trivial edits of bad answers.

@ChrisStratton - Please, kindly refer to the Review Queue.

That means absolutely nothing.  This is a fundamentally bad answer, and that fact cannot be changed by format editing.  Additionally, even if this were a good answer, your edit would be pointless.  Such pointless edits waste everyone's time.  Kindly desist.


text:
Problems coding a 12 pin 7 segment display and grove temperature sensor with Arduino Uno
I am trying to code my 12 pin seven segment display to display the temperature from my grove temperature sensor. I am new to this and I have been struggling, so if anyone could help that would be much appreciated.
My temperature sensor is displaying its information in the serial monitor, however I want the temperature displayed with the 7 segment display - that's where I need help.
//Temperature Variables
//thermistor = value of the thermistor
int a;
float temperature;
int thermistor=3975;
float resistance;
boolean DigitOn = LOW;
boolean DigitOff = HIGH;
boolean SegOn=HIGH;
boolean SegOff=LOW;

int DigitPins[] = {2, 3, 4, 5};
int SegmentPins[] = {6, 7, 8, 9, 10, 11, 12, 13};

//N is for numbers and NxP is a number with a decimal point behind
int BLANK[] = {LOW, LOW, LOW, LOW, LOW, LOW, LOW, LOW};
int N0[]    = {HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, LOW, LOW};
int N0P[]   = {HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, LOW, HIGH};
int N1[]    = {LOW, HIGH, HIGH, LOW, LOW, LOW, LOW, LOW};
int N1P[]   = {LOW, HIGH, HIGH, LOW, LOW, LOW, LOW, HIGH};
int N2[]    = {HIGH, HIGH, LOW, HIGH, HIGH, LOW, HIGH, LOW};
int N2P[]   = {HIGH, HIGH, LOW, HIGH, HIGH, LOW, HIGH, HIGH};
int N3[]    = {HIGH, HIGH, HIGH, HIGH, LOW, LOW, HIGH, LOW};
int N3P[]   = {HIGH, HIGH, HIGH, HIGH, LOW, LOW, HIGH, HIGH};
int N4[]    = {LOW, HIGH, HIGH, LOW, LOW, HIGH, HIGH, LOW};
int N4P[]   = {LOW, HIGH, HIGH, LOW, LOW, HIGH, HIGH, HIGH};
int N5[]    = {HIGH, LOW, HIGH, HIGH, LOW, HIGH, HIGH, LOW};
int N5P[]   = {HIGH, LOW, HIGH, HIGH, LOW, HIGH, HIGH, HIGH};
int N6[]    = {HIGH, LOW, HIGH, HIGH, HIGH, HIGH, HIGH, LOW};
int N6P[]   = {HIGH, LOW, HIGH, HIGH, HIGH, HIGH, HIGH, HIGH};
int N7[]    = {HIGH, HIGH, HIGH, LOW, LOW, LOW, LOW, LOW};
int N7P[]   = {HIGH, HIGH, HIGH, LOW, LOW, LOW, LOW, HIGH};
int N8[]    = {HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, LOW};
int N8P[]   = {HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, HIGH, HIGH};
int N9[]    = {HIGH, HIGH, HIGH, HIGH, LOW, HIGH, HIGH, LOW};
int N9P[]   = {HIGH, HIGH, HIGH, HIGH, LOW, HIGH, HIGH, HIGH};
int MIN[]   = {LOW, LOW, LOW, LOW, LOW, LOW, HIGH, LOW};

//Array of pointers for the 4 digits
int* lights[4];

//char array coming from the serial interface
//4 numbers or chars, 4 optional decimal points, 1 end-of-line char
char incoming[9] = {};

void setup() {
  Serial.begin(19200);
  for (byte digit=0;digit<4;digit++) {
    pinMode(DigitPins[digit], OUTPUT);
  }

  for (byte seg=0;seg<8;seg++) {
    pinMode(SegmentPins[seg], OUTPUT);
  }

  //initialize display with 1.234
  lights[0] = N7;
  lights[1] = N9P;
  lights[2] = N3;
  lights[3] = N4;
}

void loop() {
  //Temperature Sensor
    a=analogRead(5);
    resistance=(float)(1023-a)*10000/a; //get the resistance of the sensor;
    temperature=1/(log(resistance/10000)/thermistor+1/298.15)-273.15;
//convert to temperature via datasheet ;
    //delay(1000);
    Serial.print("Current temperature is ");
    Serial.println(temperature);
    //delay(500);
  //read the numbers and / or chars from the serial interface
  if (Serial.available() > 0) {
    int i = 0;
    //clear the array of char
    memset(incoming, 0, sizeof(incoming));
    while (Serial.available() > 0 && i < sizeof(incoming) - 1) {
      incoming[i] = Serial.read();
      i++;
      delay(3);
    }
    Serial.println(incoming);

    //show the input values
    for (int y = 0; y < 4; y++) {
      Serial.print(y);
      Serial.print(": ");
      for (int z = 0; z < 8; z++) {
        Serial.print(lights[y][z]);
      }
      Serial.println("");
    }
  }

      //end if, i.e. reading from serial interface
      //This part of the code is from the library SevSeg by Dean Reading

  for (byte seg=0;seg<8;seg++) {
        //Turn the relevant segment on
    digitalWrite(SegmentPins[seg],SegOn);
    //For each digit, turn relevant digits on
    for (byte digit=0;digit<4;digit++){
      if (lights[digit][seg]==1) {
        digitalWrite(DigitPins[digit],DigitOn);
      }
      //delay(200); //Uncomment this to see it in slow motion
    }
    //Turn all digits off
    for (byte digit=0;digit<4;digit++){
      digitalWrite(DigitPins[digit],DigitOff);
    }
    //Turn the relevant segment off
    digitalWrite(SegmentPins[seg],SegOff);
  }
    //end of for
}

Add four spaces to the beginning of each line of code, so that the site interprets it correctly.

You haven't actually asked a question other than how to show images. What's the problem? What are you expecting and what do you get. Please add this information in your question rather than in the comments.

@jms Do not try formatting the text manually. Use the right buttons for that. {}

I want the temperature displayed with the 7 segment display. - OK. What is happening exactly?

I see that you are using some code from the SevSeg library, but you do not appear to include the header SevSeg.h in your sketch. How are you using the library?

Your temp sensor is obviously working if it displays the temp on the serial monitor. I would now write a new sketch, forgetting the temp sensor for the moment, and get numerical data on to the seven segment display correctly.
How many digits does the seven segment display have? What interface are you using, if any? How is the display connected to the Arduino? You need to provide the information in your question, to allow us to give you an accurate answer.
You may want to take a look at my answer to Programming 4-digit seven segment display using interrupts only on SE Robotics. I had the same issues, about a year ago, when I was trying to display data on a cheap seven segment display that I purchased in BKK, and I ended up writing an Arduino library in order to get it to work, see Dual Seven Segment Display Madness. However, I don't recommend that you write your own library, and instead use a pre-built one. Take a look at the SevenSeg library. That is what I used eventually.
I see that you are using some code from the SevSeg library, but you do not appear to include the header SevSeg.h in your sketch. If you are happy using the SevSeg library, then first write a sketch using the examples and the tutorials, so that you can get data displayed. Then integrate that software with your temperature sensor software.
You really do need to divide your project into two parts, the sensor and the display. Once you are happy with displaying data on the Seven Segment display, then, and only then can you think about getting the temperature sensor data displayed on it.

The simple way is to use a MAX7219 chip which does most of the work for you.
You haven't said what LED device you have but an example of wiring it is:

That chip does the multiplexing for you. I have a detailed description here.
If you don't want to use another chip you could use 12 of your Arduino pins. It's a little tedious because you need to be refreshing the display even while you are doing other things. You could use a timer interrupt for that.
The code you posted looks like it might work. In what way does it not work?

I have been struggling ...

That doesn't tell us much. Do all segments light up? None? Incorrect ones? Does it flicker? What is the problem exactly?
Please read How do I ask a good question?

If you do not have an MAX7219 or equal, you should read this: http://arduino.stackexchange.com/questions/21608/how-to-use-a-common-anode-7-segment-4-digit-display/21609#21609


text:
Can I use a camera sensor from a not functioning smartphone in Arduino or Raspberry pi?
I want to use the OmniVision_OV16860 camera sensor from a not functioning Moto G4 plus phone to capture pictures using Arduino or Raspberry Pi.
Is it possible to do that? If yes, explain the whole process.

For your RPi questions, there is a RPi stackexchange website.

remove the camera from the phone .... 2) obtain the data sheet for the camera .... 3) build a connector adapter so that you can plug the camera into a breadboard .... 4) write necessary software to "talk" to the camera

no, no arduino supports MIPI interfaces, so you have no way to hook it up, and even if you could, there's nowhere near enough ram on an ardunio to store a single image, and there's no way to chuck image data from the camera, so it's simply impossible.

Is it possible to ... use the OmniVision_OV16860 camera sensor (on an)
  Arduino?

It is doubtful as bare image sensors usually require specialized software drivers to be of any use. Also, a common Arduino does not have the power to do image processing.  Only the few Arduino's built with unusually powerful processors could handle image processing.  But, at this level, expect little support as most do not do image processing on the Arduino platform.

Thanks for the answer :) Can you suggest some idea to use this camera  sensor  because the phone is not functioning and i am searching for some cheap and working method to use that camera except of using the sensor in other phone

If only the cell radio portion of the phone does not work, the easiest way to use the camera is to use it in the Android device.  Here is a RPi stackexchange question / answer where this is discussed.  I have several dead phones and have opted to purchase the cameras specifically intended for the RPi. Again, the powerful features needed to transfer images are not available on common Arduino platforms.


text:
How to send an integer through pyserial with Python to an Arduino and get back the same result?
There has been similar questions all over the internet but none of them seem to answer my question, so can anybody tell me what is wrong with this code and how I can fix it?
Python code:
import serial

arduino_linux=serial.Serial("/dev/ttyACM0",9600)
while True:
    print('write:',str.encode('90')) #print the sent value through the serial to check it with the readed value
    arduino_linux.write(str.encode('90'))#send the following value
    print('readed:',arduino_linux.read())#read the same value back from the arduino

my arduino code is as follows
void setup() {
  Serial.begin(9600);

}

void loop() {
  Serial.write(Serial.read());

}

this is a simple sample of a project, my aim from this code is to send the integer number 90 from the pyserial and make sure the value the Arduino is reading is the same integer.
In case if necessary my project is an object follower with object detector and after calculating all the angles and everything it sends them to the Arduino so the Arduino can act up on the servo's.
This is the result I am getting:

But I would like something like:
write:b '90'

readed:b '90', not b'9' or b'0'
I would also like to know how I can change these bytes to integers before I write them to a servo.

what version of python and the pySerial library you use?

Use Serial.write() on Arduino to send raw bytes. print converts them to text.
read is not blocking, it doesn't wait for a byte and returns -1 if the receive buffer is empty. Check if read returned -1 or use Serial.available() to get the number of bytes in the RX buffer.
Serial 'echo':
void loop() {
  if (Serial.available()) {
    Serial.write(Serial.read());
  }
}

i have seen it and used Serial.write().  but i dont seem to quit understand what you said for the second problem. give me some specific example. Thanks


text:
Splitting a Serial.readString into string array
I am working on a project where I need to split incoming data from serial (time to be exact, so aa:bb:cc) and need to split it into aa then bb and cc, ideally into  an array. I know I could use readStringUntil and make 3 separate variables, but I would prefer it is in arrays. Here is the code that supposed to do this. It works with predefined string (eg. 00:00:00), but with reading serial it says that the initializer fails to determine size of "input".
Thank you in advance for helpful suggestions.
Here is the code:
void setup() {
  FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);
  Serial.begin(9600);
  while(!Serial.available()){} //wait until Serial data received
  String vst = Serial.readString();
  char buf[vst.length()+1];
  vst.toCharArray(buf, vst.length());
  char input[] = vst;
  char delic[] = ":";
  char* sub = strtok(input, delic);
  while(sub != NULL){
   Serial.println(ptr);
    sub = strtok(NULL, delic);
  }

}

Instead of vst.toCharArray() (which copies the data) just directly use vst.c_str() which is a char array already. You don't need buf

Your main problem is this:
char buf[vst.length()+1];

You can't initialize an array with the return value of a function.
Instead you would need to use alloca to perform the same function:
char *buf = alloca(vst.length()+1);

However, the way you're doing it is wasteful. You don't need buf at all.  You can directly access and manipulate the internal char buffer inside the string using vst.c_str();.
For convenience you can point buf at it:
char *buf = vst.c_str();

To complete the picture here's a routine that takes the string and gives you three integers. Since we expect a specific format with only 3 sections to it we don't really need a loop.
// Use readStringUntil to avoid the 1 second delay.
String vst = Serial.readStringUntil('\n');
char *buf = vst.c_str();

char *hourString = strtok(buf, ":");
char *minuteString = strtok(NULL, ":");
char *secondString = strtok(NULL, ":");

if (secondString != NULL) { // Will only be true if we have two colons
    int hours = atoi(hourString);
    int minutes = atoi(minuteString);
    int seconds = atoi(secondString);

    Serial.print("It is ");
    Serial.print(minutes);
    Serial.print(" and ");
    Serial.print(seconds);
    Serial.print(" seconds past ");
    Serial.println(hours);
} else {
    Serial.println("Invalid time format");
}


text:
Regarding turning exact 180 degrees using an MPU6050
I want to turn robot exact 180 degrees by using an MPU6050. This is the code I tried. Can anyone help me?
#include <MPU6050_tockn.h>
#include <Wire.h>

#define enA 9
#define in1 4
#define in2 5
#define enB 10
#define in3 6
#define in4 7

MPU6050 mpu6050(Wire);

void setup() {
  Serial.begin(9600);
  Wire.begin();
  mpu6050.begin();
  mpu6050.calcGyroOffsets(true);
  setupmotor();

}

void setupmotor(){
    pinMode(enA, OUTPUT);
  pinMode(enB, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
  pinMode(in3, OUTPUT);
  pinMode(in4, OUTPUT);

}

void loop() {
updatempu();

while(mpu6050.getAngleZ()== 180 || mpu6050.getAngleZ()== -180 ){
       turn();
  }

}

void updatempu(){
    mpu6050.update();
  Serial.print("\tangleZ : ");
  Serial.println(mpu6050.getAngleZ());

}

void turn(){
  Serial.println("turn");
        digitalWrite(in1, LOW);
    digitalWrite(in2, HIGH);
      digitalWrite(in4, LOW);
    digitalWrite(in3, HIGH);
      analogWrite(enA, 100); // Send PWM signal to motor A
  analogWrite(enB, 100);
}

void stp(){
    Serial.println("stop");
        digitalWrite(in1, LOW);
    digitalWrite(in2, LOW);
      digitalWrite(in4, LOW);
    digitalWrite(in3, LOW);

}

do you understand that while(mpu6050.getAngleZ()== 180 || mpu6050.getAngleZ()== -180 ) is true when getAngleZ IS either 180 or -180? perhaps you meant while(mpu6050.getAngleZ()!= 180 && mpu6050.getAngleZ()!= -180 )

when mpu6050.getAglez() = 180 0r -180 then robot should stop. but it is not happening. without stopping ,it is turning

your logic as it stands now is, if getAngleZ() is 180 OR -180, call the function turn - but you want to turn if getAngleZ is NOT 180 AND NOT -180 - is that correct

if(mpu6050.getAngleZ()== 180 || mpu6050.getAngleZ()== -180 ){
stp();
}                                                                else { turn();} it should be like this or not??

maybe, I don't know, seems about right - did you try?

you are asking for help, but you do not say what the problem is. .... the information about what you observe should be in the question above .... please add it

As I understand, you want the robot to position itself automatically at either 180° or -180° and stay there. When an outer force get's applied to the robot - turning it out of the target positions - it should again try to reach the target positions.
The first problem was pointed out in the comments and your own code correction seems ok to tackle that:
if(mpu6050.getAngleZ()== 180 || mpu6050.getAngleZ()== -180 ){
    stp();
} else {
    turn();
}

But I see a second problem: In the real world sensor mostly have some kind of noise imposed on their signal (not necessarily meaning electrical noise). For example if you shake the table, where the robot stands on. Or - more importantly in my opinion - The motor, that you use, might not stop fast enough. The MPU might return a value of 179° or 181° when it should be at 180°, because the motor could stop the robot fast enough (inside the time span it needs to travel 1°). In your current logic, this would trigger another turn command. Since you are only turning in one direction, this can create an instable system, which will turn infinitely.
This kind of problem is often solved by using a feedback loop control (of course in combination with the ability to control/turn into both directions). A good and useful example is a PID control (Proportional, Integral, Differential: This is how the control is mathematically structured), where there are already Arduino libraries for it (like this one). If you want it easier, you can define a range of angles, which are acceptable for your positioning (where it should stop) (for example 175° to 185°). The size of the range, that you need, would depend on the mechanics of your robot and the motor. Note, that this also has drawbacks, but it might be easier for now, depending on what exactly you want to achieve.

As Tom pointed out in his comment, you also get trouble with your first approach, if the method getAngleZ() returns not an integer, but a float, which it indeed does. You can see this in the source code of the used library here. The line
float getAngleZ(){ return angleZ; };

tells us, that the return type of the method is float. The problem with this type is, that it cannot represent every rational value inside it's range. There are gaps between two following float values. The values inside this gap cannot be represented by float. Instead a value nearby will be used (Actually I'm not sure, how this is been done. Probably by going to the next lower value, like with int). This also means, that not every integer is representable by float. Even if the Z angle is exactly 180°, the float value may be something like 179,98. But since 179,98 is not equal too 180 the statement
mpu6050.getAngleZ() == 180

would never become true. Of course the mentioned solutions above apply here too.

I completely agree, and I would also check that getAngleZ() returns an integer, not a float or double.

You are right, I have not thought of this. I will add it to the answer. thx


text:
Powering 24 volt solenoid valve with Arduino uno
Today I received normally closed solenoid valve which I am going to use in automated pot watering system ,
I realised the valve takes 24 dc volt as input and Arduino has maximum of 5volt , using some power booster I can convert it to some extent but I think 24 volt is too much .
So how should power 24volt solenoid valve from Arduino uno?

Howmany power does the solenoid use? Get a 24V power supply, or your 19V laptop power supply may actually do the trick just fine.

Since the solenoid requires higher current than the arduino can provide you can use an alternative power source for the solenoid (maybe a couple of batteries) and switch it with a TIP120 transistor.

Got it here : http://www.instructables.com/id/Use-Arduino-with-TIP120-transistor-to-control-moto/

Yes that was my source when i first implemented it.

Actually I have plan to power over Ethernet if Arduino can handle 24 volt dc I can break part of voltage from same dc input to solenoid valve

Arduino Uno Input Voltage Limit

Input Voltage (limit)  6-20V

Well that's a problem than I would have to invest a little bit more, thanks

You can get a DC-DC (buck) converter, to step down the 24V to 5V.

Doesnt the transistor need a heatsink?

Using XL6009 I can convert 9 volts to 24 volts

You have 2 choices:
1 - Preferably, use a N-channel MOSFET. Best for usage of voltage between 9 and 60, these are great little modules that can control voltage flow.
2 - Use a relay. A little more expensive, but can handle main's voltage.

Why PNP instead of NPN? How do you turn off a PNP with only 5V?

@Gerben, my bad...

An “NPN MOSFET”? You mean an N-channel MOSFET, or an NPN BJT.

@EdgarBonet An N-channel MOSFET. Could an NPN MOSFET also mean NPN BJT? Because I think I was clear enough by putting MOSFET in capitals.

A BJT can be either NPN or PNP. A MOSFET can be either N-channel or P-channel. There is no such thing as an NPN MOSFET.

24V AC or DC?  Relay would be good for either.
Low Rds N-channel logic level MOSFET (IRFL540) would be good for sinking DC current.

The OP said "the valve takes 24 dc volt as input" in his question. I think that means 24VDC. Dat Ha recommended using a N-channel MOSFET back on Nov 15, 2016. Do you think your answer adds any new information that may help the OP or any future visitors to this question?

Dang, I need to remember to look at the dates of the original question! That's the 2rd or 3rd time I've been caught up like that.

Do you think your answer adds any new information that may help the OP or any future visitors to this question?

No, feel free to remove the whole thing.


text:
trying to make wemos d1 code modular causes collect2: error: ld returned 1 exit status exit status 1
#include "connection.h"

void setup() {
  Serial.begin(115200);
  Funcs::Connect conn;
  conn.connectWifi();
}

void loop() {

}

then connection.h file:
// connection.h

namespace Funcs
{
  class Connect
  {
    public:
      void connectWifi();
  };
}

and then connection.cpp
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include "connection.h"
const char* ssid     = "ssid";
const char* password = "password";

namespace Funcs
{

  void connectWifi() {
    // Connect to WiFi network
    Serial.println();
    Serial.println();
    Serial.print("Connecting to ");
    Serial.println(ssid);

    WiFi.begin(ssid, password);

    while (WiFi.status() != WL_CONNECTED) {
      delay(10);
      Serial.print(".");
    }
    Serial.println("");
    Serial.print("WiFi connected with ip ");
    Serial.println(WiFi.localIP());

  }
}

On compiling I get this error:
/Library/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/cores/esp8266/HardwareSerial.h:76:
undefined reference to `Funcs::Connect::connectWifi()'

collect2: error: ld returned 1 exit status
collect2: error: ld returned 1 exit status
exit status 1
Error compiling for board WeMos D1 R1.

But I do not have Funcs::Connect::connectWifi() in my code, it was in old code.

Your connection.cpp is incorrect. Take a look Class code and header files to see how class methods should be defined.

You are calling Funcs::Connect::connectWifi() right here:
conn.connectWifi();

since conn is of type Funcs::Connect
But you defined a function Funcs::connectWifi():
namespace Funcs
{

  void connectWifi() {

where I think you meant to have connectWifi be a member of that Connect class.
namespace Funcs
{

  void Connect::connectWifi() {

That's not the only issue with your code, you also create the instance in setup and let it go out of scope after calling just the one function.  But that's a different kind of error.  It's legal code, just probably doesn't do what you want.


text:
which Arduino UNO ethernet shield supports power over ethernet?
I ordered for this ethernet shield for my UNO as shown on the amazon website listing

I was thinking to add power over ethernet module to take advantage of shield that supports adding POE module.

.
But I received the one below

Does the one I received POE? Without the use of POE module!

No, it's not possible at all with this "MagJack". But you can always use injectors/extractors with 9V or 12V power supply...