body: Suggestion: - don't try to "moosh" (that's a technical-term!) the state-machine heirarchy down into one large, flat state-machine. That way lies madness. Keep your { NULL, COMMAND, PARAMETER, OPTIONS } state machine, for instance, and, wherever you need something more than simple string collection in one of those states, call a parser SM appropriate to the kind(s) of input you expect at that point - a number, a quoted string, an option specifier, etc.


sender: user

message:
How to save data to SD card using Memory Shield Module SPI

I am trying to save some data to the SD card using the memory shield module that I read from HC-SR04 Ultrasonic Module. The data that gets printed indicates error. This is how my SD card module is connected.

> SD card attached to SPI bus as
> VCC -Arduino 5v
> GND- Arduino GND
> MOSI - pin 11
> MISO - pin 12
> CLK - pin 13
> CS - pin 4

Still, Arduino complains that there was an error opening the file in SD card. My sketch is this:

    #include <SPI.h>
    #include <SD.h>
    #define echoPin 6 // Echo Pin
    #define trigPin 7 // Trigger Pin

    int maximumRange = 250; // Maximum range needed
    int minimumRange = 1; // Minimum range needed
    long duration, distance; // Duration used to calculate distance
    const int chipSelect = 4;

    void setup() {
      Serial.begin (9600);
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);

      Serial.print("Initializing SD card...");
      // see if the card is present and can be initialized:
      if (!SD.begin(chipSelect)) {
        Serial.println("Card failed, or not present");
        // don't do anything more:
        return;
      }
      Serial.println("card initialized.");
    }

    void loop() {
      readDistance();
      if(distance>minimumRange && distance < maximumRange){
        String string = "distance is" + distance;
        // open the file. note that only one file can be open at a time,
        // so you have to close this one before opening another.
        File dataFile = SD.open("datalog.txt", FILE_WRITE);
        // if the file is available, write to it:
        if( dataFile ){
          dataFile.println(string);
          dataFile.close();
          Serial.println( string );
        }else{
          // if the file isn't open, pop up an error:
          Serial.println("error opening datalog.txt");
          dataFile.close();
        }
      }else{
        Serial.println("Out of range...");
      }
      delay(50);
    }

    int readDistance(){
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);
      duration = pulseIn(echoPin, HIGH);
      distance = duration/58.2;
    }
Output:

    rror opening datalog.txt
    rror opening datalog.txt
    error opening datalog.txt
    rror opening datalog.txt
    error opening datalog.txt
    error opening datalog.txt
    error opening datalog.txt
    error opening datalog.txt
    error opening datalog.txt

How do I solve this to save the readings to SD card?

sender: assistant

body:
Is there any print out based on this;

    Serial.print("Initializing SD card...");
    // see if the card is present and can be initialized:
    if (!SD.begin(chipSelect)) {
      Serial.println("Card failed, or not present");
      // don't do anything more:
      return;
    }
    Serial.println("card initialized.");

Solution;

Try change

    const int chipSelect = 4; // change value to 10

If not, try change the above code to;

    Serial.print("Initializing SD card...");
    if (!SD.begin(10)) {
      Serial.println("Initialization failed!");
      while (1);
    }
    Serial.println("Initialization done.");


message:
How to properly process large arithmetic

just a question that requires a simple answer. How do I process a large number of arithmetic steps in arduino efficiently and precisely?

For example I have this code function setup:

    void calc() {
      batterymoment = input*batterymass;
      totalmoment = 149650+batterymoment;
      buoyancymoment = buoyancymass*centrebuoyancy;
      wheelmoment = totalmoment - buoyancymoment;
      wheelweight = totalmass - buoyancymass;
      cgwheels = wheelmoment/wheelweight;
      maindistance = mainarm - wheelweight;
      nosedistance = wheelweight - nosearm;
      mainmass = (((wheelweight)*(1-((maindistance)/(maindistance+nosedistance))))/2);
      nosemass = (((wheelweight)*(1-((nosedistance)/(nosedistance+maindistance))))/2);
      mainmoment = mainmass*mainarm;
      nosemoment = nosemass*nosearm;
      netmoment = buoyancymoment+mainmoment+nosemoment;
      netcg = netmoment/totalmass;
      staticmargin = adc - netcg;
      answer = staticmargin/meanadc;

    }

Now I've properly setup up data types for all of these variables and they are a combination of float, int and long. I don't think it's a problem with the data type. What I'm getting when I print final answer in the serial is the same number regardless the input the user enters.

I'm guessing I need to format the code in such a way that it performs each line step by step and verifies the answer before proceeding to the next arithmetic line. If so would I need a function for each arithmetic step? Or is there a simpler way to process this that I'm missing.

Any guidance is appreciated. Thanks.

Here is the code in its entirety:

    unsigned long batterymoment,num1,num2,input,totalmoment;
    double buoyancymoment,wheelmoment,cgwheels,mainmass,nosemass,maindistance,nosedistance;
    double mainmoment,nosemoment,netmoment,netcg,staticmargin,answer;
    double centrebuoyancy = 14.164;
    double mainarm = 14.3;
    double adc = 11.4;
    double meanadc = 22.65;
    double nosearm = 1.8;
    int totalmass = 12404;
    int batterymass = 720;
    int buoyancymass = 4401;
    int batteryposition,wheelweight;
    boolean mySwitch = false;

    void calc() {
      batterymoment = input*batterymass;
      totalmoment = 149650+batterymoment;
      buoyancymoment = buoyancymass*centrebuoyancy;
      wheelmoment = totalmoment - buoyancymoment;
      wheelweight = totalmass - buoyancymass;
      cgwheels = wheelmoment/wheelweight;
      maindistance = mainarm - wheelweight;
      nosedistance = wheelweight - nosearm;
      mainmass = (((wheelweight)*(1-((maindistance)/(maindistance+nosedistance))))/2);
      nosemass = (((wheelweight)*(1-((nosedistance)/(nosedistance+maindistance))))/2);
      mainmoment = mainmass*mainarm;
      nosemoment = nosemass*nosearm;
      netmoment = buoyancymoment+mainmoment+nosemoment;
      netcg = netmoment/totalmass;
      staticmargin = adc - netcg;
      answer = staticmargin/meanadc;
     }

    void setup() {
      Serial.begin(9600);
      num1=0;
      num2=0;
      Serial.println("Enter battery position");
     }

    void loop() {
      while (Serial.available()){
        batteryposition = Serial.read();
        if(batteryposition>47 && batteryposition<58){
          if(!mySwitch){
             num1=(num1*10)+(batteryposition-48);
          }else{
             num2=(num2*10)+(batteryposition-48);
            }
           }

    if(batteryposition==61){
      input=num1+num2;
      calc();
      Serial.print("Static margin is: ");
      Serial.println(answer);
      num1=0;
      num1=0;
      mySwitch=false;
      }
     }
    }

So depending on the user input, the calculations will change the final output answer. For example if a 5 should be entered the output should be -4.22 based on my calculations in excel.

body:
Per your comments, the calc() function is not acting as expected.

Change calc() to be:

    void calc() {
      Serial.print("input:");Serial.println(input);
      batterymoment = input*batterymass;
      totalmoment = 149650+batterymoment;
      buoyancymoment = buoyancymass*centrebuoyancy;
      wheelmoment = totalmoment - buoyancymoment;
      wheelweight = totalmass - buoyancymass;
      cgwheels = wheelmoment/wheelweight;
      maindistance = mainarm - wheelweight;
      nosedistance = wheelweight - nosearm;
      mainmass = (((wheelweight)*(1-((maindistance)/(maindistance+nosedistance))))/2);
      nosemass = (((wheelweight)*(1-((nosedistance)/(nosedistance+maindistance))))/2);
      mainmoment = mainmass*mainarm;
      nosemoment = nosemass*nosearm;
      netmoment = buoyancymoment+mainmoment+nosemoment;
      netcg = netmoment/totalmass;
      staticmargin = adc - netcg;
      answer = staticmargin/meanadc;
      Serial.print("answer:");Serial.println(answer);
     }

and see if it gets the expected inputs and works as expected.  Then add debugging statements in-process until you discover the mismatch.

I'd turn in into more of a function, or a series of better defined functions, and then test them individually.

As your code is there is interaction between global variables, serial parsing, and calculations.  If you break it into distinct pieces, you can isolate where the problem is.


body:
You're getting the same value every time because that is the value that is being calculated.

I think you have something wrong with how you have implemented your formula.  If you start from "answer = " and repeatedly substitute the variables with the formulae or values that make up those variables you end up with this:

> answer = (11.4 - (((4401 * 14.164) + ((((12404 - 4401)*(1-((14.3 - (12404 - 4401))/((14.3 - (12404 - 4401))+(12404 - 4401 - 1.8)))))/2) * 14.3) + ((((12404 - 4401)*(1-((12404 - 4401 - 1.8)/((12404 - 4401 - 1.8)+(14.3 - (12404 - 4401))))))/2) * 1.8)) / 12404)) / 22.65

There's nothing variable about that at all.

Your input value is being used to calculate `batterymoment`. `batterymoment` us being used to calculate `totalmoment`. `totalmoment` is being used to calculate `wheelmoment`. `wheelmoment` is being used to calculate `cgwheels`. **`cgwheels` is never used for anything**.


message:
Why does the Pro Mini 5 v and 3.3 v version have different clock frequencies?

It looks like the 5 volt version used the 16MHz external crystal while the 3.3V one uses the 8MHz crystal. I need to use 3.3v as my operating voltage.

Can I just remove the linear regulator and bring in 3.3V. I still have to select the 5V 16MHz version in the Arduino IDE, right?

https://www.arduino.cc/en/uploads/Main/Arduino-Pro-Mini-schematic.pdf

body:
The ATMega328p is not rated to operate at 16 MHz on a 3.3v supply.

In practice it may sometimes work, but cannot be considered reliable.

The data sheet will show the actual clock rate vs. voltage tradeoffs, so there might be an intermediate value that is workable for you.

The Arduino toolchain needs to know the CPU clock frequency for the serial baud rates, timing delay code, and any time-based use of the timer peripherals to come out right.

There is a special case where if the configured clock rate and the actual clock rate differ by a factor of two, you may be able to cover that by selecting a similarly wrong baud rate - however, the baud rate in the bootloader was set in comparison to the *expected* clock frequency when it was compiled before flashing, and the baud rate *expected* of the bootloader is set in the boards file, so less readily changed than it is in something like the serial monitor.


message:
Why does my PIR sensor stay high with ESP8266 breakout board?

I have a PIR sensor attached to a Amica nodeMCU board routing 5v from VIN and attached via USB port for testing. When motion is deteted it connects to the internet and sends data to IFTTT which i receive a notification on my phone.

When I power up, the PIR pauses for calibration and then immediately goes HIGH and fires the motion detected call which i receive on my phone. However From then on it never goes LOW but every 5-8 minutes sends another HIGH call through even if there is no motion.

**Testing**

- Tried using separate 5v supply to PIR same thing happens
- I have tried both retrigger modes (H & L) and experienced the same result
- The same happens with the Adafruit featherwing huzzah board.
- I have tested the PIR without a micro-controller and can confirm that it **functions correctly** *-lighting an led*
- I have tested with an Arduino Nano with the same code and it **functions correctly** *- lighting an led*

**My Code** modified version of [Arduino Playground PIR Project][1]

    //Sends IFTTT every 5 minutes it detects motion

    #include <ESP8266WiFi.h>
    //WiFi Settings

    // Set up macros for wifi and connection.
    #define SSID "my-network"    // SSID
    #define PASS "mypassphrase"      // Network Password
    #define HOST "maker.ifttt.com"  // Webhost
    //-------------------------------
    const char* streamId   = "test";
    const char* privateKey = "mysecretkey";

    //PIR Settings
    //the time we give the sensor to calibrate (10-60 secs according to the datasheet)
    int calibrationTime = 10;

    //the time when the sensor outputs a low impulse
    long unsigned int lowIn;

    //the amount of milliseconds the sensor has to be low
    //before we assume all motion has stopped
    long unsigned int pause = 5000;

    int  interval = 1000; // Wait between dumps
    boolean lockLow = true;
    boolean takeLowTime;
    int ledPin = 1;
    int pirPin = 2;    //the digital pin connected to the PIR sensor's output
    int nPIR_detect;
    int motion = 2;

    int minSecsBetweenUpdates = 300; // 5 minutes
    long lastSend = -minSecsBetweenUpdates * 1000l;
    //-------------------------------

    // Begin Setup
    void setup(){
      Serial.begin(115200);
      pinMode(pirPin, INPUT);
      digitalWrite(pirPin, LOW);

      //give the sensor some time to calibrate
      Serial.print("calibrating sensor ");
      for(int i = 0; i < calibrationTime; i++){
        Serial.print(".");
        delay(1000);
        }
      Serial.println(" done");
      Serial.println("SENSOR ACTIVE");
      delay(50);
       nPIR_detect = 0;

      // Test ESP8266 module.
      Serial.println("AT");
      delay(5000);
      if(Serial.find("OK")){
        connectWiFi();
      }
    }

    void loop(){
     if(digitalRead(pirPin) == HIGH){
           digitalWrite(BUILTIN_LED, HIGH);   //the led visualizes the sensors output pin state
           if(lockLow){
             //makes sure we wait for a transition to LOW before any further output is made:
             lockLow = false;
             Serial.println("---");
             Serial.print("motion detected at ");
             Serial.print(millis()/1000);
             Serial.println(" sec");
             sendData(String(motion));
             delay(50);
             }
             takeLowTime = true;
           }

         if(digitalRead(pirPin) == LOW){
           digitalWrite(BUILTIN_LED, LOW);  //the led visualizes the sensors output pin state

           if(takeLowTime){
            lowIn = millis();          //save the time of the transition from high to LOW
            takeLowTime = false;       //make sure this is only done at the start of a LOW phase
            }
           //if the sensor is low for more than the given pause,
           //we assume that no more motion is going to happen
           if(!lockLow && millis() - lowIn > pause){
               //makes sure this block of code is only executed again after
               //a new motion sequence has been detected
               lockLow = true;
               Serial.print("motion ended at ");      //output
               Serial.print((millis() - pause)/1000);
               Serial.println(" sec");
               delay(50);
               }
           }
    }

    void sendData(String motion){

      //Send the motion to IFTTT value1
      Serial.print("connecting to ");
      Serial.println(HOST);

      // Use WiFiClient class to create TCP connections
      WiFiClient client;
      const int httpPort = 80;
      if (!client.connect(HOST, httpPort)) {
        Serial.println("connection failed");
        return;
      }

      // We now create a URI for the request
      String url = "/trigger/";
      url += streamId;
      url += "/with/key/";
      url += privateKey;
      url += "?value1=";
      url += "motion";

      Serial.print("Requesting URL: ");
      Serial.println(url);

      // This will send the request to the server
      client.print(String("GET ") + url + " HTTP/1.1\r\n" +
                   "Host: " + HOST + "\r\n" +
                   "Connection: close\r\n\r\n");
      delay(10);

      // Read all the lines of the reply from server and print them to Serial
      while(client.available()){
        String line = client.readStringUntil('\r');
        Serial.print(line);
      }

      Serial.println();
      Serial.println("closing connection");

    }

    boolean connectWiFi(){
      Serial.println("AT+CWMODE=1");
      delay(2000);
      String cmd="AT+CWJAP=\"";
      cmd+=SSID;
      cmd+="\",\"";
      cmd+=PASS;
      cmd+="\"";
      Serial.println(cmd);
      delay(5000);
      if(Serial.find("OK")){
        Serial.println("Connection");
        return true;
      }
      else{
        Serial.println("No Connection");
        return false;
      }
    }

OQ: Why does my PIR sensor stay high with ESP8266 breakout board?

*In essence, I never see the serial message "motion ended at.."*

  [1]: http://playground.arduino.cc/Code/PIRsense

body:
I have the same issue with Huzzah and a PIR. The PIR is noisy and I get a false high every 10-20s while the code runs without any problem on an UNO.
I think it is a problem of HF coupling from wifi interfering with the PIR's amplification circuit. I will try shielding and caps/ferrites to get rid of the HF on the PIR or use another power supply and couple the signal line via optocoupler.


body:
I'm sure you have probably done both these, but just in case you haven't...

I see from your code you are using Pin 2 for the PIR sensor.  I'm sure your not as dumb as I am every time I program a ESP8266, but check you have connected the PIR to pin 2, that's not the connection labelled D2 its GPIO2, which may or may not be labelled.

Assuming that's right then the next possible problem may be that GPIO2 is shared with TXD1, its possible that this is being used.  So try moving to GPIO4.


body:
The solution I found to this problem is use a 10k resistor between the PIR sensor output and the input pin of the ESP8266.

Not sure if 10K is the best value, someone else may find a better value, but for now, for me its working great.

John


message:
434 RF Transmitter and Receiver for distance measurement problem

As a student I'm working on a project where we use 434 MHz RF Transmitter and receiver pairs for distance measurement. I know that this technology is not a good choice for this, but we have to deal with this problem due to external constraints.

Here is the receiver: [RF Link Receiver - 4800bps (434MHz)][1].

I did a little bit of research how these receivers works, but I found it a bit overwhelming to understand them bit by bit.

We want to use the signal strength for distance measurement. So we tried sending pulses of signals from one transmitter to a receiver. If the amplitude of the signal received is higher than a certain value (let's say 3V), it sends back a signal (let's call it trigger signal) in the gap between the two pulses.

The problem is that that these signals seems to affect each other even though they are not in the same time (so it's not superposition that we are talking about). When there is a signal sent back, the next pulse will be lower, which results in false distance measurement.

The whole difficulty is (to me it seems) that we are not using these signals to send data, we are using it for distance measurement. My idea is that we are using too long pulses and the AC coupling in the receiver doesn't tolerate it, but again, I don't have enough electrical knowledge to safely say that.

I know this is not descriptive, but I don't know how to make it more descriptive, so I'm happy to answer more questions on demand.

  [1]: https://www.sparkfun.com/products/10532

body:
It is very likely you have an AGC problem. Try to slow down the measurement. The sender shall send data not often than once per second.

This idea is not fully perfect for doing a distance measurement. It measures incoming power strength - affected by walls, reflection, AGC of the receiver, and a lot more. If you have a scope, measure the waveform on the pin 3 of the module (linear out). It is not a constant voltage, I am afraid, so you need some sort of averaging too.

A tricky way to get along even if you have an AGC is to measure how long the AGC needs to settle. The AGC works as follows: it detects the signal, and within some time (say, 2ms) it will change the amplification so that the signal will look having the full amplitude.

 * compare on a two channel scope the signal pulse driving the transmitter
 * and the signal on the pin 3 of the receiver module

If you are lucky, you'll see that actually pin3 or pin2 output is delayed a bit compared to the transmitter driving pulse. The delay depends on the power of the incoming signal to the receiver, which depends on the distance.

I was able to make an acceptable distance sensor from a standard AGC enabled IR receiver using the principles above.


message:
Digit LED has single input, multiple outputs for each segment. Concerns about "sinking" 5v supply into digital pins

The model name is 5161BS

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/0oNbq.png

Pins 3/8 are input and the rest are output for each individual segment.

I have connected pin 3 to the 5v pin on the Arduino, and the rest to individual digital pins.

With a simple sketch with the pins set to mode output, all segments are lit.

My concern is that the way I am turning off each segment is by setting the output pin to high.

Meaning

    5v pin --> LED <-- Digital pin

Is this dangerous to have two voltage sources going in the same direction? Is there another way to do this?

body:
This is called a common-anode LED. The anodes (+ side) are shared. They probably dedicate two pins (3 and 8) to share the current to the anodes.

Connecting the common anode to +5V is fine. However you *should have* current-limiting resistors between each of the other pins (the cathodes) and the Arduino digital pin. Otherwise you are getting the Arduino to try to "sink" its own 5V supply through a digital pin, which far exceeds its rating. You will probably damage the output driver MOSFETs and they will stop working. Plus the excessive current will damage the LEDs as well.

See the [LED resistor calculator](http://led.linear1.org/1led.wiz). Something like a 330 ohm resistor, in series with *each* of the cathodes, should be adequate.

Now, setting the digital pins to output will "sink" 10 mA or thereabouts from +5V, through the LED (which lights up) and through the digital pin to ground.

You control what "number" you see on the LED by turning off the appropriate pins, to make the segments light up.

Also see [The care and feeding of LEDs](http://www.thebox.myzen.co.uk/Tutorial/LEDs.html).


body:
The device you have is a common anode display. This means that the anodes (+ve terminals) of all the LEDs are connected to one common pin (well, 2 pins actually, pin 3 and 8 are connected internally) . Their cathodes (-ve terminals) are what make up the remaining pins. Now, to light up any LED, you need 5 V at its anode and GND at its cathode. You have connected 5 V to pin 3, which stands for the common anode of every LED, so all that is left for any LED to turn on, is for you to connect GND to its corresponding cathode. So when you made all the remaining pins (the cathodes) OUTPUT, by default the Nano sets those pins to a logic LOW (or GND) value, so ALL the LEDs got lit up. Each LED now has `5 - 0 = 5 V` across its terminals and is forward-biased.

However, when you write HIGH to any cathode, the potential difference across the associated LED/segment is now zero, because that LED has 5 V at its anode (pin 3/8) and 5 V at its cathode (as a result of writing HIGH), and `5 - 5 = 0 V` so it is reverse-biased (at least 2 V or thereabouts is needed for a red LED to become forward-biased) and so the segment turns off. And this is how you control which segment is on at any time: You write a LOW to a cathode to turn on the associated segment, and write HIGH to turn it off. It sounds counter-intuitive but it follows if you think about it. Regarding your question, there's no damage being done to anything; the minimum voltage across the LED is 0 V (well below its maximum peak inverse voltage), while the maximum voltage across the LED is around 2 V, if you use the **highly recommended** current-limiting resistors (220/330 ohms is good) in series between each cathode and its Arduino digital pin.

Without any resistors, you will be drawing a lot of current through each pin, in total, a lot more than the Nano can safely supply. Use resistors that limit the current through each LED to 10-20mA.


message:
Attach headers to servo wires?

I have these 3 wires coming from a servo motor. They're very thin and flimsy and despise staying in a breadboard.

[![enter image description here][1]][1]

Is it possible to add headers to these wires to make them easier to put in a breadboard? (Like the attached image) And if so, where would one procure such a thing?

[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/htu5c.jpg
  [2]: https://i.stack.imgur.com/Uz1Hn.jpg

body:
What I do in situations like that is get some of those breadboard hookup wires, like you have in your second photo, cut them in the middle (giving yourself two wires, each with a bare end, and a end with a plug on them).

Strip the bare end, and then solder it to the servo motor wires. Before commencing soldering, slip some heat-shrink tubing onto the wire. Once the wires are soldered together, move the heat-shrink tubing over the join and shrink it (with a hair-dryer, or heat gun).

You now have a plug for your breadboard which is designed to be mechanically strong, and the heat-shrink tubing over the join protects it from being flexed too much.

You could put some thicker heat-shrink over all three wires, to give additional stability.


body:
I have bought a crimping tool. With the correct dice and crimps and crimp holders you get a professional finish.
The crimps and crimp holders themselves are cheap (buy in multiples of 100) but the crimping tool and dice are expensive.
It takes some practise before you make "high quality good contacting crimp" connections. You need to crimp in such a way that the strength comes from the connection between the wire insulation and the crimp and not loose electrical contact.

Also it is not so easy to find the "correct" crimps and crimp holders.
So this is only an option if you are willing to invest in your hobby (or you know someone who has ;-) )

If it is a DIY job I would go with nick solution.


message:
DS18B20 Temperature Sensor return as float function returning null 50% of the time

I just got an DS18B20 Temperature sensor and am trying to modify the example code to use a function instead. Below is my `getTemp` function. It's working but returning results with a 0 value part of the time for example:

> Temperature = 72.39
> Temperature = 0.00

If I add `Serial.print(fahrenheit);` within the function I am always provided with the correct temperature. I though this may have to do with needing a delay but adding `delay(5000);` in my loop didn't help.

I'm assuming it's something simple I'm not understanding about how `floats` return.

    #include <OneWire.h>

    // OneWire DS18S20, DS18B20, DS1822 Temperature Example
    //
    // http://www.pjrc.com/teensy/td_libs_OneWire.html
    //
    // The DallasTemperature library can do all this work for you!
    // http://milesburton.com/Dallas_Temperature_Control_Library

    OneWire  ds(2);  // on pin 10 (a 4.7K resistor is necessary)

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

    float getTemp(char tScale) {
      byte i;
      byte present = 0;
      byte type_s = 0;
      byte data[12];
      byte addr[8];
      float celsius, fahrenheit;

      if ( !ds.search(addr)) {
        ds.reset_search();
        delay(250);
        return false;
      }

      ds.reset();
      ds.select(addr);
      ds.write(0x44, 1);        // start conversion, with parasite power on at the end

      delay(1000);     // maybe 750ms is enough, maybe not
      // we might do a ds.depower() here, but the reset will take care of it.

      present = ds.reset();
      ds.select(addr);
      ds.write(0xBE);         // Read Scratchpad

      for ( i = 0; i < 9; i++) {           // we need 9 bytes
        data[i] = ds.read();

      }

      // Convert the data to actual temperature
      // because the result is a 16 bit signed integer, it should
      // be stored to an "int16_t" type, which is always 16 bits
      // even when compiled on a 32 bit processor.
      int16_t raw = (data[1] << 8) | data[0];
      if (type_s) {
        raw = raw << 3; // 9 bit resolution default
        if (data[7] == 0x10) {
          // "count remain" gives full 12 bit resolution
          raw = (raw & 0xFFF0) + 12 - data[6];
        }
      } else {
        byte cfg = (data[4] & 0x60);
        // at lower res, the low bits are undefined, so let's zero them
        if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
        else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
        else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
        //// default is 12 bit resolution, 750 ms conversion time
      }
      celsius = (float)raw / 16.0;
      fahrenheit = celsius * 1.8 + 32.0;
      if (tScale == 'C') {
        return celsius;
      }
      else if (tScale == 'F') {
        return fahrenheit;
      }

    }
    void loop(void) {
        Serial.print("Temperature = ");
        Serial.println( getTemp( 'F' ) );

    }

Edit:
Interesting enough, adding an `if` statement to the loop fixes this, however. I'd still like to understand what is going on:

    void loop(void) {
      if ( getTemp( 'F' ) == 0 ){
        Serial.print( "Temperature = " );
        Serial.println( getTemp( 'F' ) );
      }
    }

body:
You have intermittent communication problems.

Your address search occasionally fails and `getTemp()` returns false. In C++ (and many other languages) false will be implicitly cast to `(int) 0`, `(float) 0.0f`, and so on.

Your `getTemp()` function  also is difficult to debug because the multiple return statements have different meaning.

After the `delay(250);` you do a `return false;` in order to skip the rest.

In the example at https://www.pjrc.com/teensy/td_libs_OneWire.html the meaning of the `return` statement(s) is different. There the return happens within the `void loop()` function, where it simply means to interrupt the current execution (without returning a value) and continue with the next loop.

While it is generally okay to have multiple `return`, it can sometimes be problematic and I recommend to avoid it.

If you want to clean this up while still preserving the ability to detect a fault, you have a couple of options (order from most to least recommended):

 - do the setup/checking in a different function (and only call the second one if the first one succeeded), i.e. `if (isReady()) { Serial.println(getTemp()); }`
 - set a separate error variable, i.e. `error = true; return 0;` (and then check `error` later)
 - define a 'default' value that you interpret as an error (and never expect to be a temperature), i.e. `return NAN; // not a number`


message:
Send JSON via POST on SIM900 shield with AT commands

I'm trying to send a JSON POST in SIM900 shield with AT commands. After I call the  **AT+HTTPACTION=1** command, it returns a 601 error: **+HTTPACTION:1,601,0**.

I saw here that the error was 601 Network Error. Could someone help me? Following is my code.

    void connectInternet() {
      if(digitalRead(9 != LOW)) {
        Serial.print("\r\n");
        Serial.print("------------------------------------------------- \r\n");
        Serial.print(" CONNECT ON INTERNET \r\n");
        Serial.print("------------------------------------------------- \r\n");
        Serial.print("\r\n");
        Serial.println("Connecting...\r");
        cmdAT("AT");
        cmdAT("AT+CIPSHUT");
        cmdAT("AT+CIPMUX=1");
        cmdAT("AT+CSTT=\"zap.vivo.com.br\",\"vivo\",\"vivo\"");
        cmdAT("AT+CIICR");
        cmdAT("AT+CDNSCFG=\"8.8.8.8\",\"8.8.4.4\"");
        Serial.print("IP Device: ");
        cmdAT("AT+CIFSR");
      }
    }

    void send2Api() {
      Serial.print("\r\n");
      Serial.print("------------------------------------------------- \r\n");
      Serial.print(" SEND TO API\r\n");
      Serial.print("------------------------------------------------- \r\n");
      Serial.print("\r\n");
      cmdAT("AT+CSQ");
      cmdAT("AT+CGATT?");
      cmdAT("AT+SAPBR=2,1");
      // Query if the connection is setup properly, if we get back a IP address then we can proceed
      cmdAT("AT+HTTPPARA=\"CID\",1");
      // Set the HTTP session.
      cmdAT("AT+HTTPPARA=\"URL\",\"http://api.com.br/endpoint\"");
      // set endPoint
      cmdAT("AT+HTTPPARA=\"CONTENT\",\"application/json\"");
      // set content json
      cmdAT("AT+HTTPDATA=100,5000");
      // POST session start
      // JSON payload
      cmdAT("{\"timestamp\":\"2016-03-08T19:36:45.000Z\",\"latitude\":\"-24.9458581\",\"longitude\":\"-53.4968357\"}");
      delay(100);
      cmdAT("AT+HTTPACTION=1");
      // POST session start
      cmdAT("AT+HTTPREAD");
      // Read the data of HTTP server
      cmdAT("AT+HTTPTERM");
      // terminate http
      ShowSerialData();

body:
The PDP context setup is missing from your code. Many years ago I figured out that this initialization sequence works (i.e. extend your connectToInternet):

   //--if autobauding was enabled, send a blank AT
   command:='AT';
   send_gprs;

   //--switch to minimal mode - this is required to reset the SIM card
   command:='AT+CFUN=0';
   send_gprs;

   //--set dce speed
   command:='AT+IPR=57600';
   send_gprs;

   //--turn off command echo
   command:='ATE0';
   send_gprs;

   //--turn off command echo again - sometimes the first command is ignored
   command:='ATE0';
   send_gprs;

   //--turn on extended error messages
   command:='AT+CMEE=1';
   send_gprs;

   //--set module to full function
   command:='AT+CFUN=1';
   send_gprs;

Then it is very important to unlock your SIM card. The simplest solution is to disable PIN request (put your SIM to a real phone, and use the phone to set up this.) Verify if the module can proceed on SIM authorization:

   //--check pin
   command:='AT+CPIN?';
   send_gprs;
   //--right answer is +CPIN: READY
   //--wrong answer is +CME ERROR: 772

Then set up the APN. This will actually initiate an asynchronous APN request, and you shall not proceed until the AT+CSTT returns OK:

  repeat
   //--reset connection
   command:='AT+CIPSHUT';
   send_gprs;

   //--set GPRS APN
   command:='AT+CSTT="internet.vodafone.net"';
   send_gprs;
  until is_ok=1;

And finally, open a GPRS connection:

  repeat
   //--Open gprs connection
   command:='AT+CIICR';
   send_gprs;

   //--Get local address - for some reason this is required
   command:='AT+CIFSR';
   send_gprs;

         //--Suppress "SEND OK" after at+cipsend
         command:='AT+CIPSPRT=2';
   send_gprs;

  until is_ok=1;

(Ok sorry, this code is pascal and not especially golden, but you got the point about the sequence of the commands.)

Two very important things:

* any command can fail - it is a good idea to send back the response to an AT command to your console window
* AT+CIFSR is evil. If you don't use AT+CIFSR at the right sequence, the communication simply does not work. I was using SIM900D modules. Although you might feel it is optional to get your IP, actually it is not optional at all for some reason.

I was using AT+CIPSEND for the actual data communication. HTTP is so easy, and it is better to be in control.


message:
How do I learn C? (was Computer project)

Can you help me writing a code for this question guys??
You have an Arduino Uno with 8 LEDs connected to digital pins 2 to 9.
Create an array of 8 elements. Fill it with random numbers between 2 and 9 (all inclusive)
Write a program which determines the greatest number among them. Save this number in a variable named max. Print this number on serial monitor. Blink the LED connected to this number. Let the delay time be 0.5 second.

Note that the random function may result in duplicate numbers generated. For example, the generated array may be {3,4, 4, 7,6, 2,5,7}

The maximum number will be 7.Since it occurred twice in the array, then you should blink it twice ^_^
It the maximum number occured 3 times in the array, then you should blink it 3 times, and so for any number of occurrences

I have written this so far but I'm sure it's all wrong

    int pins[8]={2, 3, 4, 5, 6, 7, 8,9};

    void setup()
    {
       pinMode(pins[8], OUTPUT);
    }

    void loop()
    {
        x=random(0, 8);
        digitalWrite(pins[x], HIGH);
        delay(1000)
        digitalWrite(pins[x], LOW);
        delay(1000)
    }

body:
First hint: pinMode() only applies to one pin at a time. You'll need to execute it 8 times to intialize 8 I/O pins' modes.

Second hint: As @ChrisStratton tried to suggest, generate the random number set first; then "figure out" (set some variables in memory that will tell you) what do with the terminal output and the digital I/Os; then do each of those things. It helps to partition a larger problem into smaller ones.

Update: Considering your updated title, _How do I learn C?_, and since the question reads like a homework assignment, aren't you already taking a class in C or C++? If so, how do you find it lacking, i.e., what additional resources or direction would be most helpful to you? There are a number of good books on the C language, and one of those would be a good place to start. If you don't already have a favorite one, you can't go wrong with _The C Programming Language_, by Brian Kernighan & Dennis Ritchie, the authors/designers of the C language and its early compilers. It is book on the C language, not on programming per-se, so if you are new to programming as well, a programming tutorial would be an excellent additional choice (sorry I don't have one to recommend).

Secondly, beat up on the example programs that come with the ArduinoIDE: click the "Open" button [uparrow icon on the IDE toolbar; not the File | Open menu] and you'll see a menu of your current sketches and, below the break, categories of example programs. Pick one of the examples, read it and try to understand what it does and why it is written the way it is. Then tweak the ###p out of it - both to understand how make it behave differently, and to **break** it. You'll learn a lot by a) interpreting error messages from the compiler, and b) finding and fixing your mistakes. If you're not breaking your programs at least twice as often as you're succeeding, you're not trying hard enough!


message:
Problem reading an EEPROM chip using the I2C protocol

I am trying to read an EEPROM chip that supports the ***I2C*** protocol (cannot tell the IC model number as it is not printed). For sure it supports the I2C protocol, since I wrote a code to detect it using the I2C library and the device address I got it return is ***0x51***. Now I am trying to write a code that reads data from this IC chip. The code is as follows:

    #include <Wire.h>

    int addr = 0;

    void setup() {
        Wire.begin(); // initialise the connection
        Serial.begin(9600);
        while (!Serial) {}
        delay(100);
    }

    void loop() {
      byte deviceAddress = 0x51;
      byte data = readData(addr, deviceAddress);
      Serial.print(data, HEX);
      Serial.print(" ");
      addr++;
      if(addr == 0) {
         Serial.print('\n');
      }
      // check for 1Kbits first
      if (addr8 == 0) {
         Serial.println("round complete");
         Serial.println();
         addr = 0;
      }
      delay(100);
    }

    byte readData(int address, int deviceAddress) {
      // sending device address
      Wire.beginTransmission(deviceAddress);
      Wire.write(address);
      Wire.endTransmission();
      Wire.requestFrom((short int)deviceAddress, 1);
      if(Wire.available()) {
        byte data = Wire.read();
        return data;
      }
      return 0xAA; // random data
    }

The problem I am facing is, I get back the address (from which I want to read the data) as the data itself (For e.g. read(0) returns 0, read(1) returns 1 and so on). I even tried to debug the I2C communication using the logic analyzer (Saleae logic in this case). A screenshot is shown below.

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/u1W9F.png

The screenshot shows the logic for a read operation from a single address (0x78), but the story holds for each and every address i.e. I get back the address instead of the data from the address.

The output of the above code is as follows:

> 0 1 2 3 4 5 6 7 8 9 A B C D E F

> 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F

> 20 21 22 23 24 25 26 27 28 29 2A 2B 2C 2D 2E 2F

> 30 31 32 33 34 35 36 37 38 39 3A 3B 3C 3D 3E 3F

> 40 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F

> 50 51 52 53 54 55 56 57 58 59 5A 5B 5C 5D 5E 5F

> 60 61 62 63 64 65 66 67 68 69 6A 6B 6C 6D 6E 6F

> 70 71 72 73 74 75 76 77 78 79 7A 7B 7C 7D 7E 7F

> round complete

Can you help me identifying what possibly I am doing wrong here?

Thanks.

body:
Without the specific chip info this will be difficult.

However, my experience with EEPROMs and I2C is that the first action is to write a command, then write the parameter(s) for that command, then read the response.

Often, there is a status register in the EEPROM that needs to be read (by writing a command, then reading the response) to determine if the EEPROM is ready to receive a different command, like writing to set the address for a read/or/write, then the actual read command.


body:
You need to pass the address as two bytes, one by one.

Do not do:

    Wire.write(address);

Rather, do:

    Wire.write((uint8_t)(address >> 8)); // MSB
    Wire.write((uint8_t)(address & 0xFF)); // LSB


body:
In short, you should split

    Wire.write(address);

into

    Wire.write((int)(eeaddress >> 8)); // MSB
    Wire.write((int)(eeaddress & 0xFF)); // LSB

I am working on a similar project right now. I have searched through many different codes and libraries and found the following to work the best:
https://playground.arduino.cc/Code/I2CEEPROM

I am using the 24LC1025 who's datasheet can be found here:
http://www.microchip.com/datasheet/24LC1025

I am using the 1Mb version and it uses 0x51 and 0x50 becuase it has two pages. I suspect you will find your chip to at least be similar because of the I2C Address you listed. You may have a smaller version of the same chip that only uses the one address.


message:
I need help purchasing components for my Arduino project

I am a newbie on this hardware stuff. I need help on purchasing the components

**Brief description of my project**

I need a device that would remotely detect weight or pressure when somebody push on it and send the info to the webserver or websockets. The device could be located up to 300 ft.

After doing some research on it I learned that I need, arduino uno as the device main platform, xbee for wireless communication with the web, xbee shield for the xbee and Force sensitive resistor sensor to detect small weight or pressure.

**Question**

*First am I correct above mentioned components would solve what I am trying to do? If not what am I missing? Anything I mis-stated?*

*I have learned that there are stuff like xbee explorer, Arduino stackable headers, break-away headers, and breadboard. Do I really need these?*

*In the future I want to be able do other experiments with the board like use ultrasonic sensor with it or infrared sensor to detect objects. Will I need to buy anything specific to make these sensors compatible with the board or they are all standard?*

Basically I want to buy everything I need in one shot. Thank you in advance. Any help will be appreciated.

body:
I would rather go with ESP8266. You can program that from the Arduino IDE. You don't need anything else than a programming cable (an USB-UART adapter), and you can connect the force sensor to the analog input with one pullup resistor.

There is a similar idea with one button here:
https://www.hackster.io/noelportugal/esp8266-ifttt-easy-button-888a87

You can build your own force sensor:
http://www.todayifoundout.com/index.php/2010/01/how-to-make-a-ridiculously-cheap-analog-pressure-sensor/

If you don't really need to measure the force, there are much easier solutions to detect weight of a person. These give a simple contact once pressed, and can be used like a button (see the first link in my answer).
http://learning.media.mit.edu/projects/gogo/documents/making sensors.html#Paper and Aluminum foil.

It is not really possible to buy everything as one batch :) I would say you need:

* connection wires
* plyers
* some cheap multimeter
* you may wish to power your device from a battery, so you may need a battery holder and batteries
* battery voltage may not be a perfect match for ESP8266, so you might want to get a board with internal regulator, such as https://www.adafruit.com/products/2471
* it is handy to start with a breadboard with jumper wires, something like https://startingelectronics.org/beginners/start-electronics-now/tut1-breadboard-circuits/building-cct-step5.jpg

I suggest you to find an ESP8266 based tutorial, Adafruit has a lot of those, and then you'll have an understanding about the tools and components needed.

If you buy some Arduino, consider buying the ones using 32u4 chip, such as Arduino Leonardo or Arduino Micro. The 32u4 chip has more memory, and more performance than the original Arduino Uno, plus it can work as an USB mouse or an USB keyboard too.

For infra (do you mean a PIR which detects humans, or a reflective sensor?) you have quite a lot of possibilities. In case of using ESP8266 directly, check that the sensors work on 3.3V. Some stuff works on 5V, others on 3.3V. You can interface them easily, but this is just another extra thing to cover, so better go with a dedicated 3.3V sensor.

Ultrasonic sensors are coming also in a lot of varieties. Do you need something ridiculously cheap? A sensor with a short range? A sensor with a longer range? I think you have to set up your goal first.

The Leonardo and Uno and Micro boards work both with 5V and 3.3V sensors. Driving these sensors are quite standard, you need to power them with two wires, and have one wire which goes from 0V to 5V (or vice versa) when something is detected. Ultrasonic sensors vary: there are sensors with one analog output, giving a voltage between 0V and 5V propoprtional to the distance. However most of ultrasonic sensors are simple as the ultrasonic principles: they have one input what you drive, and will give one output of the recived echo signal. In this case you have to measure the time elapsed between the drive signal and the echo, which depends on the distance of the object from the sensor.


message:
Tower Pro MG996R 180° high torque servo controlling using Arduino

We are trying to control a robotic arm using the *Tower Pro MG 996R 180°* high torque servo.

Firstly we tried to power the servo from Arduino's default 5V, but it didn't work, then we power it from an external source, the servo ran, but only in one direction. Then it stopped rotating. We used the sweep code from the Arduino examples to test the motor.

Here's the code:

<!-- language: c -->

    #include <Servo.h>

 Servo myservo;  // create servo object to control a servo
 // twelve servo objects can be created on most boards

 int pos = 0;    // variable to store the servo position

 void setup() {
   myservo.attach(9);  // attaches the servo on pin 9 to the servo object
 }

 void loop() {
   for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
  // in steps of 1 degree
  myservo.write(pos);              // tell servo to go to position in variable 'pos'
  delay(15);                       // waits 15ms for the servo to reach the position
   }
   for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
  myservo.write(pos);              // tell servo to go to position in variable 'pos'
  delay(15);                       // waits 15ms for the servo to reach the position
   }
 }

Can anyone please specify what are we doing wrong, and what is the right way to do it.

body:
The Arduino's 5V is hardly enough for driving servos. I found that even a simple 9g micro servo draws well over 1A spikes, which causes the board to reset itself.

* Power the servo from an external battery pack (e.g. 3xAA or 4xAA batteries will do);
* Ensure that the GND of the battery pack is connected to the GND of the servo *as well as* to the GND of the Arduino;
* So you'll have two wires between the Arduino and the motor: GND and the driving signal.

It has to work, servos are pretty standard stuff. *However* there are many complaints against this particular type at this link [Towerpro MG996R 10kg Servo 10kg / 0.20sec / 55g][1].

  [1]: http://www.hobbyking.com/hobbyking/store/__6221__Towerpro_MG996R_10kg_Servo_10kg_0_20sec_55g.html


body:
Si no me equivoco tiene 64 pasos. El servo no deberia ir de grado en grado sino por c/u de los 64 pasos. 180 grado / 6r es 3 grados x cada cambio de paso step to step. ?
Atte.

If I'm not mistaken in 64 steps. The servo should not go from grade to grade but by c / u of the 64 steps. 180 degree / 6r is 3 degrees x each step change step to step. ? Atte.


message:
Smallest digital 3-axis gyroscope pcb for arduino?

What is the smallest size digital 3-axis gyroscope pcb compatible with an arduino that I can buy or maybe make if its simple enough. I need one really really tiny probably around 0.8x0.1x0.5 (doesn't have to be that small but the smaller the better).

Thanks,

body: Bosch CNO055 chip is an IMU-Cortex combo capable of outputting 3-D coordinates directly in several formats via several data interfaces. Adafruit has a product based on this chip, along with Arduino library (the CNO055 is in the middle to get you an idea about minimum size) -> https://www.adafruit.com/products/2472.


body:
smallest board is no board.  pick a small BGA or LGA shaped accelerometer and superglue it face down to the arduino board then solder fine wires beween the chip terminals and arduino terminals.

search digikey for 'spi accelerometer'


body: Arduino accesories are generally large because they are meant to be easy to use. mpu-6050 is a good example and you can find many decent breakout boards for it. But if you really want it to be very small, you should consider a custom solution for your problem like designing a PCB that holds both the microcontroller and the accelerometer.


message:
Problems coding a 12 pin 7 segment display and grove temperature sensor with Arduino Uno

I am trying to code my 12 pin seven segment display to display the temperature from my grove temperature sensor. I am new to this and I have been struggling, so if anyone could help that would be much appreciated.

My temperature sensor is displaying its information in the serial monitor, however I want the temperature displayed with the 7 segment display - that's where I need help.

    //Temperature Variables
    //thermistor = value of the thermistor
    int a;
    float temperature;
    int thermistor=3975;
    float resistance;
    boolean DigitOn = LOW;
    boolean DigitOff = HIGH;
    boolean SegOn=HIGH;
    boolean SegOff=LOW;

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

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

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

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

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

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

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

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

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

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

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

body:
You loop over the segments. For each segment you set the output high, then pull the digit output low for each digit that should have that segment lit.

The big issue I see is that you turn the digits off immediately after turning them on. The digits are on for only a few processor cycles. If you delay for a few ms before turning all the digits off, you'll probably see them better.

The usual way I've seen this code written, and written it myself, is to loop over digits in the outer loop and set all the segments for one digit at once. You're setting all the digits for one segment. The way you do it, if the display is showing all 8s with decimal points, each segment will be on 1/8 of the time. If you loop over digits, each segment will be on 1/4 the time, and the display will be brighter. Looping over digits lets you illuminate up to 8 segments at once instead of 4.

Finally, doing this with digitalWrite is very inefficient. If you connect the segments to digital ports 0-7 you can set them all simultaneously by writing a byte to PORTD.


body:
The *simple* way is to use a MAX7219 chip which does most of the work for you.

You haven't said what LED device you have but an example of wiring it is:

[![MAX7219 wiring][1]][1]

That chip does the multiplexing for you. I have a detailed description [here](http://www.gammon.com.au/forum/?id=11516).

If you don't want to use another chip you could use 12 of your Arduino pins. It's a little tedious because you need to be refreshing the display even while you are doing other things. You could use a timer interrupt for that.

The code you posted looks like it might work. In what way does it not work?

>  I have been struggling ...

That doesn't tell us much. Do all segments light up? None? Incorrect ones? Does it flicker? What is the problem exactly?

Please read [How do I ask a good question?](https://arduino.stackexchange.com/help/how-to-ask)

  [1]: https://i.stack.imgur.com/T6DXN.png


body:
Your temp sensor is obviously working if it displays the temp on the serial monitor. I would now write a new sketch, forgetting the temp sensor for the moment, and get numerical data on to the seven segment display correctly.

How many digits does the seven segment display have? What interface are you using, if any? How is the display connected to the Arduino? You need to provide the information in your question, to allow us to give you an accurate answer.

You may want to take a look at my answer to [Programming 4-digit seven segment display using interrupts only][1] on SE Robotics. I had the same issues, about a year ago, when I was trying to display data on a cheap seven segment display that I purchased in BKK, and I ended up writing an Arduino library in order to get it to work, see [Dual Seven Segment Display Madness][2]. However, I don't recommend that you write your own library, and instead use a pre-built one. Take a look at the [SevenSeg library](http://playground.arduino.cc/Main/SevenSeg). That is what I used eventually.

I see that you are using some code from the [SevSeg library][3], but you do not appear to include the header `SevSeg.h` in your sketch. If you are happy using the SevSeg library, then first write a sketch using the examples and the tutorials, so that you can get data displayed. Then integrate that software with your temperature sensor software.

You really do need to divide your project into two parts, the sensor and the display. Once you are happy with displaying data on the Seven Segment display, *then*, and only *then* can you think about getting the temperature sensor data displayed on it.

  [1]: https://robotics.stackexchange.com/questions/9218/programming-4-digit-seven-segment-display-using-interrupts-only#answer-9221
  [2]: https://gr33nonline.wordpress.com/2015/08/04/dual-seven-segment-display-madness/
  [3]: http://playground.arduino.cc/Main/SevenSegmentLibrary


message:
How to convert string to long?

There is `String.toInt()`, but no `String.toLong()` or the many other variations. Do I have to resort to `atol(String.c_str())` or is there a better way to convert a `String` to a long?

body:
Using `atol(String.c_str())` looks OK to me. If there was a `String.toLong()` it would be written that way anyway.

In fact, looking at the code for `String.toInt()` that's exactly what it does:

    long String::toInt(void) const
    {
     if (buffer) return atol(buffer);
     return 0;
    }

So the answer is: use `String.toInt()`.


body:
So the answer is: use String.toInt().

Probably not, as this is the definition of a String method:

long String::toInt(void) const

The real work is:

atol(buffer);

ASCII to long.


message:
Using AVR Timer Within an ISR

I'm trying to create an ISR which operates for 15 seconds when a particular button is pressed. I'm attempting to use the AVR functions on my Arduino Uno to start counting when it enters the ISR, then quit the loop when it reaches 15 seconds.

I'm having difficulty reasoning out where the counter is actually stored that I want to use for my while loop.

Here is my code so far:

    #define button_pin 2
    #define duration 15
    #define osc_in 0

    #include <avr/io.h>
    #include <avr/interrupt.h>

    const float convert = 5.0/1023.0;

    void setup() {

      TCCR1A = 0;
      TCCR1B = 0;
      TCNT1 = 0;
      attachInterrupt(digitalPinToInterrupt(button_pin), button_interrupt, CHANGE);

      sei();

      pinMode(button_pin, INPUT);
      Serial.begin(9600);
    }

    void loop() {
        //int channel1 = analogRead(osc_in);

    //while (millis() < 10000)
      //Serial.println(millis());
      //Serial.println(channel1 * convert);
      //channel2 = channel1;
    }

    void button_interrupt(){
      //(# timer counts + 1) = (target time) / (timer resolution)
      //int timer_counts = duration/(pow(6.4, -5));
      //int dur = 234374;
      OCR1A = 234374;
      TCCR1B |= (1 << CS10);

      while (????????){
        int channel1 = analogRead(osc_in);
        Serial.println(channel1 * convert);
      }
    }

body:
Don't do delays inside an ISR. Don't do serial prints inside an ISR. Read [this](http://www.gammon.com.au/interrupts).

You need to redesign. The ISR can set a flag, that you then test in `loop`. Do the delay in `loop`.


message:
I am planning to do a periodic table with Arduino's help but I have a few questions

I'm doing that for my school project, but I have few questions before I purchase the components.

First of all, let me explain how it will work:

There will be 4x20 LCD, an Arduino and probably two potentiometers (due to the potentiometer's sensitivity). When the user turns the potentiometers, the program adds the first potentiometer's value to the other potentiometer's value, because of sensitivity issues. Then the program checks which element corresponds to the two potentiometers' values.

After that, the program shows that element's information in the LCD (like its name, symbol, neutron number, proton number, valence electrons, ...).

Questions:

 - There are around 118 elements in the periodic table. I'm not an expert with programming, but this means there will be 118 `if ... else if ...` statements. I can shorten the inside of the `if` statement by function, but there will be still 118 `if` statements. I'm afraid it will be over the memory (sketch size limit) limit of the Arduino. How can I shorten the code?

 - Should I buy a Mega or will a Uno be enough?

 - Will there be any problems if I connect a 5V Arduino pin to both potentiometers and 4x20 backlight? If not, how can I fix this? I don't want to use any other power source except Arduino.

body:
You probably don't need a Mega for this, but think about it as a long term investment if you want to keep messing around with the Arduino/move on to bigger projects.

Unfortunately, typing all the code out will be quite tedious. But you can make separate arrays for strings of all the element names:

https://stackoverflow.com/questions/1088622/how-do-i-create-an-array-of-strings-in-c

And you can make corresponding arrays for all of the numerical data.

Then you take the signal, do some math to figure out how you can use the signal to obtain an integer from 1-118, write that into an integer (say i), and then write name[i], symbol[i], neutnum[i], and so on to the LED screen.

The hardest part will be doing math so that the transition between two elements in terms of turning the potentiometer feels natural.

Note that if your math somehow generates 200, then name[200] will most likely write random values from memory to your LED screen. I think. If your LED screen is displaying nonsense, then that is what you should look at/debug first.


body:
Rather than manually putting all of the periodic-table data into a program in just the right form (which would be quite tedious), you could use a program on your software development computer to read periodic-table data files and create the corresponding C-program data structures.

The python program shown below gives an example of that approach.  (It contains a data table in a list of tuples, ie doesn't read data; but data like that in the tuples *can* be read from a file, or with a bit of programming, from a [spreadsheet of periodic-table data](http://www.meta-synthesis.com/webbook/35_pt/pt_database.php?PT_id=194).)

The python program opens file `datatables.data.c` for output, then it writes C statements into that file, which subsequently can be added into a sketch, `datatables.ino`, as shown later.

# Python program, `densconmelt.py`:

<!-- language: lang-py -->

    #!/usr/bin/python
    # From data as shown in slide 19 of 39 at
    # http://www.slideshare.net/bravetiger1964/lecture-11-metals-and-its-alloys-their-crystalline-structure-and-properties

    # Physical Properties of several Metals and Alloys.
    #   Metal or Alloy
    #     Density (kg/m3)
    #       Thermal conductivity W/(m*K) (t=20 C)
    #         Melting point (Tm) (C)
    adtm = [
        ('Aluminum', '2712', '204', '659'),
        ('Aluminum alloys', '7700-8700', '120-180', '462-671'),
        ('Brass-casting', '8400-8700',  '',  '990-1025'),
        ('Red Brass',     '8746', '159', '1027'),
        ('Yellow Brass',  '8470', '115', '930'),
        ('Bronze - lead', '7700-8700', '',  '850-1000'),
        ('Copper', '8930', '385', '1083'),
        ('Gold', '19320',  '318', '1063'),
        ('Pure iron',     '6800-7800', '72', '1530'),
        ('Cast Iron',     '7850', '', 'Gray 1370, Malleable 1360, White 1370'),
        ('Wrought Iron',  '7750', '58', '1450'),
        ('Lead',  '11340', '35.3', '327'),
        ('Nickel', '8800', '89', '1453'),
        ('Silver', '10490', '406', '961'),
        ('Solder 50/50 Pb/Sn', '8885', '', ''),
        ('Non-alloyed and low-alloy steel', '7850', '53.6', '1480'),
        ('Stainless Steel', '7480-8000', '12.11-45.0', '1430-1500'),
        ('Tin',  '7280', '63', '232'),
        ('Zinc', '7135', '115', '419')
        ]

    locs = []
    # To track current offset into datatext, and longest single string part
    used = longy = 0
    with open('datatables.data.c', 'w') as fo:
        fo.write('#ifdef ADDTABLE  // Disallows separate compile\n')
        fo.write('const char datatext[] PROGMEM = \n  ')
        for i in adtm:
            #a, d, t, m = i
            #print '{:20} {:12} {:12} {:12}'.format(a, d, t, m)
            for x in i:
                locs.append(used)
                used += len(x)+1
                longy = max(longy, len(x)+1)
                fo.write('"{}\\0" '.format(x))
            fo.write('\n  ')
        fo.write(';\nconst int offsets[] = {')
        for o in locs:
            fo.write(' {},'.format(o))
        fo.write(' {}{};\n'.format(used, '}'))
        fo.write('enum {} LONGSTR={}, ITEMS={}{};\n'.format('{', longy, len(adtm), '}'))
        fo.write('char buffy[LONGSTR];\n')
        fo.write('#endif\n')

Note, the out-commented lines

            #a, d, t, m = i
            #print '{:20} {:12} {:12} {:12}'.format(a, d, t, m)

would be an appropriate place to modify the python program so it prints out how the lines will look when displayed on the 4x20 LCD.  Rather than repeatedly downloading files to your Uno or Mega just to fix lines that are a little too long, or misaligned, etc., you could make the python program show the display appearance in the same loop where it generates data structures to be included in the Arduino sketch.

Note, if you aren't familiar with the `with` construct, see the *With Statement* section of pythonforbeginners.com's [Reading and Writing Files in Python](http://www.pythonforbeginners.com/files/reading-and-writing-files-in-python) page.

#What the Python program generates:

Some lines from the file generated by `densconmelt.py` are shown below, interspersed with comments about what those lines do.  Later, the whole of the file `datatables.data.c` is shown.

    #ifdef ADDTABLE  // Disallows separate compile

That line is a preprocessor statement to keep `datatables.data.c` from being compiled alone.  During compilations, the Arduino IDE will copy `datatables.ino` and `datatables.data.c` into a temporary work directory and will compile each of them.  However, the body of `datatables.data.c` won't compile correctly alone (outside the sketch), so is guarded from causing compile errors by surrounding it with `#ifdef ... #endif` lines.

    const char datatext[] PROGMEM =

That line tells the C compiler to store the value of `datatext[]` into program memory.  It also says the value and content of `datatext` are constant, and `datatext` is an array of characters.

      "Aluminum\0" "2712\0" "204\0" "659\0"
      "Aluminum alloys\0" "7700-8700\0" "120-180\0" "462-671\0"
      "Brass-casting\0" "8400-8700\0" "\0" "990-1025\0"
    ...
      "Tin\0" "7280\0" "63\0" "232\0"
      "Zinc\0" "7135\0" "115\0" "419\0"
      ;

Those lines each give the name of a metal or alloy, its density, its thermal conductivity, and its melting point.  Values are strings instead of numbers, so ranges and missing values can be handled.  Note that by rules of C, strings with no operators between them concatenate together.  For example, the line `"Tin\0" "7280\0" "63\0" "232\0"` is equivalent to the line `"Tin\07280\063\0232\0"`.  Note, each `\0` is a null character at the end of a substring.  If space were short, one could leave out all the `\0`s and compute string lengths as differences of adjacent entries in `offsets[]`.

    const int offsets[] = { 0, 9, 14, ... 524, 528, 533, 538, 542, 546};

That line tells where each substring begins, within the big string  `datatext`.  This method of storing offsets and substrings takes 12 bytes per item, ie 4·2 bytes for 4 `int` values plus 4 bytes for null characters.  There are half a dozen ways to reduce the overhead to 5 to 10 bytes per item, but the most effective simple change would be to put `offsets[]` in PROGMEM.  In addition, one might change some fields from strings to integers or floats, which would not need null separators or offset values if placed at fixed offsets at the front of an item's record.

    enum { LONGSTR=38, ITEMS=19};
    char buffy[LONGSTR];
    #endif

Those lines create two constants, LONGSTR and ITEMS, telling the length of the longest substring and the number of items; allocate a buffer, as long as the longest substring; and close the guarding `#ifdef ... #endif`.

#`datatables.data.c`, shown whole:

<!-- language: lang-c -->

    #ifdef ADDTABLE  // Disallows separate compile
    const char datatext[] PROGMEM =
      "Aluminum\0" "2712\0" "204\0" "659\0"
      "Aluminum alloys\0" "7700-8700\0" "120-180\0" "462-671\0"
      "Brass-casting\0" "8400-8700\0" "\0" "990-1025\0"
      "Red Brass\0" "8746\0" "159\0" "1027\0"
      "Yellow Brass\0" "8470\0" "115\0" "930\0"
      "Bronze - lead\0" "7700-8700\0" "\0" "850-1000\0"
      "Copper\0" "8930\0" "385\0" "1083\0"
      "Gold\0" "19320\0" "318\0" "1063\0"
      "Pure iron\0" "6800-7800\0" "72\0" "1530\0"
      "Cast Iron\0" "7850\0" "\0" "Gray 1370, Malleable 1360, White 1370\0"
      "Wrought Iron\0" "7750\0" "58\0" "1450\0"
      "Lead\0" "11340\0" "35.3\0" "327\0"
      "Nickel\0" "8800\0" "89\0" "1453\0"
      "Silver\0" "10490\0" "406\0" "961\0"
      "Solder 50/50 Pb/Sn\0" "8885\0" "\0" "\0"
      "Non-alloyed and low-alloy steel\0" "7850\0" "53.6\0" "1480\0"
      "Stainless Steel\0" "7480-8000\0" "12.11-45.0\0" "1430-1500\0"
      "Tin\0" "7280\0" "63\0" "232\0"
      "Zinc\0" "7135\0" "115\0" "419\0"
      ;
    const int offsets[] = { 0, 9, 14, 18, 22, 38, 48, 56, 64, 78, 88, 89, 98, 108, 113, 117, 122, 135, 140, 144, 148, 162, 172, 173, 182, 189, 194, 198, 203, 208, 214, 218, 223, 233, 243, 246, 251, 261, 266, 267, 305, 318, 323, 326, 331, 336, 342, 347, 351, 358, 363, 366, 371, 378, 384, 388, 392, 411, 416, 417, 418, 450, 455, 460, 465, 481, 491, 502, 512, 516, 521, 524, 528, 533, 538, 542, 546};
    enum { LONGSTR=38, ITEMS=19};
    char buffy[LONGSTR];
    #endif

#Sketch to get item data from program memory and display it:

We've used `densconmelt.py` to generate `datatables.data.c` as above, and now will show a sketch that gets an item's data out of program memory and displays it, whenever the sketch receives an item number via Serial input.

    // Sketch that accepts a number via serial input, and responds with
    // two lines of data via serial output.  The reply-data consists of an
    // Alloy name on the first line, and Density, Thermal conductivity,
    // and Melting point on the next line.

    // See http://arduiniana.org/libraries/streaming/ for Streaming library
    #include <Streaming.h>
    // This sets up datatext in PROGMEM; offsets[]; buffy; LONGSTR; ITEMS
    #define ADDTABLE
    #include "./datatables.data.c"

    void setup() {
      Serial.begin(115200);         // init serial port
    }

    void loop() {
      Serial << "Please enter item number from 1 to " << _DEC(ITEMS) << ": ";
      int item = 0;
      while (1) {
        while (!Serial.available()) {}; // Wait for a character
        int c = Serial.read();
        if (c == '\n') break;
        item = 10*item + c - '0';
      }
      if (item < 1 || item > ITEMS) {
        Serial << item << endl << item << " is out of range -- try again.\n";
        return;
      }
      // Display specified item's title on first line
      strcpy_P(buffy, datatext + offsets[item*4-4]);
      Serial << item << endl << "Item #" << item << ", " << buffy << endl;
      // Show other data items on next line
      strcpy_P(buffy, datatext + offsets[item*4-3]);
      Serial << "Density " << buffy;
      strcpy_P(buffy, datatext + offsets[item*4-2]);
      Serial << "   Thermal cond. " << buffy;
      strcpy_P(buffy, datatext + offsets[item*4-1]);
      Serial << "   Melt@ " << buffy << " C" << endl << endl;
    }

Note, for a description of `strcpy_P()` arguments, see nongnu.org's **[avr/pgmspace.h : Program Space Utilities](http://www.nongnu.org/avr-libc/user-manual/group__avr__pgmspace.html)** page.

See arduino.cc's [PROGMEM](https://www.arduino.cc/en/Reference/PROGMEM) page for a cursory overview of PROGMEM.

See avrfreaks.net's [GCC and the PROGMEM Attribute](http://www.avrfreaks.net/forum/tut-c-gcc-and-progmem-attribute?page=all) page for detailed coverage of PROGMEM, and see Nick Gammon's [Putting constant data into program memory (PROGMEM)](http://www.gammon.com.au/progmem) page as well.

#Example of program output, as in Serial Monitor box:
Following is an example of program output as shown in the Serial Monitor box after I typed several numbers into the input line and pressed enter after each.   (Note, at the bottom of the Serial Monitor box, set Line Ending to `Newline` and data rate to 115200 bps.)

    Please enter item number from 1 to 19: 18
    Item #18, Tin
    Density 7280   Thermal cond. 63   Melt@ 232 C

    Please enter item number from 1 to 19: 19
    Item #19, Zinc
    Density 7135   Thermal cond. 115   Melt@ 419 C

    Please enter item number from 1 to 19: 20
    20 is out of range -- try again.
    Please enter item number from 1 to 19: -2220
    -2220 is out of range -- try again.
    Please enter item number from 1 to 19: 2
    Item #2, Aluminum alloys
    Density 7700-8700   Thermal cond. 120-180   Melt@ 462-671 C

    Please enter item number from 1 to 19: 0
    0 is out of range -- try again.
    Please enter item number from 1 to 19: 5
    Item #5, Yellow Brass
    Density 8470   Thermal cond. 115   Melt@ 930 C

    Please enter item number from 1 to 19:

The sketch echoes the user-input item number twice, so it appears at the end of each input solicitation as well as in line labels like “Item #5, Yellow Brass”.


body:
i think you might have to buy a mega(probably more expensive!)

i also fear someone putting countless nights into coding (preferably on pc for me, because 1: sketch is only available as an ancient version on raspberrypi. & 2: easier transfer of code.)


body:
Expanding an answer from my comment on your question:

First thing is to define a struct that holds all the data you want to
store and display for one element:

<!-- language-all: lang-c -->

    struct Element {
        char symbol[3];
        char name[16];
        float mass;
        char electronic_state[9];
        // etc...
    };

Do not store the atomic number, as it will be deduced from the index on
the array you will build. Each string in this struct (symbol, name...)
should be big enough to store the longest possible string, including the
final NULL terminator. The compiler will help you here: if you do not
allocate enough room, it will later say something like “_error:
initializer-string for array of chars is too long_”.

It is obviously somewhat inefficient to allocate each string the maximum
possible length. I suggest you do this for the sake of simplicity, and
because I do not think you should be short on flash, even on an Uno. If
you really end up being short on flash, then I suggest you seriously
consider jwpat7's answer. It is somewhat complicated, but likely to be
significantly more efficient than mine in terms of flash usage.

Second step is to write down the periodic table as a PROGMEM array:

    const Element periodic_table[] PROGMEM = {
        // symbol  name    mass      electronic state
        {"H",  "Hydrogen", 1.008,    "1s1"     },
        {"He", "Helium",   4.002602, "1s2"     },
        {"Li", "Lithium",  6.94,     "[He] 2s1"},
        // etc...
    };
    const size_t table_length = sizeof periodic_table / sizeof *periodic_table;

Then your program will only have to browse through this table in order
to get the needed information. The only tricky part here is that you
will have to copy the data to RAM before using it, for example with
something like:

    Element elt;  // element in RAM
    memcpy_P(&elt, &periodic_table[i], sizeof elt);

I do not have an LCD, so I wrote a test program that simply dumps the
table through the serial port:

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

    void loop()
    {
        Serial.println(F("Z  Symbol  Name  Atomic mass  El. state"));
        Serial.println(F("---------------------------------------"));
        for (size_t i = 0; i < table_length; i++) {
            Element elt;  // element in RAM
            memcpy_P(&elt, &periodic_table[i], sizeof elt);
            Serial.print(i+1);  // Z = i+1
            Serial.print(F("    "));
            Serial.print(elt.symbol);
            Serial.print(F("     "));
            Serial.print(elt.name);
            Serial.print(F("  "));
            Serial.print(elt.mass);
            Serial.print(F("  "));
            Serial.println(elt.electronic_state);
        }
        Serial.println();
        delay(1000);
    }

This program only takes 4480 bytes of flash. This means I could expand
the table to 118 elements and over 200 bytes of data per element before
running out of flash on an Uno.


message:
What will happen if I supply greater than 1.1V to analogue inputs if analogReference set to INTERNAL?

I am reading a 50Hz AC voltage using the analogue inputs.

If I set the analogReference() to INTERNAL, meaning 1.1V on the Arduino Uno, what will happen if a voltage greater than 1.1V is supplied to the pin? Will the board be damaged? If not, what value will the ADC give?

body:
You will read 1023.

The limit of the voltage is not the reference voltage but the chip supply voltage - so 5v on a 5v board.


message:
Problem: "stray '#' in program"

I got a sketch from the internet [(http://www.instructables.com/id/How-to-build-an-8x8x8-LED-cube-and-control-it-with/)][1] for controlling the display of an 8x8x8 LED cube. The program won't compile and the error says "stray '#' in program". I looked it up on google but nothing appears to be relevant.
Here's a part of the code. (The error occurs at the `baseColor = color(#222222);` line)

    int rectX, rectY;      // Position of square button
    int ROWX, ROWY;
    int rectSizeX = 80;     // Width of rect
    int rectSizeY = 20;     // Height of rect
    int circleSize = 20;   // Diameter of circle
    color rectColor, circleColorOff, circleColorOn, baseColor;
    color rectHighlight, circleHighlight;
    color circleCurrentColor;
    color rectCurrentColor;
    boolean rectOver = false;

    // State of LEDs
    boolean[][] circleOn;

    // Position of LED buttons
    int[][] circlePos;

    // Mouse Over LED buttons?
    boolean [][] circleOver;

    int delayedby = 50;

    void setup() {
     //number of rows and columns
     ROWX= 8;
     ROWY= 8;

     size((ROWX*40+10), (ROWY*44+30));
     noStroke();
     frameRate(10);
     smooth();
     rectX = ROWX*20-30;
     rectY = ROWY*44+5;

     // Colors
     rectColor = color(#FF0000);
     rectHighlight = color(#FFFF00);
     circleColorOff = color(#444444);
     circleColorOn = color(#ff0000);
     circleHighlight = color(#CCFF00);
     baseColor = color(#222222);
     circleCurrentColor = circleColorOff;
     rectCurrentColor = rectColor;

    circleOn = new boolean[ROWX][ROWY];
    for(int i=0; i<=(ROWY-1); i++) {
     for(int j=0; j<=(ROWX-1); j++) {
       circleOn[j][i] = false;
        }
    }
    circlePos = new int[2][(ROWX*ROWY+1)];

    // X Posistions
    for(int i=0; i<(ROWX*ROWY-(ROWX-1)); i=i+ROWX) {
    int Xpos = 25;
      for(int ii=0; ii<ROWX; ii++) {
         circlePos[0][i+ii] = Xpos;
         Xpos += 40;
      }
    }

    // Y Positions
    int Ypos = 40;
     for(int i=0; i<(ROWX*ROWY-(ROWX-1)); i+=ROWX) {
      for(int ii=0; ii<ROWX; ii++) {
         circlePos[1][i+ii] = Ypos;
      }
            Ypos += 40;
     }

    circleOver = new boolean[ROWX][ROWY];
    for(int i=0; i<=(ROWY-1); i++) {
     for(int j=0; j<=(ROWX-1); j++) {
       circleOver[j][i] = false;
     }
    }
    }

It turns out that the code was compiled in the earlier beta versions of the Arduino IDE, and now I don't know what I need to do for it to be compiled by my 1.6.5 version.

  [1]: https://www.instructables.com/How-to-build-an-8x8x8-LED-cube-and-control-it-with/

body:
From the Instructable you linked:

> matrix8x8.pde is a program in Processing to build your own displays.

You downloaded the **Processing** code, not the **Arduino** code. See above that:

> cube8x8x8.pde is the *Arduino code*.

So basically you are compiling the wrong code. Go back and re-read that page.


message:
Send commands to Arduino from the WEB

I need to send Arduino some instructions from the web. Basically I would have a web app with a few buttons, and when I press them they send an instruction to Arduino to move for example a motor or turn a lamp. This has to function remotely, so not locally.

I'm using an Arduino Yùn.

How should I do this? Websocket? How? Thanks!

body:
It becomes lots easier if you see the yun as a linux computer with a arduino connected over serial.
Then the question becomes: what is the best way to send commands over the internet to a (linux) computer.
Answer: there are so many ways because there is no best way.
What are the main key drivers:
Your linux computer needs to be reachable from the internet. That means opening your local network(firewall). The firewall is there for a reason. Do you have the skills to open your firewall and still be safe? If so you can run a service (lots of options) and reach your yun from anywhere on the internet. Just as you do locally.

If not you will need to go to a polling system. You use a server which is on the internet and send you request to that server. Your yun polls that server to get the messages you send.

There is a third option: If you can open your firewall from the internet, and you are the only user of the service and you very rarely need the service you can temporarily open the firewall when you need it
.


body:
Another option, if you can be limited to controlling your device from a mobile app, is [blynk.cc][1]. They provide mobile apps for Android and iOS, that let you build a control panel via drag-and-drop, and embedded platform libraries for Arduino, standalone ESP8266, RPi, and others, that talk both ways between the app and your embedded device, as well as between devices.

The embedded devices and the mobile apps communicate as clients to their servers (or to your server, if you choose to host the open-source server code) so you don't have to open any ports on your router or firewall.

You won't have the full freedom (or requirement!) of designing custom web-pages; but OTOH, you can be up and running with their example code in a few minutes.

I have a couple of room-temperature monitors on my desk that can report the temperature (plus history) to me anywhere I can get a web connection. I put two buttons on my panel to turn on, or blink, 2 LEDs on the board. With my feet up on the hearth I control the LEDs. There are slider-controls that can talk to the PWM ports as well. All the capabilities you need are there, at least to get started.

  [1]: http://blynk.cc


body:
The simplest way to do this would be to host a webpage with the buttons on the Yùn itself, like for example [this here][1]. There are loads of examples for stuff like this out there.

To access it "remotely" - I presume you mean from anywhere on the internet - you would have to forward a port from your home router to the Yùn, [like this][2]. This will make the Yùn accessible from the internet. You only have to know your outside address (Google: "Find my IP") and then you can access your arduino from all over the world.

  [1]: http://www.instructables.com/id/Arduino-Webserver-Control-Lights-Relays-Servos-etc/?ALLSTEPS
  [2]: http://www.pcworld.com/article/244314/how_to_forward_ports_on_your_router.html


message:
Problem with ATtiny85 and RF modules

I am doing a project on a ATtiny85 which involves using 433MHz RF modules. Whenever I want to compile any sketch using the Manchester library I always get these errors : "Manchester library doesnt support your microcontroller". Could anyone help me solving this?

body: If you are using arduino IDE, only limited functions are supported for the ATtiny85, and if that library requires some of the function from the IDE (Probably Serial), then it will not work. There are few solutions: 1, use an atmega Chip; 2, get another library; 3, write your own code.


body:
Somehow I got it working. I don't know the cause of the problem but in order to fix it I had to Arduino 1.0 IDE; use [this][1] ATtiny support and [this][2] Manchester library. Thank you all for your help.

  [1]: https://code.google.com/archive/p/arduino-tiny/
  [2]: https://github.com/mchr3k/arduino-libs-manchester


message:
Arduino onboard LED pin number as a constant

To use the onboard LED on an Arduino one usually has to know the pin number (13 in most cases), but is there a constant in the Arduino IDE one can use as well?

So is it possible to use something like `int LED = ONBOARDLED;` instead of using `int LED = 13;`?

body:
Try `LED_BUILTIN`:

    pins_arduino.h:static const uint8_t LED_BUILTIN = 13;


body:
> `#define LED_BUILTIN 13`

([source](https://github.com/arduino/Arduino/blob/435fc323e0ab3b03bc5835e5309b5022bf57388a/hardware/arduino/sam/variants/arduino_due_x/variant.h#L97))


message:
Can't compile my library because "String does not name a type"

I am writing a small library to move some code out of the arduino sketch and make it reusable. Problem is that it does not compile since "String does not name a type".

This is my code (reduced):

myESP.h:

    #ifndef MYESP_H
    #define MYESP_H

    #include "Arduino.h"

    #include <String>

    #include <ESP8266WiFi.h>
    #include <ESP8266WiFiMulti.h>
    #include <WiFiClient.h>
    #include <WiFiClientSecure.h>
    #include <WiFiServer.h>
    #include <WiFiUdp.h>

    class myESP {
        private:
            const char* _ssid;
            const char* _password;
            const char* _host;
        public:
            myESP();
            myESP(char * ssid, char * pwd, char * host);
            String macToStr(const uint8_t* mac);
            String doGet(String data, String sensor, int duration);
    };
    #endif

myESP.cpp:

    #include <String>

    #include "Arduino.h"
    #include "myESP.h"

    myESP::myESP() {}

    myESP::myESP(char * ssid, char * pwd, char * host) {
        _host = host;
        _password = pwd;
        _ssid = ssid;
    }

    myESP::String macToStr(const uint8_t* mac) {
    }

    myESP::String doGet(String data, String sensor, int duration) {

    }

When i try to compile it, I get the following:

> /Users/lbedogni/Documents/Arduino/libraries/myESP/myESP.cpp:14:1:
> error: 'String' in 'class myESP' does not name a type  myESP::String
> macToStr(const uint8_t* mac) {
>
> /Users/lbedogni/Documents/Arduino/libraries/myESP/myESP.cpp:22:1:
> error: 'String' in 'class myESP' does not name a type  myESP::String
> doGet(String data, String sensor, int duration) {

I have tried to change the order of the imports, change libraries, but still it does not compile.

Any idea?

body:
Your syntax is wrong in myESP.cpp. Change this:

    myESP::String macToStr(const uint8_t* mac) {
    }

    myESP::String doGet(String data, String sensor, int duration) {

    }

to this:

    String myESP::macToStr(const uint8_t* mac) {
    }

    String myESP::doGet(String data, String sensor, int duration) {

    }

The return type is `String` and the function implementation should be prefixed with the class name `myESP::`. Obviously, you also need to fill in the body of the implementation or you'll get more errors because you don't actually return anything.


message:
Programming Arduino in Pascal?

My question is simple: there is any Pascal or Pascal-class (FPC, Delphi, mikroPascal) programming language for Arduino?

Preferably (I hope I don't ask too much) that language should not be older than 10 years.

----

Update:
Let's not start a flame war about "why the xxx programming language is so much better Pascal" and keep focus on the core of this question. I know that Pascal has it flaws (nothing its perfect, right?). I accept them and I still want to use it :)
Many thanks.

body:
Not Pascal, but Ada, which is much less restrictive than Pascal while enjoying the same advantages over low-level programming, and much more actively supported with language revisions as recently as 2012 and the formally provable SPARK language, for when you need your code to work.

Any processor which gcc supports can potentially support Ada, whose Gnat compiler is fully part of gcc.

That's not the whole story because you also need run-time system support for Ada's facilities, but for the Arduino's AVR processor there is a well established environment in the form of the [AVR-Ada project][1].

It generates nice tight little executables, you'll be amazed how much less space simple Gnat executables take compared to Arduino ones - unless you've already made the same comparison between Arduino and C ... which after all uses the same gcc compiler.

For ARM-based Arduinos (Arduino Due at least) the same is possible, though the support is newer and possibly less well established, see [the Cortex-GNAT project][2].

Leaving the Arduino, Ada has also been demonstrated on the [MSP430 processor][3] - my own project, sadly neglected at the moment.

  [1]: https://sourceforge.net/p/avr-ada/wiki/Home/
  [2]: https://sourceforge.net/projects/cortex-gnat-rts/?source=directory
  [3]: https://sourceforge.net/projects/msp430ada/?source=recommended


body:
> Is it possible to program Arduino in Pascal?

The answer is yes and no. The answer is yes because it is possible to port the [p-code][1] virtual machine to Arduino and compile for that.

The answer is no if extending the question with "is there a supported open-source Arduino/AVR IDE for Pascal available?"

There are a few commercial AVR/Pascal products. You can easily web-search them.

Last, a possible short-cut is to use [p2c][2], a Pascal to C translator, as a pre-processor in the Arduino IDE. There are hooks in the Arduino build for adding additional tools.

Cheers!

  [1]: https://en.wikipedia.org/wiki/P-code_machine
  [2]: https://schneider.ncifcrf.gov/p2c/


body:
A [Pascal front-end][1] to the Gnu compiler collection (gcc, on which nearly all the of AVR programming is based) already exists. Therefore, a Pascal compiler for AVR exists in principle if not in fact (and I don't know that it doesn't). I'd start by getting in touch with the folks working on the GPC to find out what has already been done.

  [1]: http://www.gnu-pascal.de/gpc/h-index.html


body:
There's also pascal p5c at sourceforge --> https://sourceforge.net/projects/pascal-p5c/

It uses gnu c as intermediate code so should work on any platform where gcc is available.