text:
ESP8266 sends webpage to client, but html codes appears in browser instead of webpage?
I am using ESP8266 with Arduino MEGA. ESP8266 is powered 3.3v via voltage divider, which is taking 5v from arduino and converting it down to 3.3v with the help of 5K and 10K resistors. AT commands seems to be working OK. I am using SD_card reader and kept my index.html file in SD_card. I am able to make a successful connection and esp also sends the whole index.html file, But the issue is my browser does not shows the page in html format, instead the whole html code appears on the browser. Can anyone help me to sort this issue ?
Herez the whole code;
    #include <SPI.h>
    #include <SD.h>

     #define SSID "Maxcotec"   // change this to match your WiFi SSID
     #define PASS "qamar0334" // change this to match your WiFi password
     #define PORT "80"      // using port 80 by default
    #define DEBUG true
     #define BUFFER_SIZE 1024
     char buffer[BUFFER_SIZE];
    //SoftwareSerial Serial2(2,3); // make RX Arduino line is pin 2, make TX Arduino line is pin 3.
                                 // This means that you need to connect the TX line from the esp to the Arduino's pin 2
                                 // and the RX line from the esp to the Arduino's pin 3
    File webFile, CSS_file;
    String webpage;
     // By default we are looking for OK\r\n
     char OKrn[] = "OK\r\n";
     byte wait_for_esp_response(int timeout, char* term=OKrn) {
      unsigned long t=millis();
      bool found=false;
      int i=0;
      int len=strlen(term);
      // wait for at most timeout milliseconds
      // or if OK\r\n is found
      while(millis()<t+timeout) {
       if(Serial2.available()) {
        buffer[i++]=Serial2.read();
        if(i>=len) {
         if(strncmp(buffer+i-len, term, len)==0) {
          found=true;
          break;
         }
        }
       }
      }
      buffer[i]=0;
      Serial.print(buffer);
      return found;
     }

    void setup()
    {
      Serial.begin(9600);
      Serial2.begin(115200); // your esp's baud rate might be different

       setupWiFi();
      // print device IP address
      Serial.print("device ip addr:");
      //esp.println("AT+CIFSR");

      //sendData("AT+RST\r\n",2000,DEBUG); // reset module
      //sendData("AT+CWMODE=2\r\n",1000,DEBUG); // configure as access point
      sendData("AT+CIFSR\r",1000,DEBUG); // get ip address
      sendData("AT+CIPMUX=1\r",1000,DEBUG); // configure for multiple connections
      sendData("AT+CIPSERVER=1,80\r",1000,DEBUG); // turn on server on port 80

        // initialize SD card
        Serial.println("Initializing SD card...");
        if (!SD.begin(53)) {
            Serial.println("ERROR - SD card initialization failed!");
            return;    // init failed
        }
        Serial.println("SUCCESS - SD card initialized.");
        // check for index.htm file
        if (!SD.exists("index.htm")) {
            Serial.println("ERROR - Can't find index.htm file!");
            return;  // can't find index file
        }
        Serial.println("SUCCESS - Found index.htm file.");

             // send web page
        webFile = SD.open("index.htm");        // open web page file
        if (webFile) {
            while(webFile.available()> 0) {
                //client.write(webFile.read()); // send web page to client
               char ch = webFile.read(); // Read a character
               webpage += ch; // Add it
            }
            webFile.close();
        }
         Serial.print("file contents>>>");
         //Serial.println(webpage);
         //delay(20000);
    }

    void loop()
    {
      if(Serial2.available()) // check if the esp is sending a message
      {
        /*
        while(Serial2.available())
        {
          // The esp has data so display its output to the serial window
          char c = Serial2.read(); // read the next character.
          Serial.write(c);
        } */

        if(Serial2.find("+IPD,"))
        {
         delay(1000);

         int connectionId = Serial2.read()-48; // subtract 48 because the read() function returns
                                               // the ASCII decimal value and 0 (the first decimal number) starts at 48

         //String webpage = "
Hello

World!
<button id=\"11\">Toggle Pin 11</button>";//<button>LED1</button>";

         //Serial.print("file contents>>>");
         //Serial.println(webpage);
         //delay(20000);
         String cipSend = "AT+CIPSEND=";
         cipSend += connectionId;
         cipSend += ",";
         cipSend +=webpage.length();
         cipSend +="\r\n";

         sendData(cipSend,1000,DEBUG);
         sendData(webpage,1000,DEBUG);

         //webpage="<button>LED2</button>";

    //     cipSend = "AT+CIPSEND=";
    //     cipSend += connectionId;
    //     cipSend += ",";
    //     cipSend +=webpage.length();
    //     cipSend +="\r\n";
    //
    //     sendData(cipSend,1000,DEBUG);
    //     sendData(webpage,1000,DEBUG);

         String closeCommand = "AT+CIPCLOSE=";
         closeCommand+=connectionId; // append connection id
         closeCommand+="\r\n";

         sendData(closeCommand,3000,DEBUG);
        }
      }
    }

    void setupWiFi() {
      // try empty AT command
      Serial2.println("AT");
      wait_for_esp_response(2000);
      // set mode 1 (client)
      Serial2.println("AT+CWMODE=1");
      wait_for_esp_response(2000);
      // reset WiFi module
     /*
      esp.print("AT+RST\r\n");
      wait_for_esp_response(3000);
      delay(5000);
      */
      // join AP
      Serial2.print("AT+CWJAP=\"");
      Serial2.print("xxxxxxx");
      Serial2.print("\",\"");
      Serial2.print("xxxxxxx");
      Serial2.println("\"");
      // this may take a while, so wait for 5 seconds
      wait_for_esp_response(5000);
      Serial2.println("AT+CIPSTO=30");
      wait_for_esp_response(1000);
      // start server
      Serial2.println("AT+CIPMUX=1");
      wait_for_esp_response(1000);
      Serial2.print("AT+CIPSERVER=1,"); // turn on TCP service
      Serial2.println(PORT);
      wait_for_esp_response(1000);
     }

    String sendData(String command, const int timeout, boolean debug)
    {
        String response = "";

        Serial2.print(command); // send the read character to the Serial2

        long int time = millis();

        while( (time+timeout) > millis())
        {
          while(Serial2.available())
          {

            // The esp has data so display its output to the serial window
            char c = Serial2.read(); // read the next character.
            response+=c;
          }
        }

        if(debug)
        {
          Serial.print(response);
        }

        return response;
    }

And this is what I am getting in web browser;
I am using Opera browser but I have tried in Chrome and firefox aswell. when I open this index.html page in my laptop with the same browser, it opens perfectly.

Did you tell the browser that you're sending it HTML?

Looks like you're lacking the whole of the header portion to me...

I am following link this tutorials. Its seems like he is also not sending the header portion.

@AnumSheraz try using the developer tools to get the headers. To do this for instance in Chrome press F12, go to the network tab, load the page and look at the files being retrieved. Find the index.html file, right click on it and press "Copy response headers"; then post them in your question: this way we'll be able to see what are the missing ones

Also, please get a proper 3.3V regulator.

You need to send the header Content-Type: text/html before the html.

I'm trying to use the program and now I have achieved good results. Now I am trying to send a txt file to a client that connects to the webserver.
When the client sends a request to: IP\data.txt, it should directly receive the txt file to download.
Have you any advice for me? Thank you, Riccardo

Why are you using the 5 V and not the 3.v V from Arduino?  Using a divider is not a good idea. Yout voltage will not stay constant and you are liminting the current with voiltage deviding.

It looks like you did not send the HTTP headers. Before sending any of the HTML content send following lines:
"HTTP/1.1 200 OK\r\n"
"Content-Type: text/html\r\n\r\n"

Make sure you send all the \r\n !

See the text from "'HTTP/1.1 200 OK'" until "'DOCTYPE html'" in the following couple of links which say the same, and you might like to read the rest of those pages:

https://www.arduino.cc/en/Tutorial/WebServer
http://www.allaboutcircuits.com/projects/using-an-arduino-as-a-web-server

this is an html question, not an arduino question. What is it doing here? Sending html from an esp8266 is no different than sending it from any other device.

Before asking the question, I didn't knew that its could be html problem, I thought it might the voltage issue (as many ppl have this issue with there esp8266).

Slightly off-topic, as this is not the source of your problem, but as jBot42 says, you need a proper regulator. When you use a voltage divider, your load (the ESP8266) is connected in parallel with one of the resistors (the 10K one) and effectively changes the output voltage of the regulator. As the consumption of power in the ESP8266 changes (e.g. when the wifi circuit transfers data), the voltage will also change.
At the very least you should place an electrolytic capacitor in parallel with the 10K resistor, but even this is not a good solution.

Make sure you save the SD card file as index.htm.
That is what you are calling for in your code. Your description has a reference to index.html. You will get the result you see.

Whilst you are correct, in that there is a mismatch between the source code calling a .htm file and the OP saying that the file on the SD card is a .html file, this is most likely a typo, in the question, on the part of the OP. The Arduino is clearly accessing the file correctly. So, unfortunately, this will not fix the issue that the OP is experiencing. The correct answer has already been provided, which is that the HTTP headers were missing.


text:
Help with Arduino Due and APA102 LED strip Vs Matrix
I am in a fix since last one week regarding this:
As mentioned in a previous question (asked here only), I have been working to develop a APA102 LED based display. Now for this I have an Arduino Due. The display area is non rectangular however there is a central rectangular region measuring 63 cm X 36 cm. I have managed to do everything from the software side however stuck with the hardware (first time, its mostly vice-versa!!). The confusion is this, 2 options that I have at my disposal:

Go for the APA102 144 LEDs/meter (high density required) strip and then use them to make the display. On doing a small approximate calculation, I found I would have close to 2500-2600 LEDs. My first question is that:
a. Can Arduino Due handle this? I also need to display static images (bitmaps) (forget animations) and perform fading. Would the refreshing be fast enough? I have some values from APA102 datasheet and Arduino Due but cannot make head or tail of it...I do not know how to find out time taken, data rate etc.
b. The other problem I have with this is that for the bitmap to be "perfect", the pixel pitch needs to be same. In vertical direction, this is not possible without cutting the strip along the length to reduce its width. This a damn tedious and useless job. This act along with the soldering and everything involved makes me go for option 2 (below).
I go for eight 8*32 APA102 flexible displays and arrange them in two columns so that to display the bitmap, I split the bitmap data into two 32*32 matrices and then pass them separately. this is because I cannot find the relation between the bitmap pixel index and the actual display index. The arrangement is like that. Here Also, my question is: Can Arduino Due deal with this a good refresh rate without flickering etc. (POV display req.) The problem with this option is that I can cover only the rectangular region of the area and I am left with some area which makes me feel guilty to see it not lighted whereas with strip I can cover the whole area and only display bitmaps for the rectangular area. Both options have serpentine arrangement. This option also has cleaner and easy construction.

Both options seem plausible to me but I really cannot decide which one is better. Confused! Please, any help, idea, guidance, advice...anything would be great. I would be ordering this stuff from aliexpress etc. and thus a wrong decision would be taxing on my pocket.
I would be glad to provide any other info if required.
Thanks!

source: Stack Exchange

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

sort: votes


text:
Producing a sine wave with the DAC?
Its being a few days i am trying to achieve something that I dont really know if possible.
Using the Samd21 chip(Arduino Zero), I am using a timer and a DAC to produce a sine wave.
The required frequencies are 100Khz to 3Mhz. I know its sounds too much, but according to my calculations its possible- I would like to know if I am wrong with my software approach.
Pseudo is this :
1.I create a look-up table of a sine wave = array of a sine samples that holds N samples
2.I use a timer with a pre scale of 1, where the clock speed is 48Mhz
3.Each timer tick I produce from the DAC 1 sample from the sine wave
4.To change frequencies I am changing the timer top counter value.
If we try to speak about the max frequency, according to Nyquist , a 3MHz sine must be sampled with at least 6MHz sample rate, and my sine array has 15 samples, means 45Mhz sampling rate.(=good)
Then the sine frequency is :
sineF= TimerF*sineSamples = TimerF*15

Than means I need a timer frequency of :
TimerF=15*sineF = 15*3Mhz=45MHz

So, both are good, the timer max f can be 45Mhz, and the sampling rate is good according to Nyquist.
The only concern here, is if the DAC can do that(speed), and if changing the timer frequency fast enough (even every period) is acceptable.
Is this whole software approach true ?
If its not, producing a square wave probably possible,since it requires much less speed, but then, can you turn it into a nice clean sin wave with filters?
Thanks.

First, I have to say I am not familiar with the Zero hardware, so I am
answering in quite general terms. Hopefully you will also get some
answers with hardware-specific information. That being said, here are my
first thoughts:

Your approach seems reasonable to me, but you are too optimistic
regarding the achievable sampling rate.
DACs are usually fast. It's unlikely that the DAC will limit the
frequency you can achieve.
You cannot achieve a sampling frequency of 45 MHz in software
with a CPU running at 48 MHz: your code to output a sample would
have to run in less than 1.07 CPU cycles.
You may achieve a higher sampling rate with an array of
16 samples rather than 15, as wrapping the array index modulo 16
can be optimized by the compiler into a bitwise AND, which is likely to
be faster than computing index%15.
Fastest would probably be to use a busy loop with constant execution
time and interrupts turned off (I know how to do that on AVR, but not on
ARM). Problem is: the program cannot do anything else than outputting
samples.

Thanks a lot, I think that DAC's are really slowly, I could see that other DAC's of ARM's such as the Due, are capable of max 1MHz rate. And regarding to your assumption on the sampling frequency of 48MHz, you can definitely do that, a pre scale 1 for a timer provide it with a processor clock speed, and if you count to 1( timer counter 1 cycle) you do get a 48MHz, this is how it works with any frequency , so I am not sure you assumptions are correct.

The problem is not triggering the timer fast enough, it's having any time between triggerings of the timer to actually retrieve the sample from the LUT and send it to the DAC. There just isn't any time.

Ok, I have checked it out, DAC is too slow! its 350ksps, that means 350Khz, so it IS a limit. Regarding the timer you are right. So I can just put it on 16Mhz, or something similar(?)

You have to allow enough time for the instructions you are executing to run. That means, effectively, one clock cycle for each and every assembly (NOT C) instruction. That could be hundreds of clock cycles - maybe thousands - depending on just what you are doing in your interrupt routine.  I am not familiar with that chip, but if it has DMA that would be a more efficient way of doing it.

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


text:
memory game arduino
so I have a project which is to make a simple memory game using Arduino where the LEDs have to blink in a certain pattern and the player has to imitate the same pattern
but unfortunately I'm having so much trouble with the code
I want to make an if statement to check whether the button was pressed or not if it was it continues to check on the second button and if it wasn't the red led (which means wrong) has to  turn on
this is how i started:
enter code here

const int button1 = 2;          // 1st button controls Blue LED
const int button2 = 3;          // 2nd button controls Yellow LED
const int button3 = 4;          // 3rd button controls Green LED
const int button4 = 5;          // 4th button controls Red LED
const int led1 = 7;             // Blue LED
const int led2 = 8;             // Yellow LED
const int led3 = 9;             // Green LED
const int led4 = 10;            // Red LED
const int correctLED = 6;
const int wrongLED = 11;
int val = 0;

// Variables
int buttonState[] = {0,0,0,0};         // current state of the button
int lastButtonState[] = {0,0,0,0};     // previous state of the button
int buttonPushCounter[] = {0,0,0,0};

void setup() {
  // initialize inputs :
  randomSeed(analogRead(0));
  pinMode(button1, INPUT);
  pinMode(button2, INPUT);
  pinMode(button3, INPUT);
  pinMode(button4, INPUT);

  // initialize outputs:
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  pinMode(led4, OUTPUT);
  // initialize serial communication for debugging:
  Serial.begin(9600);
        }
  }

 void loop() {
       digitalWrite(7, HIGH);
       digitalWrite(8, HIGH);
       digitalWrite(9, HIGH);
       digitalWrite(10, HIGH);
       digitalWrite(7, LOW);
       digitalWrite(8, LOW);
       digitalWrite(9, LOW);
       digitalWrite(10, LOW);

       digitalWrite(7, HIGH);
       delay(500);
       digitalWrite(7,LOW);
       delay(500);
       digitalWrite(8, HIGH);
       delay(500);
       digitalWrite(8,LOW);
       delay(500);
       digitalWrite(9, HIGH);
       delay(500);
       digitalWrite(9,LOW);
       delay(500);
       digitalWrite(10, HIGH);
       delay(500);
       digitalWrite(10,LOW);
       delay(500);

       val = digitalRead(2);  // read input value
       if (val == HIGH) {         // check if the input is HIGH            (button released)
       digitalWrite(wrongLED, LOW);  // turn LED OFF
       } else {
       digitalWrite(wrongLED, HIGH);  // turn LED ON
       }
       val = digitalRead(3);  // read input value
       if (val == HIGH) {         // check if the input is HIGH           (button released)
       digitalWrite(wrongLED, LOW);  // turn LED OFF
       } else {
        digitalWrite(wrongLED, HIGH);  // turn LED ON
       }
       val = digitalRead(4);  // read input value
         if (val == HIGH) {         // check if the input is HIGH (button released)
       digitalWrite(wrongLED, LOW);  // turn LED OFF
       } else {
       digitalWrite(wrongLED, HIGH);  // turn LED ON
       }
       val = digitalRead(5);  // read input value
       if (val == HIGH) {         // check if the input is HIGH (button released)
       digitalWrite(wrongLED, LOW);  // turn LED OFF
       } else {
         digitalWrite(wrongLED, HIGH);  // turn LED ON
       }
       digitalWrite(correctLED, HIGH);

       }
       }

Do yourself a favour and learn how to indent your code properly.

As for your problem: think passwords.

You can automatically format your code in the Arduino IDE by going into the "Tools" menu and selecting "Auto Format."

You have too many closing braces.

Downvoted because you didn't say what problem you're having.

For this kind of thing you don't really want to be worrying about "is this button and then this button pressed" etc. That thinking is very much "of the moment" in that it is all about what is happening now - not what has gone on in the past.
You need to be thinking about the sequence of button presses that you have seen so far - not what is happening right now.
Say you have three buttons.  Let's assign a number to each of them - say they are buttons 1, 2 and 3.
And you have 3 LEDs - let's call them A, B and C.
So you light and extinguish the LEDs in a specific order, say BAC, and you expect the buttons to be pressed in the same order - 213.
You can't be checking all the time for "If 2 is pressed then 1 is pressed then 3 is pressed" because, basically, where are you in that sequence at any one instance in time?  Instead you need to go:  "A button has been pressed. I'll store that fact." And then: "Have three buttons been pressed? Yes. Do their numbers match?"
Basically like a PIN code for your bank card, or a password for your computer. It's not what you are pressing now, it's what it remembers you pressing in the past.
And the simplest way of doing that is to literally allocate numbers to the buttons. When a button is pressed you assign a number representing that button to a variable. Then append that number to the list of numbers you have seen recently. When that list is the right length you compare it. Just like entering a password.
You can even compare what you have so far with a portion of what you expect to catch incorrect presses early.
So say you have an expected value of "213" stored in a string. You also have an empty string. When you press a button you append that number to the string - so say you press "212" you could then append and compare the string like this:
Button  Input  Expected
2       2      2         Correct
1       21     21        Correct
2       212    213       Incorrect - erase input content
2       2      2         Correct
1       21     21        Correct
3       213    213       Correct - next round please.

Format and extra braces aside there are other issues with your code, too many to fit in a comment.

You have used led1, led2 etc in the setup routine and the resorted to numbers in the loop function.
At the start of loop() you turn the leds high then low, you won't see this because the processor is faster than your eye, you need a delay statement after the last high and last low.
You can make you code more elegant by writing a function that takes the pin as a parameter and toggles the led high then low and call this rather than repeating 4 lines of code.

void togglePin(int pinNumber, int interval)
{
   digitalWrite(pin, HIGH);
   delay(interval);
   digitalWrite(pin, LOW);
   delay(interval);
}

When it comes to reading values you have blocks of repeated code, again these could be a separate function, which will make your code easier to read and understand.

When you have done that you might want to so a bit of research on 'switch debouncing' because I'm guessing you might have issues with that too.

Your code as written will have both the wrongLED and correctLED on. It will also continuously loop showing the sequence.
Showing the Sequence
To show the sequence once at the start, put it in the setup function.
Read more about the setup function here: http://www.arduino.cc/en/Reference/Setup
Detecting the Button Presses
You want to detect each press of the buttons. For this you will need edge detection code. There is an Arduino example built into the IDE and information describing the function here: http://www.arduino.cc/en/Tutorial/StateChangeDetection
To add to the Arduino explanation, you can either detect the rising edge (ie. the transition from a LOW to a HIGH) or the falling edge (ie. the transition from a HIGH to a LOW). I personally prefer the following code to detect a rising edge:
if ( (lastButtonState == LOW) && (buttonState == HIGH) )

where buttonState would be assigned by a digitalRead and lastButtonState would record the value of buttonState at the end of the loop function (ie. just before it reads in the button states again).
Using your global arrays you could write:
buttonState[0] = digitalRead(button1);
buttonState[1] = digitalRead(button2);
buttonState[2] = digitalRead(button3);
buttonState[3] = digitalRead(button4);

if ( (lastButtonState[i] == LOW) && (buttonState[i] == HIGH) )

where i is a number between 0 and 3. You could use a for loop to cycle through the 4 available buttons.
Recording the Button Presses
The StateChangeDetection example above counts the number of button presses. Instead, you want to record 4 button presses. To do this create a global variable called pressNumber. Create it with the initial value of 0.
Create an integer array of 4 elements called `userSequence'.
Every time the if statement detects a rising edge, store the button number in the userSequence' at positionpressNumberand then increment thepressNumber`.
When pressNumber reaches 4, the user has entered his/her guess.
Evaluating the Guess
This only occurs once the user has entered the guess. Start off by creating a boolean variable and assign it TRUE. Cycle through the elements in the userSequence array and compare the users guess to the correct answer. If the user gets one wrong set the boolean variable to false. At the end, turn on the red LED or green LED depending on the state of the boolean variable (ie. if it is true turn on the green LED, otherwise turn on the red).
Final Notes

As Matt suggests, try refactoring portions of code into functions. It makes the code more readable and reduces the complexity of the code.
You can use the variables for the pin numbers of the buttons and LEDs in the digitalWrite and digitalRead functions. Eg:
digitalRead(button1);
digitalWrite(led1);

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


text:
Problem uploading to Arduino Uno
The problem occurred while testing a ping program with the ethercard examples from github.
Now no program will upload. It will say uploading.... and gets stuck there. The error message below appears:
Arduino: 1.6.7 (Windows 7), Board: "Arduino/Genuino Uno"

WARNING: Category '' in library UIPEthernet is not valid. Setting to 'Uncategorized'

Sketch uses 1,030 bytes (3%) of program storage space. Maximum is 32,256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xdf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xdf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xdf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xdf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xdf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xdf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xdf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xdf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xdf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xdf
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

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

ensure that it is connected to the correct port (worked with me)

Other thing to try, if you are using a different board try plugging in a genuine Uno or true clone, setting the board and port, uploading a sketch, then start over with your board. That has helped me. Seems that some boards don't reset the usb properly after a problem. ...or maybe it's just voodoo.

I'm having the same issue on my Macbook Pro. It happens randomly. The only solution i found is disconnecting the USB cable from the PC wait for a few mins and reconnect it again (possibly using another USB port).
It worked for me!

When you get this error, they have several things to check :

Is my board reconised by Windows ?
Is my board model is the right one ?
Is the serial port is the right one ?
Is my cable damaged ?

Generally the upload problem is easy to fix.
If your board is a custom one

bootload problem
crystal problem.
reset not triggered properly ? (try to push it when arduino ide say "uploading sketch")

Disconnect everything to Arduino, Plug in your Arduino to your computer - check for the Serial port, Check for your Arduino Model, select programmer as USBasp, open up BLink sketch from Examples and HIT upload.
if you don't see your Arduino in Tools>Port then it should be the problem of USB cable, Computer USB port or "DRIVERS"

No, do not select USBasp unless that is what you are using - the asker clearly isn't.

Remove the ethercard, return to the basic board.
Disconnect the Arduino from the host.
Reboot the host computer.
Reconnect the Arduino.
Upload the Blink example.

This should sort things out, well it did when it happened to me.

When I started reading that list I thought it was going to end up like this: http://www.snopes.com/humor/business/wordperfect.asp ;)

If you have the Arduino Uno with removable chip then try to remove the IC. Then plug it again and check the power on the IC with a multimeter on pin 7 (+ positive) and pin 8 (- negative). If you are getting 5V there then you need to try to upload a simple blink sketch. If you are not getting the appropriate voltage then you can try to use a different wire to upload the sketch.

This is unlikely to help.  There are better places to measure power, such as the 5v pin on the shield connector.


text:
How to read data using Arduino SPI
in the datasheet, it's stated that I should apply 32 serial clocks to get the 32 bits of data. How can I program this is Arduino?

I suggest you to open the examples of the SPI library and check them. Anyway, the code should be byte result[4]; for (i = 0; i < 4; i++) result[i] = SPI.transfer(0x00); and you will find in result the 32 bits you need

I already did that. but the energy chip I am using is STPM10 and it suggests that I should use simplex synchronous SPI where the MOSI is not connected. there is just a timing diagram to switch from reading bytes and writing bytes. When I used SPI.transfer(), The data is not stable and I think not reliable

How do you say it is not reliable? The peripheral is full duplex, and according to the way it works the only way to receive data is by sending dummy data. If MOSI is not connected, well, it doesn't matter; note however that you can't use the MOSI pin for other tasks. By the way, did you remember to correctly set the slave select pin of the other peripheral? Did you use the SS pin on the arduino board or another one?

You call SPI.transfer() four times, each time saving the returned value to a variable after proper bit shifting.
uint32_t val;
val = SPI.transfer(0xff);  //0xff is a dummy
val |= (uint32_t)SPI.transfer(0xff) << 8;
val |= (uint32_t)SPI.transfer(0xff) << 16;
val |= (uint32_t)SPI.transfer(0xff) << 24;

I assume the least significant byte is received first. Make sure the SPI mode is the right one, as indicated in your datasheet.
If the slave can't handle being deasserted between bytes (which is what SPI.transfer() will do at the end of the transaction), then you can either try st2000's hardware SPI approach or use bitbanged SPI with shiftIn().

Not sure this will work.  We really need to know how the SPI slave works before we can assume how it will react.  Also, if the Chip Select line is asserted and de-asserted with each 8 bit SPI transaction, how well is the SPI slave designed?  That is, such a SPI slave could easily get out of sync with the SPI master.  Specifically, how are you assured which 8 bit byte you are actually reading?

@st2000 The OP saw fit to not give enough details; nothing but assumptions can be made till that changes.

All the examples I've seen use SPI,transfer(0) to read data rather than SPI.transfer(0xff). They also use SPI.transfer for writing data, too. I still haven't figured out what SPI does with the 0 or 0xff when you are actually reading data. Is this sent to the slave?

@S.Imp They're dummy bytes. You can send whatever you want to send, the device at the other end will still discard them, if it even pays the data any mind. SPI.transfer() is always used partly because of the intrinsic full-duplex nature of SPI and (as a result of the first factor) then partly because of the way most MCUs implement their SPI peripherals. Once the clock starts running, there is always "data" on the MOSI and MISO lines, it's just up to each participant on the bus to read it or not, deciding based on whatever predefined higher-layer protocol if the "data" is meaningful or not.

It wouldn't be totally incorrect to say you can't truly read without writing on an SPI bus and vice versa as well. So it makes sense to simply design a peripheral that takes a byte in one register and, 8 cycles later, returns a byte in another (or even the same) register, just to generalize usecases. Then it's up to the user's application to decide if they're only interested in the byte that was written out in the first place (TX) or the one that was read back (RX) or both (TX and RX). Also, hence the ambiguous name transfer() since it serves both reading and writing roles.

Sparkfun has a good explaination of what SPI is:
https://learn.sparkfun.com/tutorials/serial-peripheral-interface-spi
The Arduino IDE has a SPI library that comes with the IDE.
http://www.arduino.cc/en/Reference/SPI
The library comes with two examples:
Using SPI to read a Barometric Pressure Sensor
Controlling a Digital Potentiometer Using SPI

Objective is to read 32 bits using the (unknown) device's SPI port.
If the device will tolerate the SPI Chip Select line activity (going from inactive to active to inactive for each 8 bit byte read) you should be able to get the desired 32 bits of data by performing 4 consecutive 8 bit SPI reads.
However, if the device will not tolerate the above SPI Chip Select line activity (that is, if the device requires the SPI Chip Select to be active for the entire 32 bit SPI transaction), you can not separate the 32 bit transaction into 4 individual 8 bit SPI transactions with out controlling the SPI Chip Select line.  The following code example illustrates how this is done:
void loop(){
//transfer 0x0F to the device on pin 10, keep the chip selected
SPI.transfer(10, 0xF0, SPI_CONTINUE);
//transfer 0x00 to the device on pin 10, keep the chip selected
SPI.transfer(10, 0×00, SPI_CONTINUE);
//transfer 0x00 to the device on pin 10, store byte received in response1, keep the chip selected
byte response1 = SPI.transfer(10, 0×00, SPI_CONTINUE);
//transfer 0x00 to the device on pin 10, store byte received in response2, deselect the chip
byte response2 = SPI.transfer(10, 0×00);
}

The above example comes from the Arduino SPI library web page and is a 16 bit (not 32 bit) transfer.  To code up a 32 bit transfer, continue to call the SPI.transfer method using the SPI_CONTINUE parameter.
added later...
It appears people are discouraging use of the DueExtendedSPI methods. And SPISettings and SPI.beginTransaction() are to be used? If so this page show example code where the code is explicitly controlling the SPI Chip Select line (look for slaveAPin & slaveBPin).  Note how the code is reading 24 bits from slave A and writing 8 bits to slave B. To read 32 instead of 24 bits, we need to alter a segment of the code (along with a few other supporting changes) in this fashion:
...
  SPI.beginTransaction(settingsA);
  digitalWrite (slaveAPin, LOW);
  // reading only, so data sent does not matter
  val0 = SPI.transfer(0);
  val1 = SPI.transfer(0);
  val2 = SPI.transfer(0);
  val3 = SPI.transfer(0);
  digitalWrite (slaveAPin, HIGH);
  SPI.endTransaction();
...

We really need to see the specifications of the slave SPI device to compose a more specific answer.

I use STPM10 evaluation board. The connection is a simplex synchronous SPI, and the MOSI of the Arduino is not connected to anything. There is a timing diagram to switch from read only and write only. My problems is to how to read the data from the registers of the chip. I used SPI.transfer but I don't think the data is reliable.

The STPM10 timing diagram found on page 11 of it's spec does not look like a standard SPI transaction. I am inclined to say you can not use the Arduino SPI library. Instead, you may need to bit-bang this out totally in software. For instance, I do not believe there is a "SYN" line in the standard SPI bus. And I don't believe the Chip Select line should go high before the end of the SPI transaction.


text:
mqtt library which support softwareSerial on arduino uno with ESP8266
I am using ESP8266 and Arduino with SoftwareSerial. My requirement is to use MQTT protocol with it. So I am using an MQTT library named pubSubClient but the problem is it doesn't support SoftwareSerial. Could anyone tell me how can I use MQTT protocol with it?
#include
#include
SoftwareSerial esp(2, 3); // RX, TX
PubSubClient client(esp);

The error I get is: no matching function for call to 'PubSubClient::PubSubClient(SoftwareSerial&)

Are you using http://pubsubclient.knolleary.net/

Could you please edit your question with the following information:

Why can't you use softwareSerial? What error do you get?
Why cant you use the main UART (serial) port?
What daughter board are you using for the ethernet?

You are asking the wrong question. PubSubClient has nothing at all to do with serial in any form whatsoever. It interfaces with the standard Arduino Client class. What you should be looking for (and maybe asking about) is an ESP8266 library that supports SoftwareSerial and presents the standard Arduino Client interface.

#include
#include
SoftwareSerial esp(2, 3);// RX, TX
PubSubClient client(esp);
Error is:no matching function for call to 'PubSubClient::PubSubClient(SoftwareSerial&)'

As @Majenko says, you need an Arduino PubSubClient that supports SoftwareSerial - you are trying to pass in a SoftwareSerial object which is not a PubSubClient. A brief google failed to find any SoftwareSerial clients but there is a ESP8266 PubSubClient here : https://github.com/knolleary/pubsubclient

In order to use the ESP8266 WiFi module with pubSubCient, you need a library that interfaces with the module with the usual AT commands, while presenting an Arduino Client interface on the surface. A while back, I found this library after a great deal of searching. It supports SoftwareSerial as well as HardwareSerial objects. Its ESP8266 interface provides the standard Client methods of write(), read(), connected(), etc. There are some issues, of course, but its the best I've found so far. You can pass the created Client object to the pubSubClient constructor and you're good to go.

Not sure what you're trying to do - but thought I would offer this since I just spend some time on getting my esp8266 to act as a wifi shield for my arduino.  Basically I wanted to subscribe to an mqtt channel and send the payload to my arduino.  So the esp8266 connected to a broker, upon reading a message, it would simply write it via serial to the arduino (I used software serial on the arduino side so I could use the standard serial for debugging).  If it helps, check out http://mganis.blogspot.com for the details
--Matt


text:
Can I use Visual Studio instead of Arduino IDE?
I think that Visual Studio is a great product! I find the Arduino IDE is limited in its features. For example the Arduino IDE does not have:

Code prediction
Error highlighting
Previews of #define values
Peek at code definition
Jump to code definition
and many more...

Since the Arduino ino & pde file types are basically C++, Can I use the Visual Studio IDE instead of Arduino IDE?
To be considered as a replacement, Visual Studio must be able to:

Save & open ino & pde files.
Compile my code.
Download my code.
Use existing/custom libraries from the Arduino IDE.
Detect and display an Arduino project.

I would consider these features as a bonus:

Arduino board selection.
Debugging

Variable watch window
Breakpoints
Step through code

Simulation
Open the Arduino Examples
Automatic board detection
Serial Monitor

This question is similar but different to http://arduino.stackexchange.com/questions/4354
I am after all options available, using any method.

Atmel Studio deserves mention here.  It's based on the Visual Studio shell, has top debugging support if using something like ATMEL-ICE and is the official way to program Atmel chips.
Downside?  It's clunky with Arduino API.

I use Eclipse and Sublime Text for editing Arduino code, and I build in the Arduino IDE with it set to "external editor" mode, or using the Arduino Command Line tools. Eclipse has a fantastic indexer and makes understanding the Arduino core much easier. I've written a detailed PDF about using and setting up Eclipse for professional software development here: https://github.com/ElectricRCAircraftGuy/eRCaGuy_dotfiles/blob/master/eclipse/Eclipse%20setup%20instructions%20on%20a%20new%20Linux%20(or%20other%20OS)%20computer.pdf.

I only use Visual Studio for Arduino programming.
Arduino Plugin for Visual Studio

This really ought to be the accepted answer.  VisualGDB would be your go-to for "real" debugging, but unlikely it works with base Arduino Uno.

If it wasn't when before, the linked plugin is a paid product.

Atmel Studio 7 which is built with Visual Studio. Google "Atmel Studio 7" or click here. It has everything you want and it's released by the company that makes the atmega328 your Arduino is built on.

The link location has changed to: https://www.microchip.com/mplab/avr-support/atmel-studio-7.

Note, this answer is not technically for the full edition of Visual Studio, rather Visual Studio Code.
Microsoft has released an Arduino extension for VS Code that can do most (all?) of the required items in the OP's list.
Added this answer as a free alternative to the accepted answer.

It's not exactly what you are asking, but maybe you would be willing to consider a solution based on Eclipse?
Eclipse has the advantage of being cross platform, so you can have the same experience no matter what your OS might be.
Although, for the sake of completeness, almost all you mentioned can be done even with vim, if adequately configured. But I wouldn't recommend it as first choice, if you have never used it before.

I use Eclipse and Visual Studio on an almost daily basis for my job. Although there are a few nice things I like about Eclipse, and even CodeBlocks, Visual Studio is by far a more polished product.

Different strokes ... I'm happy with vim :-)
About debugging, you will need something more than an IDE.
You need an ICE or equivalent. I have the AVR dragon (http://www.atmel.com/tools/AVRDRAGON.aspx) and it works nicely with ddd + gdb, but it can be made to work also with eclipse, iirc. If you want a windows based solution, I suggest you to check the Atmel site. Most likely they do support primarily windows and you can start from there, to pick the debugger, based on what is available/recommended.


text:
upcoming voltage from a button
i use this simple code for arduino :
const int buttonPin = 2;
const int ledPin =  13;

int buttonState = 0;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT);
  Serial.begin ( 9600 ) ;
}

void loop() {
  buttonState = digitalRead(buttonPin);
  if (buttonState == HIGH) {
    digitalWrite(ledPin, HIGH);
    Serial.println ( buttonState ) ;
  } else {
    digitalWrite(ledPin, LOW);
    Serial.println ( buttonState ) ;
  }
}

it's so basic program, I've seen some people work with Resistors when they use buttons, so i wanted to know why, i plugged in one side of the button to the pin 2 , no matter if i plugged in the other side of the button or no to the 5 volte source, the arduino started giving me some ones and zeroes therefore the blinking of the led, so basically that means there's a certain voltage comming from the button to the pin 2, I wonder why and what's the reason for this ?

I see you are new to Arduino, so let's start:
1) if you say it works you might be using an circuit like this:

which is not all bad but you might find trouble. I explain:
1. When you set pinMode(pin,INPUT); you tell arduino to enable a high-impedance state on that pin: it's equivalent to 100Mohm resistor in series in front of that pin, good for getting sensor readings, but when you use a switch the state/reading of that pin (HIGH or LOW) is "floating" when the switch is opened which will give unpredictable readings.
That's why you need to use a "pull-down" resistor, which means you pull down the value of that pin when the switch is OPENED by using GND as reference value for LOW so you are sure it goes down when switch is opened. The resistor also serves as protection (10Kohm is recommended) when the switch is CLOSED as it stops the high current flow/drain (!!5V pin connected to GND!!) that arduino can't support without (aka short-circuit).
2. So you end up with something like this:

I would personally put the resistor and the GND wire between the button and the digital pin wire.
I hope I was useful! If you need/want more documentation check those two links out:
https://www.arduino.cc/en/Reference/Constants look into "Defining Digital Pins modes" section
https://www.arduino.cc/en/Tutorial/DigitalReadSerial here you have an practical example.

that was a fully understandable explanation, thanks, i managed to do what you explained but using 2 resistors, the same as you did, and I added a 100 hm between the pin 2 and the switch button, and it worked perfectly

Note that there is another, easier way to do this. If instead of setting your pin to INPUT, you set it to INPUT_PULLUP then internally the input line is connected through a resistor to +5 volts. Then when nothing is connected to the pin, it reads as HIGH. You connect your input to a switch, and connect the other pin of the switch to ground Now when you press the switch it grounds the input pin, pulling it low. No resistors needed, but it does mean the state of your switch is reversed (HIGH = switch not pressed, LOW = pressed)


text:
It seems as if there is a 220K pull-down resistor on analog pin 0
So I am building a project that uses the analog pins for precise measurements of resistance through a voltage divider and I have been having some seemingly unsolvable problems with nonlinear response to linearly changing resistances when using the A0 pin to measure.
I first realized this was the problem when I had a voltage divider consisting of a 76.8K and 100K 1% resistors with Vout connected to A0, and I was consistently getting wrong values. I measured the output voltage of the voltage divider and got 1.7V, instead of the ~2.7 volts I should be getting with my supply. When I disconnected the wire to A0, the voltage rose to the expected level.
I disconnected power and measured resistance between the analog pins of the Atmega328 I was using and ground and found that A0 had 220K of resistance, while all other pins measured as infinite. When using the other pins, the voltage divider returned the expected values and was able to measure a wide range of resistors with values just as accurate as my multimeter. I know I have changed a lot of low-level things with code (analog reference, the comparator, ADC clock prescalers, using analog pins as outputs, etc.) but I don't think any of this could persist while the chip is not powered on. Does doing any of these things connect a resistor in the way I was describing, and is there anything that could cause this to stay "stuck" this way?

The datasheet says: The ADC is optimized for analog signals with an output impedance of approximately 10 kΩ or less - your voltage divider of 76k and 100k does not appear to satisfy those requirements.

Try adding a small capacitor between the voltage you try to measure and ground.

@NickGammon The voltage divider's impedance does not seem to be an issue, as it works perfectly on pins A1-A5 with a wide range of resistor values as the one being measured. The question is asking why there is the internal 220K resistance to ground that is causing it to work incorrectly on analog pin 0.

This is a raw chip is it? Not on some board? Try another chip, maybe this one is faulty.

Yes, it is a raw chip. I will try another one soon.

They don't connect a resistor as such, but analog input pins do have an impedance which can affect your readings.
If your output impedance (the resistance of your resistors) is within about a tenth of the impedance of the input pin then you will (and have) noticed skewing of the results.  This is normal.  The input impedance is somewhere in the region of 1MΩ - 10MΩ.
You have to keep your output impedance to a value below the order of a few tens of kΩ to minimise the effect the measuring of the value has on the value.
If you want to measure higher resistances then you will need to buffer the voltage with a very high impedance op-amp buffer.
Incidentally, your volt meter probably has an input impedance in the region of 10GΩ - around 1000x higher than the Arduino's ADC.

This does not answer the question. I am not experiencing skewing of the results as you said when I use any pins except A0. In fact, when using the other pins I can read a resistor and match the value my multimeter gives me. The question is asking why my Atmega has 220K of internal resistance between A0 and GND, but not any other analog pin.

It may be a faulty chip. I have never experienced differences between the different analog pins.  Nevertheless, you should watch that impedance and keep it within the specifications of the input pin.

It's also worth noting that the primary load impedance of an ADC is not something you can measure with the power off.  In fact on some chips (though perhaps not the ATmega) it actually changes depending on the ADC clock rate, and can become a rather heavy load at the higher ones.  What resistance an ohm-meter will see on a pin of an unpowered MCU depends in part if the test voltage is high enough to bias the protection diode into a measurable degree of conductance, and also on the test polarity.


text:
Reserve /dev/ttyUSBx
I have multiple Arduinos that I want to control using Python. My problem is that when I plug my Arduinos into the computer, they get assigned the port /dev/ttyUSBx where x increments with each one I connect.
Is there any way to reserve a certain number for a certain Arduino so that I can hard code that into the Python script? If not, can I scan the port to figure out which Arduino it is?

Do they have unique serial numbers?

@IgnacioVazquez-Abrams What do you mean by serial number? Do you mean the baud rate?

No. The serial number of the USB device.

@IgnacioVazquez-Abrams You mean the x in /dev/ttyUSBx?

No. I mean the serial number when you run lsusb -v.

If you mean iSerial, it's 0 for both.

Yes, iSerial. If they are the same you are kind of screwed. That's the price you pay for cheap Chinese clones though.

Am I screwed if I use Majenko's answer?

Since it relies on the serial being unique, yes.

You might be able to reprogram the serial, but I wouldn't count on it.

Yes. You need to create new unique names for them using udev rules.
By using the unique serial number, along with the VID and PID of the board you can use udev to create a symbolic link to a device name of your choice. Best to keep it to something that the Arduino IDE recognises if you want to access the link from within there for programming (otherwise you can choose what you like).
Rules are stored in /etc/udev/rules.d and take the form of .rules files with various instructions in.  One example, that should do what you want, is:
SUBSYSTEMS=="usb", ATTRS{product}=="Arduino Uno", ATTRS{serial}=="6493832323135111C0A1", KERNEL=="ttyACM*", SYMLINK+="ttyACM50", MODE="0666", GROUP="plugdev"

Of course, tweak it to your personal requirements.
Once you have crafted your rules be sure to restart udev:
sudo systemctl restart udev

or
sudo /etc/init.d/udev restart

and plug your board in.
Genuine Arduino devices usually use /dev/ttyACM* not /dev/ttyUSB*. If you have /dev/ttyUSB* then you are either on a very old device (with an FT232 chip) or a cheap Chinese clone.
If the latter then your mileage may vary somewhat.

Yep Chinese clones. Thanks for your answer.

Stepping on standard namespaces is probably not the best idea though. Naming the symlink something like "arduinoNN" might be a better idea.

Then the IDE won't see it. You notice I chose a name way up in the numbers - one not likely to be used under normal circumstances.


text:
Unable to type in Arduino IDE running on OS X
I'm trying to use the Arduino IDE (1.6.8 downloaded from arduino.cc) on a MacBook running OS X (10.11.5 beta).
The IDE seems to run and I can open and upload the examples and they run. But…
I can't type in the editor window of the IDE – either with the examples or with the new sketch that opens when you launch the IDE.
I have a similar problem with the version of the IDE distributed with mBlock (1.6.5) if I use the Edit in Arduino IDE button. I also tried the 1.6.9 hourly version. All to no avail. So I'm thinking that this is a OS X problem, or maybe an issue with version of Java (1.8.0).
Any ideas or troubleshooting suggestions?

Make sure that in preferences the option Use external editor is not checked. You could also try downloading an older version.

Yes! Thank you. I'd forgotten I'd done that. Make it an answer if you'd like and I'll accept it.

Make sure that in preferences the option Use external editor is not checked.

I find solution on this forum [http://forum.arduino.cc/index.php?topic=93338.]
File | Preferences | Use External Editor (Don't use)

This is the same solution as the accepted answer.

you may also consider Sublime Text -> with the STino plug-in, it is a full-fledged editor that does everything your arduino IDE does, in a much more stylish way.


text:
all in one Arduino robot
Can I make all in one arduino robot? Example - line follower, bluetooth control, sonar sensor,dtmf in one arduino robot just switch to any mode without change the parts.

Sure. Just get a large enough device.

Pls tell me how.

@Suny please show some effort of your own.
What have you tried? What works, what doesn't work? What do you think that's wrong? What have you observed? What sources have you found? What do/don't you understand?

I just want to make a robot with arduino.I want to add line flower,sonar,bluetooth control and dtmf. I want these 4 thing in different 4 switch with one arduino.I want to turn on/off 1/2/3/4 or all feature at the same time without changing parts.I want all of them in same place together but with different switch.

Yes, actually it has been done before (multiple times).
I, along with some other students did such a project at my school.
https://www.youtube.com/watch?v=GTJQ2VXtmk0
https://www.youtube.com/watch?v=sXXh3Q8WoEM
Materials needed

Arduino (or other programmable microcontroller board with voltage regulation)
Battery pack (and charger)
2 to 5 line sensors
ultrasonic sensor
Bluetooth module
Robot chassis
Atleast two motors (with encoders is nicer, but not neccesary)
Motor driving circuitry
Switch and emergency stop button

It can be useful to buy a "line follower robot kit"
Connection
This is the connection we used. You're free to make your own adjustments.

Programming
We used a server that (was connected via bluetooth) and has the map and a user-interface.
When you press the end-point on the server, it would generate the shortest route, calculate the directions, and send it to the robot.
The robot would then drive until it comes to a junction and then executes the direction command.
I've attached some preview code. It's better to do it yourself, but if you really don't know where to get started, you can try this.
You will have to implement the low-level code yourself.
The robot will wait for Bluetooth messages. You can set it to a "direct drive" modus or "line following" modus.
void setup() {
  // put your setup code here, to run once:
  setupBluetooth();
  setupUltrasonicSensor();
  setupMotors();
  setupLinesensors();
  state=waiting;
}

void loop() {
  char receivedCharacter = bluetoothReceiveCharacter();

  switch (state) {
    case waiting:
      switch(receivedCharacter){
        case 'd':
          bluetooth.println("Direct Drive enabled!");
          state = directDrive;
        break;
        case 'l':
          bluetooth.println("Line following enabled!");
          state = following;
          motor1.setSpeed(50);
          motor2.setSpeed(50);
        break;
      }
      break;
    case directDrive:
        directDrive(receivedCharacter);
      break;
    case following:
        followLine(receivedCharacter);
      break;
    default:
      bluetooth.println("STATE ERROR!");
      buzzer.buzz();
      led.blink();
    break;
  }
}

void followLine(){
    long distance = ultrasonicSensor.measureDistance();
    unsigned char lineSensorsPattern = lineSensors.getPattern();

    switch(receivedCharacter){
      case 'X':
        bluetooth.println("Line following disabled! (Now waiting)");
        state = waiting;
      break;
    }

    if(distance > 100 || distance == -1){
      switch(lineSensorsPattern){
        case 0b00000000:
          motor1.setSpeed(0);
          motor2.setSpeed(0);
          bluetooth.println("Following interrupted, lost path!");
          findPath();
        break;
        case 0b00000100:
          motor1.setSpeed(100);
          motor2.setSpeed(100);
          bluetooth.println("Following line, middle sensor on.");
        break;
        case 0b00000100:
          motor1.setSpeed(100);
          motor2.setSpeed(100);
          bluetooth.println("Following line, middle sensor on.");
        break;
        case 0b00000110:
          motor1.setSpeed(70);
          motor2.setSpeed(100);
          bluetooth.println("Following line, middle & right sensor on.");
        break;
        case 0b00001100:
          motor1.setSpeed(100);
          motor2.setSpeed(70);
          bluetooth.println("Following line, middle & left sensor on.");
        break;
        case 0b00000010:
          motor1.setSpeed(0);
          motor2.setSpeed(100);
          bluetooth.println("Following line, right sensor on.");
        break;
        case 0b00001000:
          motor1.setSpeed(100);
          motor2.setSpeed(0);
          bluetooth.println("Following line, left sensor on.");
        break;
      }
    }else{
      bluetooth.println("Following interrupted, obstacle in path!");
    }
}

void directDrive(char receivedCharacter) {
  switch (receivedCharacter) {
    case 'X':
      motor1.setSpeed(0);
      motor2.setSpeed(0);
      state = waiting;
      bluetooth.println("Direct Drive disabled! (Now waiting)");
      break;
    case 'w':
      motor1.setSpeed(motor1.getSpeed()++);
      motor2.setSpeed(motor2.getSpeed()++);
      break;
    case 'a':
      motor1.setSpeed(motor1.getSpeed()++);
      motor2.setSpeed(motor2.getSpeed()--);
      break;
    case 's':
      motor1.setSpeed(motor1.getSpeed()--);
      motor2.setSpeed(motor2.getSpeed()--);
      break;
    case 'd':
      motor1.setSpeed(motor1.getSpeed()--);
      motor2.setSpeed(motor2.getSpeed()++);
      break;
  }
}

My advice
My best advice is to work in iterations. Slowly add more features until you've got the product that you desire. Or develop parts of it individually.

Get a bluetooth link working, send some messages back and forth.
Connect motors to an Arduino and chassis let it drive a pre-programmed path.
Get some line sensors to work (non reflecting black tape!)
Get a ultrasonic sensor to work.
Start combining these! Control the robot over bluetooth. Let the robot follow the lines. Add a breaking when it sees something within range.

As addition/clarification.
You could make a button, that increases the state every time you press it.
If you then check which state the robot is in, you can make it perform his task for that state.
if(buttonPressed){state++;}
if(state>3){state=0;}

if(state==0){
  //code for DTMF handling
}else if(state==1){
  //code for bluetooth
}else if(state==2){
  //code for sonar
}else if(state==3){
  //code for line sensors
}

I'm sure the OP sill just write "there are compiler errors in your code, can you fix them?", according to the amount of effort he put in the question. And by the way, great answer, even if it is wasted for this question

How to without ATMEGA? I want to use only a anduino r3

@Suny the Arduino R3 is an "Atmega328P development board". In our project, we "made our own Arduino". You can easily use the Arduino Uno R3 in your case, it doesn't really matter ;)

I just want to make a robot with arduino.I want to add line flower,sonar,bluetooth control and dtmf. I want these 4 thing in different 4 switch with one arduino.I want to turn on/off 1/2/3/4 or all feature at the same time without changing parts.I want all of them in same place together but with different switch

I hope u understand.

@Suny, yes, but I think it's better to just get started. Do you have all the parts required? Do you know how to hook them up? Try to get it working and if one thing won't work, you can ask again. You can easily change from "mode" by pressing a button or sending a command, so I don't think it'll be a problem.

But what about arduino code? can I upload all code for 4 defferent iteam at the same time?

@Suny if you look at my code. You can keep a "state" variable, this can be an integer or anything to keep track of what your robot should be doing. In your code you can then call the code that is used for that state. I've added a little clarification at the bottom of my answer.

Ok.I am trying. Hope it will work.


text:
Tmp36 spike and dip
I'm measuring two temperatures  and powering both tmp36 sensors off of the 5v pin.  For some reason pin A0 (t0) will periodically spike or dip 100°f over actual ambient and pin A1 (t1) will spike or dip but only by about 30°f at the same time but not necessarily in the same direction at A0.
I'm using about 4' of 24ga solid wire to each sensor.
This began with a wall adapter putting out 5v 850ma connected to the barrel connector
Previous adapter of 5.3v 2a worked fine connected via USB.
I don't think it's SW because the arduino is doing exactly what I want it to do: measure t0 and t1 and write them to a database table via wifi.  I'm thinking that I need a 5.3v 2a barrel connector.  Am I right?

You should read the specifications of the Arduino board. It states that you need at least 6V on the barrel jack, preferably 7V minimum.

Well...there ya' go.  User error.


text:
How to handle an error in setup()
What is the "proper" way to handle an error during setup on an Arduino -- for example some attached component is missing or returning an error code or invalid response?  The setup() function returns void so that's no help. This just doesn't seem to be an issue that is addressed in the official docs -- at least not that I have found so far.
Here are some options I have considered:

Throw an exception (but where does that go?)
Write a message to Serial and then go into an infinite loop or wait for a y/n to continue.
Set a setup_successful flag and then do if (!setup_successful) return;  in the main loop()

The setup() function returns void so that's no help.

You wouldn't be able to get the return value anyway even if it did return something - it's not you calling the setup() function, but main(), which is not in your code or control.

This just doesn't seem to be an issue that is addressed in the official docs

That is because it is not within the remit of the API and its associated documentation.

Throw an exception (but where does that go?)

It goes in the bin.  Exceptions are disabled.  They make little sense in an embedded system.  Yes, it is possible to use them, but not worth it.

Write a message to Serial and then go into an infinite loop or wait for a y/n to continue.

That kind of thing is what most people do - or variations on that kind of theme.

Set a setup_successful flag and then do if (!setup_successful) return; in the main loop()

That will just run loop() again - after all, it's called loop() for a reason.
You seem to be in the mindset of a PC programmer. Embedded programming is a very very different beast. You don't (usually) have an operating system to handle exceptions and errors and things like that. You don't have a keyboard and mouse, and a screen with pretty pictures on it. Every single thing that the board does is what you program. If you want it to raise an error when an error occurs then it is up to you to program a suitable mechanism for that to happen. Reporting that error and asking for feedback in some way is entirely governed by your system's design. If you have a TFT screen you could put an error message on that. If you have a serial connection you can use that to show error messages. If you don't have any of those you can blink an LED or use a buzzer to beep in a specific pattern (like a PC's POST beeps).

It's true, I have been an application developer (mostly unix/linux) for over 30 years so my thinking is more along those lines and since Arduino and others have made access to embedded development so accessible, there are probably a lot of people like me that art starting to cross over and blur the lines.

Same way you would handle any error in an embedded system; either try to recover from it if you can, or use whatever communications mechanism you have to let the user know that something failed.
I normally use a combination of Serial.println in case I happen to have a serial connection at the time, and also a blinking pattern on an LED (which most boards I use have). As an example, look at my code here: https://github.com/jayeye/jardino/blob/master/libard/WiFiSPIFFSConfig/src/WiFiSPIFFSConfig.cpp#L11. error() will do a sequence of slow and then fast blinks, and either return if I think the error is recoverable and I'm merely warning the user, or just stay in an infinite loop and keep blinking in despair :)
Obviously this is not an original idea -- think beep codes!


text:
I want to run jvm on arduino.What minimum configuration do I need?
If Arduino IDE itself is built on Java can I run JVM on the Arduino? If yes how should I do it?

An Arduino is the wrong choice for this task.

Ah, why do you want to do this?

Which limited memory hardware I can use here? I want to use in robotics and want to run machine on java.

Search for "embedded java". Oracle supports it for ARM cores, which is what some of the arduino-like boards such as the Teensy 3.X have, but I doubt they have enough resources to support it.
There is haiku-vm (google it!) that's designed with AVR processors in mind, but I don't know how actively it is being worked on.
Googling "embedded java avr" yields a tremendous amount of results; did you even try that?

Thank you very much for suggestions. I've tried searching vms. They support limited java libraries though. I want to know some other options if any.Also I don't know what hardware resources are required to support jvm.I went through nano vm too.Your suggestions helped me.


text:
My code is stuck in a loop involving Serial.read. How can I break this?
So I'm running a program that involves both Arduino and a Raspberry PI and they are communicating between the Serial port. As you can see below when my an emergency stop door, involving a magnetic switch, is opened then the PI sends a message to the Arduino. When the door is closed the PI sends a different value telling the Arduino to continue with the program. The Arduino is receiving and reading the messages correctly as I have ran a few tests with the serial monitor.
When the door is open the PI is printing '1' which shuts down the Arduino correctly. My problem is that when I close the doors nothing happens when in theory it should break the loop and continue to run the main Arduino code. The raspberry PI is correctly printing '2' and the Arduino is correctly reading this value as it prints "Logoff" in the serial monitor.
If anyone can help or lead me to correctly breaking this loop and returning to the main code that would be great.
Thanks.
Below is the emergency part of the code that continues to run. If the full code is needed I will gladly edit it into this post. Also if the PI code is needed I will post that too, I don't believe is necessary because there are no problems on that side.
void Estop() {
    if (Serial.available()) {
        int d = Serial.read() - '0';

        while (d == 1) {
            digitalWrite(green, HIGH);
            digitalWrite(red, LOW);
            digitalWrite(blue, HIGH);
            digitalWrite(estopout, HIGH);
            digitalWrite(piston, LOW);
            digitalWrite(belt, HIGH);
            Serial.read() - '0';
            Serial.print(d);
            delay(2000);
            break;

            if (d == 0) {
                Serial.print("Logoff");
                delay(2000);
            } else {
                break;
            }
        }
    }
}

`

I have reformatted your code so it indents properly. It then becomes much easier to see the flow of logic. I have a feeling the whole way you are doing what you are wanting to do is flawed. A proper description of what exactly it is you are trying to achieve would help.

What does this line prints? Serial.print(d);

You never reassigned the variable d anywhere within the loop. The while breaks after a 2 seconds delay after printing what is the value of d. That means that your if (d == 0) [...] never gets hit. I presume that you expect to read 'logoff' on your code?
void Estop() {
    if (Serial.available()) {
        int d = Serial.read() - '0';

        while (d == 1) {
            digitalWrite(green, HIGH);
            digitalWrite(red, LOW);
            digitalWrite(blue, HIGH);
            digitalWrite(estopout, HIGH);
            digitalWrite(piston, LOW);
            digitalWrite(belt, HIGH);
            d = Serial.read() - '0';
            Serial.print(d);
            delay(2000);
            #break;

            if (d == 0) {
                Serial.print("Logoff");
                delay(2000);
            } else {
                break;
            }
        }
    }
}

Inside your while loop, you never change the condition, running into an infinite while loop.
Further: Your program does not delay until d equals 0 or 1. This can be problematic as d can have other values. It is an int.
Plus, you do a while loop while d equals 1 and ask, if d equals 0 without changing the value of d in between. Your if would never be true.
I also don't know, what this line should do:
int d = Serial.read() - '0';

did you mean:
int d = Serial.read();

I dont't see any sense, to subtract 0 from your the value you read.

The line that subtracts '0' converts the script coming form the PI into a value that the Arduino can read. So should i change the while to an if statement?

'0' is the ASCII value, so subtracting turns a ASCII number into its corresponding integer.  It is basically atoi(Serial.read()) that is only valid for the characters 0-.


text:
Second I2C address not accepted
I have set up 2 DHT22 sensors and 2 BMP280 sensors with an Arduino Uno SMD R3 board. The DHTs are working fine and are outputting correct temperature and humidity values to the Serial monitor. The BMPs are connected via I2C and do not.
I assigned the standard address (0x77) to one of them, and set the other to 0x76 by placing a jumper between GND and SDO. However, in the Serial output, both devices are detected and connected (this is checked in the loop() by using the Wire library), but only one of them (0x77) shows up with the correct pressure and temperature. The other address is recognized, but it seems not to be able to transmit data.
There are already pullups on the SCL and SDA lines to the +5V terminal.
Both BMP280 sensors work, by reversing their position, it is still address 0x77 that works, however, once I change the jumper, neither works. Might this be simply an issue with the breadboard or is there an address conflict somehow? Also, I have tried several values for the pullup resistors (4.7 kOhm, 10kOhm and 140kOhm), they all seem to have the same effect.
The output looks like this:
Found address: 118 (0x76)
Found address: 119 (0x77)
Found 2 device(s).
DHT22_1: hum1 = 28.00 %, temp1 = 24.80 C
DHT22_2: hum2 = 24.80 %, temp2 = 24.70 C
BMP280_0x77: t_77 = 25.83 Cp_77 = 100039.43 Pa
BMP280_0x76: t_76 = 0.00 Cp_76 = 0.00 Pa

and I used the following code:
#include <DHT.h>
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BMP280.h>

// Constants
#define DHTPIN_1 5     // pin for data
#define DHTPIN_2 4
#define DHTTYPE DHT22   // what type of sensor: DHT 22  (AM2302)

DHT dht1(DHTPIN_1, DHTTYPE); // initializes sensor
DHT dht2(DHTPIN_2, DHTTYPE); // initializes sensor

Adafruit_BMP280 bm77; // I2C
Adafruit_BMP280 bm76(0x76); // I2C

// Variables
int chk;
float hum1;  // stores humidity
float temp1; // stores temperature
float hum2;  // stores humidity
float temp2; // stores temperature

// --- Setup --- //
void setup()
{
  delay(1000);
  Serial.begin(9600);
  dht1.begin();
  dht2.begin();
  bm77.begin();
  delay(500);
  bm76.begin();
}

void loop()
{
  byte count = 0;
  Wire.begin();
  for (byte i = 1; i < 120; i++)
  {
    Wire.beginTransmission (i);
    if (Wire.endTransmission () == 0)
      {
      Serial.print ("Found address: ");
      Serial.print (i, DEC);
      Serial.print (" (0x");
      Serial.print (i, HEX);
      Serial.println (")");
      count++;
      delay (1);  // maybe unneeded?
      } // end of good response
  } // end of for loop
  Serial.print ("Found ");
  Serial.print (count, DEC);
  Serial.println (" device(s).");

  hum1 = dht1.readHumidity(); // reads and stores hum
  temp1= dht1.readTemperature(); // reads and stores temp
  hum2 = dht2.readHumidity(); // reads and stores hum
  temp2= dht2.readTemperature(); // reads and stores temp
  // serial output commands

  delay(2000); // reading needs to be delayed by at least 2000ms
  Serial.print("DHT22_1: ");
  Serial.print("hum1 = ");
  Serial.print(hum1);
  Serial.print(" %, temp1 = ");
  Serial.print(temp1);
  Serial.println(" C");

  Serial.print("DHT22_2: ");
  Serial.print("hum2 = ");
  Serial.print(hum2);
  Serial.print(" %, temp2 = ");
  Serial.print(temp2);
  Serial.println(" C");
  delay(500);
  Serial.print("BMP280_0x77: ");
  Serial.print("t_77 = ");
  Serial.print(bm77.readTemperature());
  Serial.print(" C");
  Serial.print("p_77 = ");
  Serial.print(bm77.readPressure());
  Serial.println(" Pa");
  delay(500);
  Serial.print("BMP280_0x76: ");
  Serial.print("t_76 = ");
  Serial.print(bm76.readTemperature());
  Serial.print(" C");
  Serial.print("p_76 = ");
  Serial.print(bm76.readPressure());
  Serial.println(" Pa");

  Serial.println();

}

The setup I used. red = +5V, black = GND, green = SCL, blue = SDA, yellow = DHT data lines, white = jumper between GND and SDO. Pictured is a different model of the BMP series, but in my case, I used the BMP280 and did not connect the other connectors. Edit: seems to be missing in the diagram, but of course, the positive and ground terminal are connected to the breadboard.

According to the datasheet:

SDA and SCL are not pure open drain. Both pads contain ESD protection diodes to VDDIO and GND. As the devices  does  not  perform  clock  stretching,  the  SCL  structure  is  a  high-Z  input  without  drain capability.

I'm not sure if this affects the operation with two together as you have them, but I must say that your debugging seems very thorough. :)
The words "without  drain capability" are a bit worrying. There is a thread on the Adafruit forum about this, where they suggest an I2C multiplexer.
On my page about I2C I have a schematic and code for a simple multiplexer using the CD4051 multiplexer chip (reply #11).
The schematic is this:

I am basically just interested in connecting and reading both BMP sensors simultaneously, not necessarily over I2C. However, I cant get the SPI connection to work, I2C seems like the best option so far. Is there maybe a possibility without such a multiplexer?

Judging by what you found, no. The multiplexer is, like, a $1 chip.

Alright, thank you. As an update, I have not tried it with this I2C multiplexer, but instead returned to using only one BMP sensor with an SPI connection. According to what the internet says on this topic, it seems that indeed such a multiplexer is the only reliable solution.


text:
Driving numerous chips from 2 separate SPI connectors w/ Arduino Micro
I want to drive numerous chips (L9823, TLC5925, ADG1414, MCP23S08) from an Arduino Micro as well as read input from analog pins connected to momentary buttons, toggles, potentiometers and such. The chips and input controls will be on various boards connected to the Arduino using ribbon cables.
The current idea is to have two sets of 8 pin FFC connectors with the following pins:
FFC digital "bus" conductors:
--
SCLK
VL
SDI
RST
SDO
LE3
LE2
LE1

The clock, VL (5V), SDI and SDO will be shared by both connectors but I still need 6 latches (which can also be commandeered for an interrupt or analog input) and 2 reset pins. This will allow me to run up to 3 types of chips per connector (minus latches used for something else).
I will also have a third 8-conductor FFC connector for 7 analog inputs (the eighth conductor is 5V analog ref).
So my question is, does anyone see any holes in this strategy? I don't think I'm going to try to even breadboard something like this. PCB fab is so easy now (and the first run is always wrong anyway) so I'm just going to make the boards and go from there.
So I just need to settle on what pins to use. Here is a diagram of the Arduino Micro:

So the connectors could use pins:
Connector 1 - Digital I/O:
--
SCLK SCK
VL   5V
SDI  MOSI
RST  11
SDO  MISO
LE3  A8
LE2  A7
LE1  SS

Connector 2 - Digital I/O:
--
SCLK SCK
VL   5V
SDI  MOSI
RST  13
SDO  MISO
LE3  A9
LE2  7 (Arduino INT)
LE1  5

Connector 3 - Analog Inputs:

5V
A0
A1
A2
A3
A4
A5
A6

A10 and A11 are reserved for other purposes as well.
Does this look ok?
UPDATE 1:
I have updated the text of this question to consider many of the great comments. The changes include:

Share MISO and MOSI
between connectors. Not sure why I thought I needed to use separate
ports for the different connectors. SLCK, MISO and MOSI should
indeed be shared by both connectors.
Moved 5V to be in between
SCK and MISO and moved RST to be in between MISO and MOSI. The idea
is that the low impedance of these lines will shield from capacitive
crosstalk described by Majenko. The connectors are 1mm pitch which
isn't terribly small so hopefully this will not be an issue. It does
make routing a little harder since the data pins tend to be next to
each other but the same bus is going to connect to multiple boards
in a daisy chain fashion so capacitive crosstalk could definitely be
an issue. Fortuntely things don't have to run really fast since
everything is ultimately for interfacing with humans who are
relatively slow.

The micro only has one SPI bus. It is SCK/MISO/MOSI. You may want a second one, but you don't have one.  You can't magic one up out of thin air.
You could emulate one in pure software (bit-banging) but it won't be anywhere near as efficient as using a real hardware one.
Why do you feel you need to have two independent buses anyway? What are you wanting to achieve that you can't achieve with a single shared bus? That same bus can quite happily appear on multiple connectors.
One thing to note with your strategy: Ribbon connectors and SPI don't mix well together.  There is a lot of crosstalk and capacitance in a ribbon cable that high speed serial communication really doesn't like.  If I had to use ribbon cable for SPI communication for anything longer than a couple of inches I would use twice as many connections and interleave ground between each signal.  That is what the ribbon cables for later IDE drives in PCs used to get higher speed, more reliable, communication down ribbon cables.

I have a bit-banged SPI library on my page about SPI. For low-ish speeds that could be perfectly acceptable.

The MOSI (Master Out Slave In) and MISO (Master In Slave Out) will be much better for your SPI pins. Your SDI (Slave Digital In iirc) will equate to MOSI and your SDO (Slave Digital Out iirc) will equate to MISO. Those are the hardware SPI pins and will be much better than trying to emulate SPI in software.

But I want 2 buses. Meaning I want 2 channels of SPI so that I can have 2 cables with different latches (2 x 3 = 6 latches). So you can't use other pins for SPI without "emulating"? What about pins 2 and 3. It seems they are used for I2C communication so perhaps they can be jerry rigged for SPI? None of this needs to be terribly fast. Even 125 KHz would be fine I think.

Could you have one bus that splits off on your PCB to both connectors?

You have SDI and SDO backwards there. SDO is Serial Data Out and is the same as MOSI - SDI is Serial Data In and is MISO. It's the flow of serial data as seen from the master.

Thanks. I have updated the question. Yes, I definitely can share MISO and MOSI on both connectors. Not sure why I thought I needed separate pins for that. Also I corrected the reversed MISO and MOSI lines.

@Majenko It depends on what datasheet you're looking at in my experience. For example, the MAX31865 IC datasheet here: https://datasheets.maximintegrated.com/en/ds/MAX31865.pdf has the SDI line as an input to the MAX31865, not as an output to the micro.

Actually SDI and SDO were not backwards. The input of each chip needs to connect to the output of the uC. MOSI sends data to SDI and SDO sends data to MISO.


text:
arduino mega overheat when connected to TFT 7" and TFT shield
I have bought a 7" LCD (TFT01-7) and a shield to make it work with arduino mega (http://www.elecfreaks.com/store/lcd-tft01-mega-shield-v10-p-214.html), but when I upload my code to the arduino and plug my LCD to the shield the arduino get overheated and the LCD lose power and I don't know why even when I power my arduino with external 9V 2A adapter, I even tried uploading an example from the library but it does the same, I used to work with the same code and the same shield but with 5" LCD ITDB50 and I didn't have this problem before, how can I fix this?

What is powering the mega?

an external adapter (9V,2A)

7" LCDs need a lot of current. They need it for the back light.
That current comes from the 5V pin.  That 5V pin is supplied by a linear regulator that has limited current capacity.  As you draw more current it gets hotter and hotter and eventually shuts down.
You will need to power your LCD screen with another external 5V source. The best solution may be a powerful (2A) phone charger (USB) which you then plug direct into the USB port of the board thus bypassing the weak regulator.

So can I connect my lcd to the shield and connect the 5V pin to external power source and then connect the ground pin to the external source ground and make it common with the arduino ground?

Yep. That's right. As long as it is a regulated 5V power source.

Sorry for the late reply (I was buying some components), I did try what you said, I connected my LCD to the shield and connected it to arduino through jumpers, except for the (3.3V, 5V, ground, Vin) pins wich happen to be the power pins on the shield, I connected them to external (5V 1.5A) usb adapter, I think that the LCD is stable now but I only get the backlight on...I can't see my code, it doesn't draw anything.

Is the ground connected to both the Arduino and the external power supply?

I'm connecting Vin on the arduino board to 5V and whenever I take it off the LCD starts blinking, and I do connect the corresponding pin to Vin on the shield to 5v, I'm also connecting both the ground pins on the arduino and the corresponding pins to the on the shield to the ground of the 5V power source, the 3.3V corresponding pin on the shield is connected through a level shifter that I made of 10k and 20k resistors and connected them to the 5V adapter and finally the RST pin is connected to it's corresponding on the shield

the 3.3V corresponding pin on the shield is connected through a level shifter that I made of 10k and 20k resistors - that is doomed to failure. You cannot translate power that way, only very very tiny signals.

Ok, I moved it back to the arduino 3.3V pin but still nothing happens.

Please provide a picture or drawing of how you have it wired up at the moment. It is not clear from your description.

please check the edit that I did to my question


text:
Visibility of #define between sketch and library
I want to have a define from my sketch be picked up by a library.
Here is a similar question for references: Using #define and multiple classes
I have a CI server that compiles my arduino sketchs on commmit. It pulls all my personal libs from an other repository and compiles the sketch using arduino-builder.
Now i want it to also make a debug build. (Some of my library's have debugstatments in them i enable using a #define debugsomething.
Is there any way i can get the compiler to pickup the #define in the sketch or am i better off making a very complex build script that modifies the headers between builds?

You need a common place that the building of all the places can get the definition from.
That isn't the sketch. The sketch is one of the things that would have to look at that common place.
That can either be a single shared header that everything else (that needs it) includes, or it can be a -D flag added to the compilation command.
For instance, adding:
-DDEBUG=1

to your compilation command is the same as adding
#define DEBUG 1

to every single file you compile.

Thanks for the replay. The -D options looks great for my purpose. Do you have any clue how to do this with https://github.com/arduino/arduino-builder?

I haven't a clue. Never used arduino-builder, and I don't speak "go", so I can't even work out what it's supposed to be doing. The lack of documentation makes it impossible to know how to actually use it, as well.

I made a issue over there. Hope they can help me : https://github.com/arduino/arduino-builder/issues/138

Can i also do multiple defines with one -D argument? Looks to me something does wrong when i try multiple -D arguments see issue 138

You can use as many -Dxxx=yyy arguments as you like.

There is no way to hack it into one argument? As the builder currently fails to give me the second one.

Nope. Not unless you want to re-program the AVR GCC compiler - which you don't.

Wow your fast. Indeed i won't. I rather fix the arduino-builder :). I hope i get a response there.


text:
Graphing force sensor data routed through HX711?
I'm using the code off of the sparkfun website HX711 hookup guide (https://learn.sparkfun.com/tutorials/load-cell-amplifier-hx711-breakout-hookup-guide#arduino-code) to attempt to create a scale.
Currently I have output data of weight in the serial monitor - is there an easy way to then graph this data with regards to time? I've spent an hour fooling around with Processing and googling, but haven't had any luck.
Thanks!

Include the Time library in your sketch, then print the time and your sensor output as a comma separated list. Your output to the serial monitor can then be written to .csv file using PuTTY, which you will need to download in order to collect data (I used online tutorials to figure out writing to a file with PuTTY). Once in a .csv, you can open the file in Excel to graph the data.


text:
STPM10 using Arduino SPI communication
I am working with STPM10 energy metering chip (evaluation board) and I want to read the data from 8 internal registers of the chip each containing 32 bits.
The datasheet of the STPM10 chip suggested to have a simplex synchronous SPI where the MOSI of the Arduino is not connected to any pin on the energy chip. Instead they provided a timing diagram to switch from reading and writing on the energy chip.

After the t5, datasheet stated that we should apply 32 serial clocks per data record and up to 8 data records can be read this way. My problem is how to apply 32 serial clocks to the chip.  Is the Serial clock on the Arduino SPI automatically activated after SPI.begin() ? If not, how can I start the serial clock? By the way, this is the code I've written:
#include <SPI.h>

SPISettings settingA(32000000, LSBFIRST, SPI_MODE0);
const byte SYN = 8;
void setup() {
  Serial.begin(9600);
  pinMode(SYN,OUTPUT);
 /*Initializes the SPI bus by setting SCK, MOSI and SS to outputs
  Pulling SCK, and MOSI low, and SS high */
  SPI.begin();
  SPI.beginTransaction(settingA);

  }

void loop() {
  //0----->t1
  digitalWrite(SS,HIGH);
  digitalWrite(SYN,HIGH);
  delay(500);
  //t1----->t2
  digitalWrite(SYN,LOW);
  delayMicroseconds(1000);
  //t2----->t3
  digitalWrite(SYN,HIGH);
   delayMicroseconds(0.035);
  //t3----->t4
  digitalWrite(SS, LOW);
  delayMicroseconds(0.035);
  //t4----->t5
  digitalWrite(SYN, LOW);
  delayMicroseconds(0.035);
  //t5---->t6
  digitalWrite(SYN, HIGH);
  delayMicroseconds(0.035);

  byte d1 = SPI.transfer(0x00);
  byte d2 = SPI.transfer(0x00);
  byte d3 = SPI.transfer(0x00);
  byte d4 = SPI.transfer(0x00);
  byte d5 = SPI.transfer(0x00);
  byte d6 = SPI.transfer(0x00);
  byte d7 = SPI.transfer(0x00);
  byte d8 = SPI.transfer(0x00);
  byte d9 = SPI.transfer(0x00);
  byte d10 = SPI.transfer(0x00);
  byte d11 = SPI.transfer(0x00);
  byte d12 = SPI.transfer(0x00);
  byte d13 = SPI.transfer(0x00);
  byte d14 = SPI.transfer(0x00);
  byte d15 = SPI.transfer(0x00);
  byte d16 = SPI.transfer(0x00);
  byte d17 = SPI.transfer(0x00);
  byte d18 = SPI.transfer(0x00);
  byte d19 = SPI.transfer(0x00);
  byte d20 = SPI.transfer(0x00);
  byte d21 = SPI.transfer(0x00);
  byte d22 = SPI.transfer(0x00);
  byte d23 = SPI.transfer(0x00);
  byte d24 = SPI.transfer(0x00);
  byte d25 = SPI.transfer(0x00);
  byte d26 = SPI.transfer(0x00);
  byte d27 = SPI.transfer(0x00);
  byte d28 = SPI.transfer(0x00);
  byte d29 = SPI.transfer(0x00);
  byte d30 = SPI.transfer(0x00);
  byte d31 = SPI.transfer(0x00);
  byte d32 = SPI.transfer(0x00);

  digitalWrite(SS,HIGH);
  digitalWrite(SYN,HIGH);
  delay(499);

  Serial.println(String(d4,BIN) + " " + String(d3,BIN) + " " +  String(d2,BIN) + " " +  String(d1,DEC));
  Serial.println(String(d8,BIN) + " " + String(d7,BIN) + " " +  String(d6,BIN) + " " +  String(d5,BIN));
  Serial.println(String(d12,BIN) + " " + String(d11,BIN) + " " +  String(d10,BIN) + " " +  String(d9,BIN));
  Serial.println(String(d16,BIN) + " " + String(d15,BIN) + " " +  String(d14,BIN) + " " +  String(d13,BIN));
  Serial.println(String(d20,BIN) + " " + String(d19,BIN) + " " +  String(d18,BIN) + " " +  String(d17,BIN));
  Serial.println(String(d24,BIN) + " " + String(d23,BIN) + " " +  String(d22,BIN) + " " +  String(d21,BIN));
  Serial.println(String(d28,BIN) + " " + String(d27,BIN) + " " +  String(d26,BIN) + " " +  String(d25,BIN));
  Serial.println(String(d32,BIN) + " " + String(d31,BIN) + " " +  String(d30,BIN) + " " +  String(d29,BIN));
  Serial.println(" ");

The timing diagram posted does not look like a standard SPI transaction.  I am inclined to say you can not use the Arduino SPI library.  Instead, you may need to bit-bang this out totally in software.  For instance, I do not believe there is a "SYN" line in the standard SPI bus.  And I don't believe the Chip Select line should go high before the end of the SPI transaction.

This is basically a bidirectional SPI (which many of ST's MCUs support) plus a mode/latch pin - SYN which one would drive with a GPIO.  I don't believe there is any requirement that the chip select go high early, especially as some of the timing diagrams in the data sheet show it low during the whole transfer.

The STPM10 specification describes a SPI bus unlike any I have seen.  Apparently the STPM10 "SYN" line controls the direction of the "SDA" line.  As far as I know, there is no "SYN" line in a SPI bus.  As such I do not think a normal Arduino SPI library will talk to an STPM10.
A normal single port (MOSI and MISO combined) SPI slave would automatically switch between reading and writing bits.  When interfacing with a two port master (such as an Arduino) a resistor is used between the MISO and MOSI nets.
This is the best image I could find.  Ignore the chip names.  And substitute MOSI for SDO and MISO for SDI.  Note there is no "SYN" line in this SPI bus.

I'm showing this diagram as it appears the STPM10 is using a single line for both input and output data.
Because of the missing "SYN" line I do not think you can even use the SPI hardware in the Arduino's Atmel processor.  I think your only option is to create a SPI driver from scratch only using software.
I see where STMicroelectronics offers an evaluation software package that talks to the STPM10.  Guessing, it looks like they wrote it in National Instruments Lab View.  If you could get the source code for that it may provide hints on writing your own STPM10 driver.

Like the datasheet says, its best if you implement writing in software and use the hardware SPI for reading. The steps for writing to the registers are as follows:

disable the SPI peripheral;
set MISO, SCLK and SS to be output;
set the pin which is connected to SYN to be output high;
activate SCS first and then SYN;
activate SCL;
apply a bit value to SDA and deactivate SCL;
repeat the last two steps seven times to complete one byte transfer;
repeat the last three steps for any remaining byte transfer;
deactivate SYN and the SCS;
enable again the SPI module;

In Arduino-speak:
#define SCS 4  // define your own CS to have better control

void setup(){
  pinMode(SS, OUTPUT);  //needed to use the SPI

  pinMode(SCS, OUTPUT);  // set SCS and SYN as output
  pinMode(SYN, OUTPUT);
  digitalWrite(SCS, HIGH);  // idle state
  digitalWrite(SYN, HIGH);
  SPI.beginTransaction(SPISettings(32000000, MSBFIRST, SPI_MODE3)) // mode 3, max read clock is 32mhz
}

void write_reg(byte addr, byte val){
  val = (val << 7) | (addr << 1);  // 6-bit addresses!
  SPI.end();  // disable SPI
  pinMode(MISO, OUTPUT);
  digitalWrite(SYN, HIGH);
  delayMicroseconds(10);

  digitalWrite(SCS, LOW);  // assert SCS and SYN
  digitalWrite(SYN, LOW);
  for (int i = 0; i < 8; i++){  // shift out a byte
    delayMicroseconds(10);
    digitalWrite(SCK, LOW);  // max clock is 100kHz
    digitalWrite(MISO, (val & 0x80) ? HIGH : LOW);
    delayMicroseconds(10);
    digitalWrite(SCK, HIGH);
    val <<= 1;
  }

  digitalWrite(SYN, HIGH); // deassert SCS and SYN
  digitalWrite(SCS, HIGH);

  SPI.beginTransaction(SPISettings(32000000, MSBFIRST, SPI_MODE3)); //restart SPI
}

For reading, you use the hardware SPI like this:
void read_regs(uint32_t data[], uint8_t len){  // an array to hold register data is passed
  digitalWrite(SYN, LOW);  // latching operation
  digitalWrite(SCS, LOW);
  digitalWrite(SYN, HIGH);

  uint32_t val = 0;
  for (int i = 0; i < len; i++){  // read the 8 32-bit registers into the array
    val = SPI.transfer(0);  // your 32 serial clocks
    val |= (uint32_t)SPI.transfer(0) << 8;
    val |= (uint32_t)SPI.transfer(0) << 16;
    val |= (uint32_t)SPI.transfer(0) << 24;
    data[i] = val;
  }

  digitalWrite(SCS, HIGH);  // deassert SCS
}

// Use the functions this way:

uint32_t reg_data[8];  // array to hold read data, max is 8

void loop(){
  write_reg(47, 1);  // set config bit 47
  read_regs(reg_data, 8);  // read all reg data into array

  for (int i = 0; i < 8; i++)
    Serial.println(reg_data[i], HEX);
}

The connections are:
Arduino MISO = SDA
Arduino SCK = SCL
Arduino D4 = SCS
Arduino D5 = SYN

Each call of SPI.transfer() yields 8 serial clocks i.e. a clock for each bit, so 32 serial clocks is merely 4 SPI.transfer() calls. Your code is actually producing 32 x 8 = 256 serial clocks. I suggest you read up on SPI.
I didn't include some of the delays in the datasheet because digitalWrite() on an Uno takes about 5us which is more than enough for this case. Of course, the code is untested so...I've done most of your work already, almost feels like I should be getting paid or something...

Will definitely test this once I have a breakout for the module. Will donate some cash to you when it works. 80% done on this non-SPI , SPI.