text:
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%16 == 0) {
     Serial.print('\n');
  }
  // check for 1Kbits first
  if (addr%128 == 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.

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.

How about using a 16-bit address? Here is a link to a driver that I have written for Cosa; https://github.com/mikaelpatel/Cosa/blob/master/libraries/AT24CXX/AT24CXX.hh

How many legs (pins) does the chip have?

I agree with Mikael too, you could try sending a 16-bit address. For example, send a zero first, then an address. In any case, can you be certain that the chip does not happen to have 0x00, 0x01, etc. inside its memory?

@MikaelPatel: I will give a try with 16-bit address and let you know what the results are.

@NickGammon: Just to make sure that the contents are not 0x00, 0x01, etc. I tried to perform a write operation to the chip. But the result for reading after a write, remains the same. Maybe I have to try using 16-bit addresses as you suggested as well.

@NickGammon: I tried using the 16 bit addresses, but to no success. The data I got in return is all zeroes. Maybe because now I am getting back the first 8 bits which I am writing, i.e. 0x00. I was also looking at the I2c library that you suggested in your blog. http://dsscircuits.com/articles/arduino-i2c-master-library. Can you help me in understanding, what exactly is registerAddress here? Its used in many functions of this library, for.e.g.I2c.write(address, registerAddress, *data, numberBytes). Thanks!

It depends on the device, but some have a register where writing something to it causes internal bits to be set. Honestly, trying to help write to / read from an unknown device is almost impossible. For $5 you could buy a chip that you know the part number of and can get the datasheet for.

Ahh OK. I was doing a reverse engineering project and the chip is in fact a COB. I have to then decap it somehow and see underneath. Thanks anyways.

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

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.

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.


text:
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.

Shopping questions are explicitly OFF TOPIC on this site.  Re-read the guidelines you were supposed to have read when you signed up.

@JRE- I apologize, Where do i have to re-direct this question to?

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%20sensors.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.

The ATmega32u4 does have some advantages, and the ability to run code directly on the ESP8266 can simplify projects too.  However, it might not be a bad idea for a beginner to have an absolutely ordinary Uno/Duemilanove type ATmega328p board on hand in order to be able to use peripheral example code without any changes - as working out what does have to change for other boards can take a little experience.

@Gee Bee Thank you very much. Do you think xbee should work for sending data to the internet(through websocket)? (I don't want to user ethernet because i want it to be wireless and i don't want to use wifi because it consumes lots of power.)

I am unsure how do you mean xbee. It is a form factor of various communication products from Digi, see http://www.digi.com/lp/xbee Unless you're using xbee wifi, you can't go to the internet with an xbee module alone. These modules are built to form an intellingent internal wireless network, but require a sort of a concentrator or network hub which has a wifi or ethernet connection if you want to go to the Internet.

You may not wish to rule out wifi just "because it consumes a lot of power". Any technology will consume a lot of power. The trick is to keep the communication interval at a minimum. In your case, the device can do nothing, and stay in deep sleep consuming 88uA when no humans are detected. The detection can wake up the module, the module will connect to an access point, send the data, and will consume 200-400mA for 1.5 seconds, then go back to sleep. Average current draw? It runs for 2 days on 2 AA batteries if you don't do sleep. If you do the sleep trick, it can run a year.

Oh wow i didn't know that.Thank you very much that was helpful.

source: Stack Exchange

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

sort: votes


text:
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:
#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.

Show how you have the servo connected to the Arduino.  Did you remember to connect the ground from the servo to the Arduino ground?

The default pulse width range for servo.write() is 544us to 2400us, which can overdrive some servos. Try limiting the range to 1~2ms with myservo.attach(9,1000,2000);

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.

These have a label with "towardpro"? Probably counterfeit, should return to shop immediately.

@Gee Bee we did exactly that, except instead of using battery pack, we used an external 5v dc power source. grounds are connected as you described, but its still rotates in one direction and stops rotating at a certain angle. however I can feel the motor running, but the shaft is not rotating... any suggestion ??
at_Paul... its "towerpro**" so I guess its not counterfeit....

Can you try to drive a simple standard model servo? That will rule out any problems of software and connections.
I found that even micro servos draw 1.5A spikes at start, so you need a very good 5V power source. A PC power supply would do, but an USB  charger is not. Although it sounds silly, give a try to the AA batteries. They provide much better transient responses than an off the shelf power supply. I had a project where servo anomalies drove me crazy - all caused by power supply glitches.

Thanks a lot bro... you are a life saver :D :D ... this time we powered the servo directly from computers USB, instead of external power supply.. and it WORKED :D really appreciate your help... and lesson learned... power can be brutally preposterous.

Good that it worked. Note that computer USB is a way too weak to power a brutal servo, sometimes I managed to trigger the short circuit protection of the PC just because of the sudden power draw of a servo can be huge. You may improve the situation a bit by connecting a 1000uF/10V electrolyt capacitor to the power pins of the servo connector, but I advise to use a dedicated power supply or a good battery with small internal resistance.

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.

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


text:
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,

How small you can make depends on your skills - what are they? You may find trouble finding a fab house that is willing to make such small boards - commonly 10mm² is a minimum size.

The recent invensense parts come in 3x3 mm QFN packages, you could probably put them on a 6mm x 6mm PCB - really the challenge would be getting the wires for the offboard connections to them.  If you want really small, put a QFN ATmega on the reverse side as your "Arduino" and make the board no bigger than that requires.  OSHPark should be able to make the board for you for around $1 each, and you can build it with solder paste and a $60 hot air station.

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'

That technique is known as Dead Bug.

@Jasen I meant gyro but I get what you mean. I found an example of a LGA shaped gyro here: http://www.amazon.co.uk/GYROSCOPE-3AXIS-2000DPS-L3GD20-STMICROELECTRONICS/dp/B018COVMAM/ref=sr_1_14?ie=UTF8&qid=1457819243&sr=8-14&keywords=LGA+gyroscope How big would that chip be?

Of course that ends up as big as the arduino - which by extension means you could do the same thing with substantially easier soldering by using a typical SMT part as sold on a breakout board (which is incidentally often cheaper than buying a single bare chip anyway)

@ChrisStratton  Yh of course but couldn't I solder some 0.35mm^2 wires to the IC chip so that I can mount it wherever I want and have an Arduino somewhere else?

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.

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.


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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.

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

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

I have been struggling ...

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

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


text:
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?

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().

Interesting. I wonder why they didn't just call it toLong()??

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.

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


text:
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);
  }
}

Doing serial inside an ISR is typically a bad idea.  Maybe consider doing your sampling continuously, and using an ISR to set a flag and initiate a 1-shot timer.  The the loop code could check the flag and do the 9600 baud serial reporting as needed.

Don't do delays inside an ISR. Don't do serial prints inside an ISR. Read this.
You need to redesign. The ISR can set a flag, that you then test in loop. Do the delay in loop.


text:
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.

Learn how to use arrays and PROGMEM. It's all on the Arduino Playground if you google it.

Look into switch-case instead of ifs

You should be able to store about 100 to 150 bytes per element on an Uno, as a PROGMEM array. That is more than a full page of your LCD. And you may want to use a rotary encoder instead of your two pots.

@Gerben: For this usage case, an array seems more appropriate, by far, than a long switch-case.

@EdgarBonet 10 turn 10kohm pot should do it too in my opinion. Can you give me a hint about where i should use arrays? and does the progmem store the array's data in normal memory (32kb) instead of ram?

The clue is in the word "PROGMEM"...

You define a struct that holds all the data of an element, then an array of 118 such structs can hold all the data you need. Your program then browses through the array to extract and print the data of the element chosen by the user. I can try to write a basic example showing how you could organize the data, but I will not have time before ~ 24h.

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:
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.

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.

thx for the answer, i will probably buy a incremental rotary encoder. But if i cant set up the R.E. i will go with pots. Arrays didn't come to my mind before, but now i understand that arrays will work better. I will buy mega, i found a cheap one (Non-Clone). Thx again

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.)
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:
#!/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 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 \0s 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:
#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 page.
See arduino.cc's PROGMEM page for a cursory overview of PROGMEM.
See avrfreaks.net's GCC and the PROGMEM Attribute page for detailed coverage of PROGMEM, and see Nick Gammon's Putting constant data into program memory (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”.

That's seems complicated. I got the idea but i don't know anything about python syntaxs, statements..., and i can't carry an external device except arduino. just the arduino and electrical components. Thx for the idea though

@ÇayÖncesi, the sketch uses Serial just for illustration – you would substitute a rotary encoder or a pot for input, and an LCD for output.  Even if you don't use a development-system preprocessor (with a code-generator written in python, C, or whatever language you prefer) you can organize your Arduino code in a manner similar to that illustrated.

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.)

i will buy mega, for this project and for future

Could you please explain why Mega would be a better choice?


text:
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?

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.


text:
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/) 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.

That is not C/C++ syntax. Replace # with 0x (to start with). Then you will have to reduce the size of the data structures. Check the sizeof(boolean).

I think this code is obsolete. I'm getting new errors like non existent data types and other syntax errors

Some of that looks more like java than C to me...

The code you have posted is a processing file, you haven't posted all the code and stated that its processing related, leaving it to the community to figure this out. This is more suited to stackoverflow or the Processing IDE

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.

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


text:
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!

You should send commands through a socket, yes. You can either make your own on your own port or you can just make HTTP requests (for instance GET requests). Just search for a tutorial that shows how to do it with a webpage, then discard all the webpage design and implement just the get pages. From the remote web app, then, call these pages. Or just make your own protocol

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
.

Another option, if you can be limited to controlling your device from a mobile app, is blynk.cc. 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.

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. 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. 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.


text:
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?

This isn't an electronics problem and has zilch to do with RF.

Sorry, I removed the tag now.

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 ATtiny support and this Manchester library. Thank you all for your help.

Could you share your code?

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.

Thank you for your answer. Your solution #1 I can not and do not want to use it, since I know it can be done on a ATtiny85; 2: I have tried multiple libraries but all of them give me errors.; 3: I do not have the knowledge to do this.

The problem originated from the fact that attiny chips lack the hardware UART that all atmega chips have, and the libraries that you have downloaded are probably written for the atmega chips using UART. SO, get the right library is the key; or use the atmega chip; or educate yourself with the knowledge and write your own code.


text:
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;?

#define LED_BUILTIN 13

(source)

Try LED_BUILTIN:
pins_arduino.h:static const uint8_t LED_BUILTIN = 13;


text:
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?

#include <String> - the IDE automatically includes the String type so you don't need this include.

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.


text:
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.

Because the usual Arduino environment is based on C++ you'd be best searching on "Pascal for AVR" which is the microcontroller used and it looks like there's a few options.

@PeterJ-Thanks. It seems I might have a chance to find some non-experimental or at least stable-enough Pascal language for Arduino

Perhaps Mikroelektronika has some compiler based on Pascal.

Why do you want to? Arguably, C++ is "Pascal-like". I used to program in Pascal heavily, and moved to C/C++ when it became obvious that most serious programming was done in those languages.

One day I will learn C as you recommend. Until then, my question is about Pascal. Many thanks for your recommendation anyway.

Brian W. Kernighan, Why Pascal is Not My Favorite Programming Language, http://www.threedee.com/jcm/psystem/whypascal.html

@MikaelPatel - WOW! I cannot believe people are are still quoting articles wrote at the dawn of programming era. ALL the drawbacks shown in the article are now gone. I think in '81 C had way more problems/drawback. C only got its ANSI standardization in '88. Come on Mikael, bring your knowledge up to date and quote a decent 201x article to clean your embarrassment. Pascal has evolved in billion ways since 1981 (see modern Pascal based languages such as FPC+Lazarus and Delphi)! Don't live in the past!

@Kenny How about you contributing with something? A quote, some code, testing to use what is available in main-stream, etc. So far I think you have not made any friends around here. There are many reasons for why Pascal has left main stream development and why most  embedded development use C/C++. We are a few that are trying to help you change focus. Obviously you can continue to look for an Arduino Pascal but it will be hard to find supporting libraries, drivers, etc.  Please see the bigger picture - live in the now :) :) :)

@MikaelPatel-Contributions related to programming / electronics are not really relevant if they point to some ancient article written back in 81.  I don't think that posting (as you) the first random link found on google is good for the community. So, instead of posting some random garbage I will refrain until I have something relevant for community.

@MikaelPatel-Thanks for the revenge downvote.  Please remember that the question is not "Why Mr. Patel hates Pascal" but "Is it possible to program Arduino in Pascal?". Answer THAT if you want to give something valuable to the community!

@Kenny Yes, we should focus on your original question. Please see my answer. The Pascal debate is very much off-track. Who cares why someone would want to do that. It is not relevant. You should get an answer to the question about using Pascal on Arduino.

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.
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.
Leaving the Arduino, Ada has also been demonstrated on the MSP430 processor - my own project, sadly neglected at the moment.

Read your own question. You SPECIFICALLY asked about "... or Pascal-like languages". How amazing can Ada can be? the best way to find out is learn. You can use a Pascal-like subset and ignore the advanced features if you like; some of them are inappropriate for MCUs anyway. And re: language revisions,  the latest standard for Pascal seems to be ISO7185:1990, perhaps you are confusing compiler revisions with language standards? Of course Gnat is updated much more often than the language itself.

Clarifications: 1. I am talking about Pascal derivatives (mikroPascal, FPC, Delphi, etc). 2. I am talking about the 'thing' that you install and use in your computer not about ISO. When I will do the program for Arduino I will use a real piece of software (hopefully Pascal) not an ISO.

I'm OK with you not "accept"ing it, btw. One or two of the comments pointed at possible alternative leads : if you follow up and they turn out to be useful, you can always add your own answer. Alternatively there used to be some sort of Pa front end for gcc. So if you feel strongly about Pascal, why not try building that for the AVR back-end, in which case the AVR-Ada project (runtime system) and my MSP430-Ada documentation may provide useful clues about some of the steps on that path. (Working on gcc is not trivial!) Good luck...

Anyway, until somebody will provide a different answer (if ever), Ada is indeed the closest thing to Pascal. I will accept your answer is no better alternative is provided. Thanks anyway. Upvoted.

@Kenny I hear you on obsolete criticisms of Pascal. Ada suffers from the same irrational reluctance to consider it and that affected me for years. I started programming in Wirth's first big language (Algol-W), also used Turbo Pascal (fantastic for its era) then his third (Modula-2 - great but with its limits). Then C and C++ for a decade or so thanks to their commercial inevitability, despite their design insanities. Looking for a saner alternative, tried Ada (not previously available). After C++, felt more like healing than learning. Not a recommendation, just a story of a journey.

@BrianDrummond- Ok, I will try that. I am looking to buy my frist Arduino board.

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 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, 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!

Thanks @MikaelPatel. Honestly, I don't mind paying (up to) 100 bucks for a Pascal commercial tool. I pay one order of magnitude more for my Delphi license so, 100 is not that much. P2C seems a decent alternative. I will consider P2C versus Ada (as recommended by Brian). Upvote (but I will keep Brian's post a the answer for the moment). Many thanks again.

A Pascal front-end 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.

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.


text:
Serial Monitor Suddenly Doesn't Work
I have had this problem a few times, it seems the Arduino IDE and the serial monitor is incredibly unstable, unless it's user error but judging from the fact that I hadn't even touched anything before it broke, I would say it's not me.
It was working the night before but this morning it just wouldn't print anything to the serial monitor from my code, however if I start one of the communication example codes like the ASCII example, it prints fine...I'm using the arduino uno, but I have a couple of dues too, so I tried the script on the due and it printed fine to the serial monitor.
Here is my code, could someone check my code and see if they can print to the serial monitor or not?
/*
   Pins:

   RTC:
   5V to VCC
   GND to GDN
   A4 to SDA
   A5 to SLC
*/

#include <Wire.h>
#include "RTClib.h"

#if defined(ARDUINO_ARCH_SAMD)
// for Zero, output on USB Serial console, remove line below if using programming port to program the Zero!
#define Serial SerialUSB
#endif

RTC_DS1307 rtc;

char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

//Words     //0      //1     //2    //3     //4     //5     //6    //7      //8      //9     //10   //11      //12      //13        //14        //15       //16       //17         //18        //19        //20      //21       //22    //23     //24                    //25//26 //27
char* w[] = {"Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen", "Twenty", "Thirty", "Forty", "Fifty", "Keeg Jo And Mat 2016", "", " ", "Good",
             //28       //29         //30       //31     //32    //33  //34       //35    //36       //37  //38
             "Morning", "Afternoon", "Evening", "It Is", "Past", "To", "Quarter", "Half", "O'Clock", "AM", "PM"
            };

//End Words

int timeType = 0;
int _hour = 0;

int dayInput = 0;
int hourInput = 0;
int minuteInput = 0;

int iDay = 0;
int iHour = 0;
int iMinute = 0;

void setup () {

#ifndef ESP8266
  while (!Serial); // for Leonardo/Micro/Zero
#endif

  Serial.begin(57600);
  pinMode(11, INPUT);//Minutes
  pinMode(12, INPUT);//Hours
  pinMode(13, INPUT);//Day

  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }

  if (! rtc.isrunning()) {
    Serial.println("RTC is NOT running!");
    //rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    //rtc.adjust(DateTime(2016, 3, 11, 10, 51, 0));
  }

  //rtc.adjust(DateTime(2016, 3, 11, 1, 0, 50));
  rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
}

void loop () {
  DateTime now = rtc.now();

  minuteInput = digitalRead(11);
  hourInput = digitalRead(12);
  dayInput = digitalRead(13);

  if (minuteInput == HIGH) {
    Serial.println("Minute");
  } else if (hourInput == HIGH) {
    Serial.println("Hour");
  } else if (dayInput == HIGH) {
    Serial.println("Day");
  }

  Line();

  if (now.minute() == 0) {
    timeType = 0;
  } else if (now.minute() > 0 && now.minute() <= 20) {
    timeType = 1;
  } else if (now.minute() > 20 && now.minute() < 50 && now.minute() != 30 && now.minute() != 45) {
    timeType = 0;
  } else if (now.minute() >= 50 && now.minute() < 60) {
    timeType = 2;
  } else if (now.minute() == 30) {
    timeType = 3;
  } else if (now.minute() == 45) {
    timeType = 4;
  }

  ps("Time Type: ");
  pi(timeType);

  Line();
  Line();

  //Greeting
  p(27);
  Space();
  if (now.hour() >= 0 && now.hour() < 12) {
    p(28);
  } else if (now.hour() >= 12 && now.hour() < 18) {
    p(29);
  } else if (now.hour() >= 18 && now.hour() < 24) {
    p(30);
  }

  Line();
  Line();

  //Time (It Is) Time Type 0
  if (timeType == 0) {
    Itis();
    hours(0);
    Space();
    _minutes();
    OClock();
  }

  //Time (Past) Time Type 1
  if (timeType == 1) {
    Itis();
    _minutes();
    Past();
    hours(0);
    OClock();
  }

  //Time (To) Time Type 2
  if (timeType == 2) {
    Itis();
    _minutes();
    To();
    hours(0);
    OClock();
  }

  //Time (Half Past) Time Type 3
  if (timeType == 3) {
    Itis();
    p(35);
    Past();
    hours(0);
  }

  //Time (Quarter To) Time Type 4
  if (timeType == 4) {
    Itis();
    p(34);
    To();
    hours(1);
  }

  //AM/PM
  AMPM();

  Line();
  Line();

  //Day
  //Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
  ps(daysOfTheWeek[now.dayOfTheWeek()]);

  Line();
  Line();

  pl(24);

  Serial.println("--------------------------------------------------");
  Serial.println("--------------------------------------------------");

  delay(1000);

}

//------------------------------------------------

void Line() {
  pl(25);
}

void Itis() {
  p(31);
  Space();
}

void Past() {
  Space();
  p(32);
  Space();
}

void To() {
  Space();
  p(33);
  Space();
}

void Space() {
  p(26);
}

void OClock() {
  DateTime now = rtc.now();
  if (now.minute() == 0 || now.minute() == 60) {
    Space();
    p(36);
  }
}

void AMPM() {
  Space();

  DateTime now = rtc.now();

  bool am = false;

  if (now.hour() > 12) {
    am = false;
  } else {
    am = true;
  }

  if (am) {
    p(37);
  } else {
    p(38);
  }
}

void p(int i) {
  Serial.print(w[i]);
}

void pl(int i) {
  Serial.println(w[i]);
}

void ps(char* i) {
  Serial.print(i);
}

void pi(int i) {
  Serial.print(i);
}

void _minutes() {
  DateTime now = rtc.now();
  int minutes = 0;

  if (timeType == 2) {
    minutes = 60 - now.minute();
  } else {
    minutes = now.minute();
  }

  int i = minutes;

  if (i <= 20 && i != 0) {
    p(i);
  } else if (i > 20 && i < 30) {
    p(20);
    Space();
    p(i - 20);
  } else if (i > 30 && i < 40) {
    p(21);
    Space();
    p(i - 30);
  } else if (i > 40 && i < 50 && i != 45) {
    p(22);
    Space();
    p(i - 40);
  } else if (i > 50 && i < 60) {
    p(23);
    Space();
    p(i - 50);
  } else if (i == 30) {
    p(35);
  } else if (i == 40) {
    p(22);
  } else if (i == 50) {
    p(23);
  }

}

void hours(int m) {
  DateTime now = rtc.now();

  if (now.hour() > 12) {
    _hour = now.hour() - 12;
  } else {
    _hour = now.hour();
  }

  _hour = _hour + m;

  p(_hour);
}

  //rtc.adjust(DateTime(2016, 3, 11, 1, 0, 50));
  rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));

Every time you reset the Arduino, the RTC clock will be set back to the date/time you compiled the sketch. Surely you don't want that?

The serial monitor is not at all unstable, as you agree when you try a different sketch. Therefore your sketch has a bug, which you need to find.
One possible issue is hardware. The default Wire library will hang if communications are lost when doing a read. Can you describe your clock hardware? Is it a chip you soldered yourself? A board? If so, which one? Do you have pull-up resistors on SDA/SCL?
There is an alternate I2C library that you could try.

Your method of printing is certainly unusual. You call, for example:
Line ();

When you could just as easily (and a lot more readably) call:
Serial.println ();

Similarly for Space and so on.

Still, despite the very hard-to-read code, I can't see any loops that might cause printing to fail. I suggest you comment out the calls to rtc.now() and test it. If it works, that confirms you have a clock issue, not a printing issue.
I note that you have multiple calls to:
DateTime now = rtc.now();

... sprinkled throughout your code. Surely you only need to read the time once, per loop?
Put the now variable outside loop, and call it once only, like this:
DateTime now;

void loop () {
  now = rtc.now();

Then remove the other calls to rtc.now().

I found when I tested (without a RTC connected) that it did indeed hang. But that was the rtc.now() call failing. If you comment that out, it prints fine.
eg.
Minute

Time Type: 0

Good Morning

It Is Six Twenty Eight AM

Keeg Jo And Mat 2016
--------------------------------------------------
--------------------------------------------------
Minute

Time Type: 0

Good Morning

It Is Six Twenty Eight AM

Keeg Jo And Mat 2016
--------------------------------------------------
--------------------------------------------------

That shows it is definitely a clock issue, not a serial printing issue.

Hi Nick, I just noticed something, when I pulled the clock module out of the board to get the name of the board it started printing again the serial monitor...then when I put it back in it started printing the same as what you put in above, however it's printing 'It Is Zero O'Clock AM'...

Think I may have found the problem, one of the pins has come loose from the board, the solder has come right off, I'll try re soldering it and see if that fixes it

Oh and as for those unusual printing methods, I'm just trying to keep my code as simple as possible, I'm working with some inexperienced coders, not that I'm particularly experienced though, besides, I actually quite like it!

All fine now, must have been the soldering...


text:
Is this method to a String from a function going to cause memory corruption?
I'd like to define a function such that I return a string and a boolean indicating whether the result is valid. Like this:
bool getStringOrTimeout(String *s) {
  ...
  if (timed_out) {
    return false;
  } else {
    *s = String(<some value>);
    return true;
  }
}

Is this going to cause a memory problem because the string is allocated on the stack and deallocated when it leaves scope, or is this okay?

You don't need to use the String constructor there. You could just as easily have said: *s = "foo";

You are better off passing the string by reference, like this:
bool getStringOrTimeout(String & s)
{
  if (timed_out)
    return false;
  s = "foo";
  return true;

}

That means the caller's string will be modified. And you no longer need to pass down a pointer to a string.


text:
Arduino metronome - Change time signature on button press
/**************************************/
const int lowestPin = 1;//the lowest one attach to
const int speaker = 13;
int ts = 4;//how many beats you want
int count = 1;
const int keyPin = 12;
int buttonState = 0;
int bpm = 120;
/**************************************/
void setup()
{
  for (int thisPin = 1; thisPin <= ts; thisPin++)
  {
    pinMode(thisPin, OUTPUT); //initialize thisPin as an output
    pinMode(6, INPUT);

  }
  pinMode(keyPin, INPUT);
}

/****************************************/
void loop()
{

  //iterate over the pins
  //turn the led on from lowest to the highest

  if (digitalRead(keyPin) == HIGH && ts == 2) {
    ts = 3;
    delay(2000);
  }

  else if (digitalRead(keyPin) == HIGH && ts == 3) {
    ts = 4;
    delay(2000);
  }

  else if (digitalRead(keyPin) == HIGH && ts == 4)
  {
    ts = 2;
    delay(2000);
  }

  for (int thisPin = 1; thisPin <= ts; thisPin++)
  {

    bpm = pulseIn(6, HIGH);

    pinMode(13, OUTPUT);
    if (ts > 4)
    {
      if (count > 3)
        for (int a = 4; a <= ts; a++) {
          digitalWrite(a - 3, HIGH);
        }

    }
    else
      digitalWrite(thisPin, HIGH);

    if (count == 1)
      tone(13, 1500, 100);
    else
      tone(13, 1000, 100);

    delay(bpm - 52);
    pinMode(13, INPUT);
    digitalWrite(thisPin, LOW);

    count++;
    if (count > ts)
      count = 1;

  }

}

I am trying to make a metronome using Arduino Uno, with 4 LEDs, each LED is a beat. I want to change the time signature every time I press the pushbutton, so that there are different number of beats per measure, but when I do press the button, it runs the code for 2 and 3 beats per measure once, and then goes back to its default, 4 beats per measure.
Sometimes, it even changes without pressing the button, randomly. I am using a 220 ohm resister instead of 10, as 10 starts much more randomly than the 220.

Do you have resistors in series with those LEDs?

No resistors are with those LEDs

You must have resistors in series with the LEDs. See The care and feeding of LEDs. 330 ohms in series with each LED would be about right in your situation.
With no resistors you are drawing far too much current from the output pins. That would drop the voltage and the processor would reset. Thus it goes back to the default of 4 beats per measure.
It also damages both the processor and the LEDs.
You can tell if the processor resets by putting extra code into setup. For example, after setting the pins to outputs:
 for (int i = 0; i < 10; i++)
    {
    digitalWrite (3, HIGH);
    delay (200);
    digitalWrite (3, LOW);
    delay (200);
    }

If you see pin 3 flashing 10 times, you know the processor has reset.

I think your problem now is that you have a floating input for the switch. When I tried your sketch, with a couple of modifications, it worked fine.
My code:
/**************************************/
const int lowestPin = 1;//the lowest one attach to
const int speaker = 13;
int ts = 4;//how many beats you want
int count = 1;
const int keyPin = 12;
int buttonState = 0;
int bpm = 120;
/**************************************/
void setup()
{
  for (int thisPin = 1; thisPin <= ts; thisPin++)
  {
    pinMode(thisPin, OUTPUT); //initialize thisPin as an output
    pinMode(6, INPUT);
  }
  pinMode(keyPin, INPUT_PULLUP);
}

/****************************************/
void loop()
{

  //iterate over the pins
  //turn the led on from lowest to the highest

  if (digitalRead(keyPin) == LOW && ts == 2) {
    ts = 3;
    delay(2000);
  }

  else if (digitalRead(keyPin) == LOW && ts == 3) {
    ts = 4;
    delay(2000);
  }

  else if (digitalRead(keyPin) == LOW && ts == 4)
  {
    ts = 2;
    delay(2000);
  }

  for (int thisPin = 1; thisPin <= ts; thisPin++)
  {

    bpm = pulseIn(6, HIGH);
    //bpm = 1000;

    pinMode(speaker, OUTPUT);
    if (ts > 4)
    {
      if (count > 3)
        for (int a = 4; a <= ts; a++) {
          digitalWrite(a - 3, HIGH);
        }
    }
    else
      digitalWrite(thisPin, HIGH);

    if (count == 1)
      tone(speaker, 1500, 100);
    else
      tone(speaker, 1000, 100);

    unsigned long now = millis ();
    while (millis () - now < (bpm - 52))
      {
      // quit delay if switch pressed
      if (digitalRead(keyPin) == LOW)
        break;
      }

    pinMode(speaker, INPUT);
    digitalWrite(thisPin, LOW);

    count++;
    if (count > ts)
      count = 1;

  } // end of for each pin

} // end of loop

Note that the input from the switch is now INPUT_PULLUP which means it is pulled HIGH by an internal resistor. Thus, the tests are now for == LOW rather than == HIGH.
Also, instead of a delay for the timing of the metronome, I changed it to testing millis() and seeing if time is up. Otherwise you have to hold the switch down for the entire time that a cycle repeats.

Now that I have resistors, the button still does not change the time signature (ts). How can I wire this differently or change the code?

See amended reply.


text:
MQTT Broker on an Arduino
Has anyone here setup an MQTT Broker on an Arduino?  I am looking to use pubsubclient to send sensor data from 12 individual wireless sensors to an Arduino every 250ms.  I know this can be done using a Raspberry Pi, but I am new to all this and am just now comfortable with programming an Arduino.  I also looked at using XBee, but have heard it may not be able to handle the data frequency.  I am only sending 1 byte of data from each sensor each time.  Any help or suggestion is appreciated.

Maybe link to some info on MQTT.  From my limited understanding, MQTT is on top of a TCP/IP stack, so to send one byte per observation, there would need to be quite a few bytes of overhead.

Sending one byte of data over MQTT is incredibly inefficient. You would be better off using a simple serial protocol of some form and forgetting about MQTT to send data between little nodes like this. By all means use MQTT to publish it out onto the internet somewhere, but internally don't use MQTT.

Majenko: when you say to use a simple serial protocol, can you give an example of what you mean?  What hardware would be needed at the sensors to transmit, and at the arduino to receive it? I do not need to publish to the web, just from the 12 unique sensors wirelessly to a single arduino.

One additional piece of info, the physical distance from the sensors to the Arduino is about 10 ft.  I'm sure that plays into how this could be done.  I looked at using RF24, but read that it is limited to just 6 connections communicating in an organized manner.

MQTT is TCP based. A nodeMCU (think of it as a super-Arduino) has a 5 concurrent connections limit. I don't know about Arduino WiFi shields, but I doubt it can handle more than that.


text:
Understanding the contents of a library in C
So this is a question not just about the #include  but most all includes you find while programming in C.
So I understand a library is prewritten code and when you include that library are you able to used certain function that are included in that library.
What I have always wanted to know is: where can you find the "instruction set", in C, for these libraries?
How can I find out what commands are available for me to use with this library?
hope this makes sense.
thank you everyone.

A library provides an Application Program Interface (API) and the API should be documented with the library somewhere, but the quality of that documentation varies depending on the library.  Maybe https://www.arduino.cc/en/Reference/Libraries is a place to start?

where can you find the "instruction set", in C, for these libraries? Libraries come with either binary or source files. You should include the header file (.h or .hpp) in this file you can find the function definitions along with (usually) comments.
If you have a implementation file (.c or .cpp) these will have the (C/C++) source code available.

What I have always wanted to know is: where can you find the "instruction set", inc C, for these libraries?

The libraries are usually found in the libraries sub-folder under your sketchbook folder (wherever that is). There is also another libraries folder inside the IDE install folder for the "official libraries".

How can I find out what commands are available for me to use with this library?

Usually the library documents them in one way or another. Try looking inside the .h file used by the library to see what functions are exposed.


text:
Function of rxAlign parameter in the PCD_ReadRegister function in MFRC522 Library
I'm trying to port the MFRC522 Arduino library (from GitHub) to the ARM MCUs.
My problem is with the PCD_ReadRegister function:
/**
 * Reads a number of bytes from the specified register in the MFRC522 chip.
 * The interface is described in the datasheet section 8.1.2.
 */
void MFRC522::PCD_ReadRegister( byte reg,       ///< The register to read from. One of the PCD_Register enums.
                                byte count,     ///< The number of bytes to read
                                byte *values,   ///< Byte array to store the values in.
                                byte rxAlign    ///< Only bit positions rxAlign..7 in values[0] are updated.
                                ) {

    if (count == 0) {
        return;
    }
    //Serial.print(F("Reading "));  Serial.print(count); Serial.println(F(" bytes from register."));
    byte address = 0x80 | (reg & 0x7E);     // MSB == 1 is for reading. LSB is not used in address. Datasheet section 8.1.2.3.
    byte index = 0;                         // Index in values array.
    SPI.beginTransaction(SPISettings(SPI_CLOCK_DIV4, MSBFIRST, SPI_MODE0)); // Set the settings to work with SPI bus
    digitalWrite(_chipSelectPin, LOW);      // Select slave
    count--;                                // One read is performed outside of the loop
    SPI.transfer(address);                  // Tell MFRC522 which address we want to read
    while (index < count) {
        if (index == 0 && rxAlign) {        // Only update bit positions rxAlign..7 in values[0]
            // Create bit mask for bit positions rxAlign..7
            byte mask = 0;
            for (byte i = rxAlign; i <= 7; i++) {
                mask |= (1 << i);
            }
            // Read value and tell that we want to read the same address again.
            byte value = SPI.transfer(address);
            // Apply mask to both current value of values[0] and the new data in value.
            values[0] = (values[index] & ~mask) | (value & mask);
        }
        else { // Normal case
            values[index] = SPI.transfer(address);  // Read value and tell that we want to read the same address again.
        }
        index++;
    }
    values[index] = SPI.transfer(0);            // Read the final byte. Send 0 to stop reading.
    digitalWrite(_chipSelectPin, HIGH);         // Release slave again
    SPI.endTransaction(); // Stop using the SPI bus

} // End PCD_ReadRegister()

I read the datasheet several times & can't understand what's the function of this parameter!
Based on datasheet for reading a register from rc522:

Concerning the image in your post about 'SPI Read Data', that simply says the first byte received over MISO is discarded, which is done in PCD_ReadRegister() right before the for loop, and then n bytes are read, with 0 transferred the last time to stop reading.
A quick look at the library and datasheet shows that the rxAlign argument is used in identifying the first valid bit in the first received byte. txLastBits serves a similar purpose, only for transmission of the final byte. Both are written to BitFramingReg of the MFRC522 and are necessary for bit-oriented frames between the MFRC522 and a card/tag.
For example, in the function you have above, if rxAlign = 3, it means only bits 7 to 3 are valid in the first received byte, extracted with bit mask 11111000. So the first valid 'byte' comprises bits 7 to 3 of the first received byte concatenated with bits 2 - 0 of the next received byte. Similarly, in transmission, txLastBits indicates the number of bits of the last byte that are to be transmitted to the card/tag. In both cases, what is transmitted or received over the RF field may not be a multiple of 8, hence the need for these arguments and BitFramingReg.
Anyways, this shouldn't interfere at all with porting the library. Simply replace the Arduino-specific functions/interfaces and allow the library's existing logic to remain as is.

EDIT
I'll try to answer your questions:

In this context, 106kBd refers to the data rate between the RC522 and a card, and not between the RC522 and the MCU. The maximum is about 848kBd, i think. Check the datasheet for more details.
Bit-oriented frames are necessary for the anti-collision process. Superimposed bits in the Manchester encoding, when several cards attempt to communicate with the RC522 at once, require that individual bits be processed as opposed to the usual byte-sized units. Look up anti-collision techniques.
Anticollision is necessary if the same reader will possibly have multiple tags within its range. From an IEEE article:

Tag collisions can impose a major inefficiency in RFID systems, resulting in low identification rates, short reading range and ineffective resource utilization. They are more problematic in passive tags due to limitations on power and functionality.

So, if you will be presenting only one card at a time, then you should be safe without implementing anticollision in your code. Else, I'm afraid you have no choice unless you want to confuse the reader.
If all you want to do is read UIDs and read from/write to blocks on a card (one at a time), you may want to try porting this straightforward MFRC522 UART library, which doesnt implement anitcollision, by the way.
If you still want to port the SPI-based library, then, a few suggestions:
You want to replace the SPI interface with UART. This is low-level stuff, all contained within a few functions like PCD_ReadRegister(), PCD_WriteRegister() and a few others. These functions serve higher-level functions, which have no clue of their internal implementation, but expect certain behaviour from them. Swap the SPI functions for their UART equivalents, as soon as you understand how to talk to the reader over UART. Once your ARM UART functions behave exactly like the SPI functions, your work is almost done; there is no need to learn the reason for everything in the higher-level functions since they dont relate to anything interface-specific. This includes everything concerning rxAlign and whatnot. Good luck :).

Dear Tiste,Really thanks for your great description.Problem is that i must changed libraries used connection peripheral from SPI to UART.3 new question:1-Based on Datasheet page 46-table 48:These bits are only to be used for bitwise anticollision at
106 kBd, for all other modes they are set to 0.then for default 9600 baud rate in uart can i avoid this?2-second question is i understand what is do,but i don't know why we do this yet?why bytes are not formed as usual and are not valid from first bit?why there are avoidable bits in the beginning of data stream?3-is this necessary in UART mode too?

@MahmoudHD I've edited my answer.

@MahmoudHD Does this help? Have you gotten past this?

Dear Tiste,Really appreciated you for your great guidance,I'm trying hard to port an official SPI arduino library of this chip to my target MCU,I will be place to new question here,WBR.

@MahmoudHD You arent porting to UART anymore?

Actually I mean,I'm trying to port SPI version(https://github.com/miguelbalboa/rfid) to initialing with UART yet.Now here we are in new year holidays & after that i will continue to porting that for LPC ARM MCUs,WBR.


text:
RGBW LED strip: which components are required?
I'm brand new to this community, and in electronics as well.
I'm a software developer and I want to start a new journey with a project in mind: I want to control a 5 meters addressable LED strip for my living-room.
I need all the components for this project... I already know eclipse and Java world, but I need help in choosing the components for the project:

which Arduino (starter package maybe?)
LED strip (smd 5050 on sw2812b, sk6812, APA104...) more than 60 LEDs/m
Power Supply for the project

Can you point me to the right direction, posts that can be useful to me, so I can start on good basis?

I doubt that you'd need the starter kit, you only need to pick an Arduino board based on your code storage requirements and power.

NeoPixels
The strips based on the WS2812 / SK6812 and similar chips, known by some as NeoPixels, are clever ways of implementing fully-addressable 24-bit colour LEDs.
One of the clever things is that they only require one data wire, plus power and Gnd, i.e.

+5V
Data
Gnd

The pixel information is sent by precisely timed sequences of 24 bits per pixel. The first pixel "peels off" these 24 bits (ie. 3 x red / green / blue) and then passes the rest on to the next pixel, and so on.
Libraries
Various people have written libraries to do this for you including:

Adafruit library
NeoPixels Revealed: How to (not need to) generate precisely timed signals
My own library which uses SPI

Power
Each pixel draws around 60 mA at maximum brightness (showing white) so you need to allow for a heavy-duty power supply. Particularly if you have 5m of 144 pixels/m then that is 720 pixels, which would require 43.2 amps!
According to Adafruit:

To estimate power supply needs, multiply the number of pixels by 20, then divide the result by 1,000 for the “rule of thumb” power supply rating in Amps.

Even that means you need 14.4 amps for your 720 pixels!
So bear that in mind when sizing your power supply.
Addressing methods
The Adafruit library (as far as I can tell) holds the pixel information in RAM, and then "dumps" it to the NeoPixels in one operation. This lets you do fancy things in memory, and copy the results to the pixels. However that means you need enough RAM for all this. At 3 bytes per pixel (24 bits), if you have 720 pixels, that will be 2160 bytes, which is more RAM than the smaller processors (like the Uno) have.
Larger processors (like the Mega) have more RAM.
An alternative method, as explained here does not keep the data in RAM, but generates the colours "procedurally" on-the-fly. This is much less RAM-intensive, but perhaps less flexible. On that page he links to a YouTube video which shows a humble Arduino Duemilanove (similar to a Uno) driving over 1000 pixels!
Procedural generation however can do quite a lot, for example you can set the entire string to a single colour, change that rapidly, or make a rainbow effect by increasing (say) the red value for each successive pixel. You can also make "chaser" effects quite simply.
The library I wrote is also designed to allow you to use minimal RAM. You could conceivably add in your own storage scheme, perhaps only storing one byte per pixel, with less bits per colour (eg. 2 bits each for red, green, blue) and that would reduce RAM requirements by a third.
Cabling run
You could try sending the data over 2m. I warn you that the timing for a zero-bit is that it has to go HIGH and then LOW within about 400 ns, so you can't afford to have the data signal degrade too much.
When I had a similar string of coloured LEDs set up at Xmas time (not NeoPixels however) I had a long run of a 5V power supply (just using a pair of figure-8 wire), and situated the processor quite close to the pixels. This is probably the safest way of doing it.

Wow that is a well detailed answer, now I'm scared ! joking :) Thanks a lot, i'll keep all of this in mind ! so the strip I found is ok (72/m x 5m = 360 pixel), I'm glad to hear that ^^

BTW I got my 300 NeoPixel string in the mail today. Powering it up with all white at full brightness it consumed 3.9 amps, and even then the end of the strip looked yellow. There is provision on mine for powering both ends, and I guess I would need to do that if I wanted full brightness through the string.

I like the ws2812 RGB LEDs with integrated controller. They can be found on adafruit.com, e.g. here: Adafruit NeoPixel NeoMatrix 8x8.
There are some good tutorials on adafruit.com:

https://learn.adafruit.com/adafruit-neopixel-uberguide/overview
https://learn.adafruit.com/adafruit-neopixel-uberguide/best-practices
https://learn.adafruit.com/adafruit-neopixel-uberguide/neomatrix-library

Choosing your Arduino you have to keep in Mind that the Arduino Due runs at 3.3 V, while the Arduino Mega runs at 5 V. The ws2812. But you can use a level shifter to connect an Arduino Due to the ws2812.
Your Arduino is powered via USB, the LED matrices / stripes need their own power supply, but a DC 5V wall plug (something like a cell phone charger) will do the work (check the max. ampere ratings to be high enough for your LEDs).
A starter package depends on what you already have. Some jumper cables are always good to have, basic tools for electronics as well, e.g. a soldering iron or some prototyping board.

thanks a lot for your hints. FYI I'm in France as I heard there was some licence stories about Arduino' name... can I have the Arduino next to me at around 2 meters of the led strip ? or is it better to have a 2 meters long usb cable... ?

Adafruit says to minimize the distance between the LED matrices and the Arduino. but I have seen systems working with ~ 2 m of cable between the Arduino and the LEDs. But a 2 m long USB cable is working as well.

Thanks !! could this strip be ok (model IP30 72Pixel RGB WW) aliexpress ?

You don't need 2m of USB cable. A lot (all?) of Arduinos also have a power input jack. Just extend a 5V power supply to reach it. It will be easier with a 5V Arduino like the Uno. It looks like the strip you mentioned has the same/similar chip (SK6812) to the NeoPixels.

ho now I understand your message ^^ the 2m usb cable was for dialoging with the pc ^^