text:
FreqMeasure.h uncompatible with my code problem
I have written code to read temperatures on a motor which also has pulse feedback to see speed, (one hall sensor) and my previous version of the code does work fine, however when i add example frequency code from codebender into my code it doesn't give feedback on the frequency. Standalone the frequency code works fine. Is there any obvious failure in the code or is there just some conflict between files in library?
Trying to return RPM into the SD card results in 0.00. And the temperature measurements goes into switching between 85C and -127C.
Equipment: Arduino Nano, DS18B20, 2x16 LCD, Homemade SD shield, motor with internal motordriver.
Here is my code:
#include <OneWire.h>
#include <DallasTemperature.h>
#include <LiquidCrystal.h>
#include <SD.h>
#include <FreqMeasure.h>

// Data wire is plugged into pin 9 on the Arduino
#define ONE_WIRE_BUS 9

// Setup a oneWire instance to communicate with any OneWire devices
// (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);
LiquidCrystal lcd(7, 6, 5, 4, 3, 2);

// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);

float temperature1, temperature2, temperature3;
double RPM;
void setup(void)
{
  // start serial port
  Serial.begin(57600);
  FreqMeasure.begin();
  Serial.println("Dallas Temperature IC Control Library Demo");
  // Start up the library
  lcd.begin(16, 2);
  sensors.begin();
  Serial.print("Initializing SD card...");      // Initialize SD card

  if (!SD.begin(10)) {
    Serial.println("initialization failed!");   // Initialize SD card failed
    return;
  }
  Serial.println("initialization done.");       // Initialize SD card done
}

double sum=0;
int count=0;

void loop(void)
{
  if (FreqMeasure.available()) {
    // average several reading together
    sum = sum + FreqMeasure.read();
    count = count + 1;
    if (count > 30) {
      double frequency = F_CPU / (sum / count);
      RPM=frequency*60;
      sum = 0;
      count = 0;
    }
  }

  unsigned long curMillis = millis();
  unsigned long curSeconds = curMillis/1000;   // Get current seconds
  // call sensors.requestTemperatures() to issue a global temperature
  // request to all devices on the bus
  Serial.print(" Requesting temperatures...");
  sensors.requestTemperatures(); // Send the command to get temperatures
  Serial.println("DONE");
  temperature1=sensors.getTempCByIndex(0);
  temperature2=sensors.getTempCByIndex(1);
  temperature3=sensors.getTempCByIndex(2);
  logData();
  Serial.print("Temperature for Device 1 is: ");
  Serial.print(sensors.getTempCByIndex(0)); // Why "byIndex"?
  Serial.print("Temperature for Device 2 is: ");
  Serial.print(sensors.getTempCByIndex(1));
  Serial.print("Temperature for Device 3 is: ");
  Serial.println(sensors.getTempCByIndex(2));

  lcd.setCursor(0, 0);
  lcd.print("T1=");
  lcd.setCursor(3, 0);
  lcd.print(sensors.getTempCByIndex(0));
  lcd.setCursor(8, 0);
  lcd.print("T2=");
  lcd.setCursor(11, 0);
  lcd.print(sensors.getTempCByIndex(1));
  lcd.setCursor(0, 1);
  lcd.print("T3=");
  lcd.setCursor(3, 1);
  lcd.print(sensors.getTempCByIndex(2));
  lcd.setCursor(8, 1);
  lcd.print("S=");
  lcd.setCursor(10, 1);
  lcd.print(curSeconds);
    // You can have more than one IC on the same bus.
    // 0 refers to the first IC on the wire

}

void logData() {
  Serial.print("Temperature1 = ");   Serial.print(temperature1);    // Printing to serial communication
  Serial.print(" C, Temperature2 = ");  Serial.print(temperature2);       // Printing to serial communication
  Serial.print(" C, Temperature3 = ");  Serial.print(temperature3);       // Printing to serial communication
  Serial.println(" C");                                           // Printing to serial communication
  Serial.println(RPM);
  unsigned long curMillis = millis();          // Get current time
  unsigned long curSeconds = curMillis/1000;   // Get current seconds

  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  File myFile = SD.open("LOG.txt", FILE_WRITE);

  // if the file opened okay, write to it:
  if (myFile) {
    Serial.print("Writing to LOG.txt...");                        // Printing to serial communication
    myFile.print("Time = "); myFile.print(curSeconds);            // Printing to log file on sd card
    myFile.print(" Temperature1 = "); myFile.print(temperature1);   // Printing to log file on sd card
    myFile.print(" Temperature2 = "); myFile.print(temperature2);         // Printing to log file on sd card
    myFile.print(" Temperature3 = "); myFile.print(temperature3);       // Printing to log file on sd card
    myFile.print(" RPM = "); myFile.println(RPM);       // Printing to log file on sd card
    // close the file:
    myFile.close();
    Serial.println("done.");
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening LOG.txt");                      // Error either SD card not connected or not detected
  }
  delay(1000);
}

if (FreqMeasure.available() == false) then RPM is not initialised but it is used later on, this will produce odd results, but not the fault you see.
Also why keep calling sensors.getTempCByIndex(2) when you have written the values to Temperature3?

The repetition of 'sensors.getTempCByIndex(2)' is just a minor fault from my previous version of the code. And i have checked the 'FreqMeasure.available()' and it is false in the start but goes to some number between 1-11 during motor running, so should start running then.

Gísli - Sorry neither of the things I mentioned will fix you problem, I should have said that.  Yes sensors.getTempCByIndex(2) is a minor thing.  The RPM is  going to cause problems.  I will do an answer so I can explain.

I believe there is a conflict bewteen the code relative to the SD card, which uses SPI and the use of timer1 within FreqMeasure.
My advice is to temporarily remove the code for the SD card and write that data onto the serial console: if the data displays correctly on the serial monitor than you have an indication the issue is in there.
The problem with SPI and time based interrupts is the latter might prevent the SPI communication to properly complete.

Thanks for the idea, will check it out and then post if it is the problem.

The conflict is between the (OneWire.h DallasTemperature.h) and the FreqMeasure.h, tried the SD.h and all its variables and that was not the conflict however when i tried disabling the temperatures then the frequency worked fine.

From what i have tested myself towards then it seems that the problem with this code is that OneWire.h and DallasTemperature.h are the problem when combined with FreqMeasure.h, so i found a way to use the A0 as RPM reader. So the answer to the question is that those libraries are uncompatible, and with the following code it is possible to read RPM, temperature and write to SD.
My code works with the added A0 as RPM reader.
#include <OneWire.h>
#include <DallasTemperature.h>
#include <LiquidCrystal.h>
#include <SD.h>

// Data wire is plugged into pin 9 on the Arduino
#define ONE_WIRE_BUS 9

// Setup a oneWire instance to communicate with any OneWire devices
// (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);
LiquidCrystal lcd(7, 6, 5, 4, 3, 2);

// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);

float temperature1, temperature2, temperature3;
double RPM=0.0;
//storage variables
byte newData = 0;
byte prevData = 0;
//freq variables
unsigned int timer = 0;
unsigned int period = 0;
double frequency;

void setup(void)
{
  cli();  //disable interrupts
  ADCSRA = 0; //clear register
  ADCSRB = 0; //clear register

  ADMUX|=(1<<REFS0);  //Set reference voltage
  ADMUX|=(1<<ADLAR);  //left align the ADC value so we can read highest 8 bits from the ADCH register only
  ADCSRA|=(1<<ADPS2)|(1<<ADPS0);  //set ADC clock with 32 prescaler- 16mHz/32=500kHz
  ADCSRA|=(1<<ADATE); //enable auto trigger
  ADCSRA|=(1<<ADIE);  //enable interrupts when measurement is complete
  ADCSRA|=(1<<ADEN);  //enable ADC
  ADCSRA|=(1<<ADSC);  //start ADC measurement
  sei();  //enable interrupts

  // start serial port
  Serial.begin(57600);
  Serial.println("Dallas Temperature IC Control Library Demo");
  // Start up the library
  lcd.begin(16, 2);
  sensors.begin();
  Serial.print("Initializing SD card...");      // Initialize SD card

  if (!SD.begin(10)) {
    Serial.println("initialization failed!");   // Initialize SD card failed
    return;
  }
  Serial.println("initialization done.");       // Initialize SD card done
}
ISR(ADC_vect){  //when new ADC value ready
  prevData = newData; //store previous value
  newData = ADCH; //get value from A0
  if(prevData<127 && newData>=127){ //if increasing and crossing midpoint
    period = timer; //get period
    timer = 0;  //reset timer
  }
  timer++;  //increment timer at rate of 38,5kHz
}

void loop(void)
{
  frequency = 38462/period; //timer rate/period
  RPM = frequency*60;
  unsigned long curMillis = millis();
  unsigned long curSeconds = curMillis/1000;   // Get current seconds
  // call sensors.requestTemperatures() to issue a global temperature
  // request to all devices on the bus
  Serial.print(" Requesting temperatures...");
  sensors.requestTemperatures(); // Send the command to get temperatures
  Serial.println("DONE");
  temperature1=sensors.getTempCByIndex(0);
  temperature2=sensors.getTempCByIndex(1);
  temperature3=sensors.getTempCByIndex(2);
  logData();

  lcd.setCursor(0, 0);
  lcd.print("T1=");
  lcd.setCursor(3, 0);
  lcd.print(temperature1);
  lcd.setCursor(8, 0);
  lcd.print("T2=");
  lcd.setCursor(11, 0);
  lcd.print(temperature2);
  lcd.setCursor(0, 1);
  lcd.print("T3=");
  lcd.setCursor(3, 1);
  lcd.print(temperature3);
  lcd.setCursor(8, 1);
  lcd.print("S=");
  lcd.setCursor(10, 1);
  lcd.print(curSeconds);
    // You can have more than one IC on the same bus.
    // 0 refers to the first IC on the wire

}

double sum=0.0;
int count=0;

void logData() {
  unsigned long curMillis = millis();          // Get current time
  unsigned long curSeconds = curMillis/1000;   // Get current seconds
  Serial.print("Time="); Serial.print(curSeconds);
  Serial.print(" Temperature1 = "); Serial.print(temperature1);
  Serial.print(" Temperature2 = "); Serial.print(temperature2);
  Serial.print(" Temperature3 = "); Serial.print(temperature3);
  Serial.print(" RPM = "); Serial.println(RPM);
  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  File myFile = SD.open("LOG.txt", FILE_WRITE);

  // if the file opened okay, write to it:
  if (myFile) {
    Serial.print("Writing to LOG.txt...");                        // Printing to serial communication
    myFile.print("Time = "); myFile.print(curSeconds);            // Printing to log file on sd card
    myFile.print(" Temperature1 = "); myFile.print(temperature1);   // Printing to log file on sd card
    myFile.print(" Temperature2 = "); myFile.print(temperature2);         // Printing to log file on sd card
    myFile.print(" Temperature3 = "); myFile.print(temperature3);       // Printing to log file on sd card
    myFile.print(" RPM = "); myFile.println(RPM);       // Printing to log file on sd card
    // close the file:
    myFile.close();
    Serial.println("done.");
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening LOG.txt");                      // Error either SD card not connected or not detected
  }
  delay(100);
}

This is an explanation of the issue with the RPM variable in the code, its not an answer, but it needs formatting to explain it clearly.
double RPM;
...
if (FreqMeasure.available()) {
...
  RPM=frequency*60;
...
}
...
Serial.println(RPM);

It is possible that RPM is going to be written to Serial.println() before it has a value set.
In this case it is very unlikely to cause anything more than 'garbage' to be printed, but it could be much worse.  So I think if you initialised the RPM variable to 0.0 when you declare it it would be good practice.


text:
No connection with XBee radios on Arduino board
I have two Arduino boards which I've attached XBee radio boards to. One is to send data via Serial.write(num), where num is an integer. The other is receiving that integer via Serial.read. However, when I have both units running, nothing is ever received by the receiving unit. I've tried switching the receiving unit radio board to the USB mode so that I can use the serial monitor to send data to the unit. I've tried sending bytes 01111110, as well as integers such as 77. Nothing ever gets read from the serial monitor. I've downloaded XCTU, but it cannot find either of the radios. What can I do?

source: Stack Exchange

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

sort: votes


text:
EthernetClient: HTML table isn't being fully populated
I have the following code below for an EthernetClient named client. It is supposed to print a 2 row, 9 column table. The headers are ID and Name and are the first cell in each row. The other columns are the associated data. The problem I am having is that it is only printing the first ID and then the rest of the cells for that row are blank. The names all get printed in the row below it without a problem. Why won't it print the other IDs?
Here is the ID array: String ids[16] = {"00000", "00001", "00010", "00011", "00100", "00101", "00110", "00111", "01000", "01001", "01010", "01011", "01100", "01101", "01110", "01111"};
client.println("
");
client.println("
");
client.println("ID	");
for(int i = 0; i < 8; i++) {
  client.print("");
  client.print(ids[i]);
  client.println("	");
}
client.println("
");
client.println("
");
client.println("Name	");
for(int i = 0; i < 8; i++) {
   client.print("");
   client.print(name[i]);
   client.println("	");
}
client.println("
");
client.println("
");

Could you show the output your get? Preferably the raw "view-source" html output.

I tried your code, changing client to Serial and the output looked OK. It even rendered OK in my web browser.

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


text:
Is there a counter library in Arduino?
I'm looking for a counter that can be incremented and will overflow with predictable behavior, preferably reset to 0 on overflow. I've tried using integers for counting but I'm getting weird overflow issues. Is there some library that provides an implementation of a counter?

Use unsigned integers. If you need a specific size, use uint8_t, uint16_t, uint32_t or uint64_t. They are respectively 8, 16, 32 and 64 bits wide.

For reference, all integer types can be incremented and will overflow with predictable behavior.  What kind of weird overflow issues were you getting with ints?  What are you trying to do?

@mwwalk: What you say is absolutely wrong! Please, do not spread such nonsense over the Internet. Signed integer overflow is undefined behavior in C and C++. In some sense, it is considered “illegal”. Technically, it means the compiler will assume your signed integers do not overflow, and optimize your code on the basis of this premise, completely disregarding the possible consequences of the premise possibly being wrong. Then, any kind of weird behavior can happen if you overflow a signed integer. Unsigned integers, on the other hand, have predictable overflow behavior.

@mwwalk: Here is a good read about undefined behavior in C and C++, with some enlightening examples related to signed integer overflow (see part 2): A Guide to Undefined Behavior in C and C++.

Yeh, I take it back and I was obviously wrong.  But you could calm down a little, I obviously didn't mean to be wrong and I'm not trying to push some alternative overflow agenda.  I just made a mistake.  Literally every time I've ever had an integer overflow, it has done so in the predictable and expected manner.  Apparently I've just gotten lucky so far.

Since you dont give the largest number your counter over flows at. You may want to look at libraries that implement arbitrary size integers. This means that there the integers can be bigger than usual - You would need to implement a counter, reset to 0 if the integer gets too big (just use a if statement if what youre doin is that simple-it sounds like it). So its entirely predictable for your purpose (whatever that is you didnt state). If you google around you will find libraries for arbitrary large integers for arduino e.g.
https://forum.arduino.cc/index.php?topic=85692.0
a library by Nick Gammon.


text:
How to keep track of if data is outdated
I have a large set of data and it is refreshed every 30 seconds or so. However, not all data is refreshed every time. It is possible that no new data for a particular calculation isn't received for even a few hours. For this reason I need to track what data is possibly outdated, but hasn't been updated (maybe due to technical malfunctions or a sensor is down). I was thinking about creating an additional (large) 2d array to do this, and increment some sort of counter. This way if a particular spot is at 1000 this means it is old. When new data is received it can be reset to 0. However, this seems like a slow, ineffective way to do this. How could I keep track of data more efficiently?

It depends what form the data takes.

Also what you are using the data for.

@Majenko the data is all integers stored in arrays. It is just being stored and displayed on a webpage. So it'd be great to have some indication of what data on the page is old

What range are the values?

@Majenko -1 (indicating no data available) to 1000

You could add a timestamp for each value (or set of values). It would hold the time when the value(s) was latest updated.

OK, so you have three possible states for your values:

No valid data (-1, or 0xFFFF in 16-bit 2's complement)
Valid data (0 to 1000, or 0x0000 to 0x03EB in 16-bit)
Valid but "old" data.

If you first check for invalid data before thinking about "old" data (invalid data is never considered "old") then you just have two states:

Valid data (0 to 1000, or 0x0000 to 0x03EB in 16-bit)
Valid but "old" data.

As you can see the highest 6 bits of the stored value aren't used at all except for storing -1 for invalid data (hence checking for that first). So you could utilize those 6 bits to store all sorts of things. In 6 bits you can store the values 0 to 63. That could be the number of seconds since the last time you got some data.
By masking and shifting you can separate out the two values:
val = data[x] & 0x3FF;
sec = data[x] >> 10;

Every second add one to the seconds count of each and every data entry that is less than (say) 60.
val = data[x] & 0x3FF;
sec = data[x] >> 10;
if (sec < 60) sec++;
data[x] = val | (sec << 10);

Now each entry in your array knows how old it is (up to 1 minute), and if it's older than a certain threshold (30 seconds? 45 seconds? you choose) then you consider it "old" and display it as such.
You can make it easier to program by using a union/struct combination:
typedef union {
    int16_t rawval;
    struct {
        unsigned value:10;
        unsigned seconds:6;
    } __attribute__((packed));
} data_t __attribute__((packed));

If your data array is now made up of that type instead of integers:
data_t data[500];

you can now access:

data[x].rawval as the raw 16 bit signed value (to look for -1).
data[x].value as the unsigned 10 bit value from 0 to 1000.
data[x].seconds as the unsigned 6 bit value from 0 to 63.

Updating the seconds then becomes as simple as:
if (data[x].seconds < 60) data[x].seconds++;

When you store a new value using
data[x].rawval = sensor.getValue();

the seconds is automatically overwritten with 0 which resets the count for you.
And both methods give you data ageing without using a single byte more memory.

Rather than frequently updating a time flag for each data item, you can store a “generation number” for each item.  Maintain a “current generation number” currentGen and at intervals add one to it.  If the interval at which you increment currentGen is 20 seconds and you store 16-bit generation numbers, rollover will occur about every 15 days.  [20*2¹⁶/3600/24 = 15.17 days.]
For example, suppose your data structure has fields for item.value and item.gen.  Whenever you store a new value into item.value, copy currentGen into item.gen.  Later, to tell the age of an item, use unsigned int arithmetic to subtract item.gen from currentGen.  For example, if  currentGen is 23453, an element with item.gen = 17487 is about 33 hours old.
Note, if item age ever exceeds 15.17 days, it will wrap around to zero.  It that's a concern, either use a larger datatype for item.gen, or update currentGen less frequently, for example every two minutes for a 90-day wraparound or every 8 minutes for a 364-day wraparound time.


text:
XBee radio dropping bytes?
I am using an XBee radio setup to transmit bytes over a distance of approximately .25 miles. For the first 20,000, or so, transmissions it was completely error free. However, once there was a single error, every other transmission became an error. For my project a transmission consists of three bytes, with the third byte being an XOR of the first two. The first byte also has a parity bit. The 1st byte is a sensor number and the second byte is data. In the past I've received a few transmissions with errors detectable through the parity or XOR, but these did not cause an "avalanche effect" of errors. However, yesterday when I was running the radio setup, after ~20,000 transmissions (~60,000 bytes) there was an error, and after that error occurred, all transmissions were detected as containing errors. What I am hypothesizing occurred was that a single byte was dropped in transmission completely throwing off the sequence of bytes for a transmission. For example, the second "data" byte was lost, meaning the next transmission would consist of the first "sensor" byte, the third "XOR" byte, and the next first "sensor" byte. This error would continue to effect all later transmissions. I am operating a baud rate of 9600, with a nominal baud rate that is much lower. For this reason, I do not believe this is an issue with the serial buffer instead of a dropped byte, but I could be wrong. Is it possible that a byte would be dropped given the scenario I explained? If so, how could this be fixed in software/hardware? If it is likely to be a serial buffer issue, can this be solved? I know according to the Arduino core documentation increasing the serial buffer size beyond 256 may cause race conditions.

You need to learn the concept of synchronisation and proper packetisation.


text:
Clear GET params from URL
I have a simple GET webform that takes in text. Once that text is submitted the URL permanently displays the text as the parameter. This causes echoing issues when I check the input from the web form; the string I am looking for is always found because the URL is never cleared. I cannot use an HTTP redirect and am looking for a way to do this based upon code.

I'm voting to close this question as off-topic because their isn't even the word "Arduino", not even once, in the question. How is this suppose to be on topic?

@DatHa I am using the Arduino EthernetClient and EthernetServer

Try Stack Overflow

@DatHa the forum is specifically for Arduino so I assumed it was generally understood any programming questions were related to Arduino programming

Not my problem. The question has to be clear.
Be specific : program, schematic, part used.
See : http://stackoverflow.com/help/how-to-ask

This can only be done with a redirect. If you cannot use a redirect (because something about your web server doesn't let you) then you need to re-think your website design.

this is exaclty waht get are supposed to do. Use a POST or use a redirect; a POST is way better as the "back" button of the browser will take care of it


text:
How to represent -1 as a byte
I want to initialize the value of byte to -1. When I just use byte num = -1 the value ends up being a decimal 255. I've also tried int8_t number = -1 and then byte num = number but this didn't work either.

What are you trying to accomplish?

Note that while a byte cannot have the value -1, it can store a pattern of bits which could mean -1 when interpreted instead as a signed type, for example int8_t.  On a 2's complement machine like an Arduino the bits that mean -1 in an int8_t mean 255 in a byte. This kind of thing comes up often in communications when you have an array of bytes that contains the data of fields of other types.  However, you have to be careful when forcibly casting types as the rules of behavior that apply have various gotchas for the unwary, especially if you also cast to a type of different width.

If you show the code of what you are trying to do, then an appropriate suggestion can be made.  Without that, people can only explain the failure and guess at what your goal is.

A byte can't be -1. A byte can only store numbers between 0 and 255 inclusive.
Depending on the range of your numbers you could use a char (-128 to +127) or an int (-32768 to +32767).

Simply -1 can't be a byte. A byte is a number from 0-255. -1 is below 0. The Arduino reference defines a byte as "A byte stores an 8-bit unsigned number, from 0 to 255.".

As the other two users have already mentioned:
A byte can only store a number between 0-255, which obviously means that -1 can't be stores as a byte.
I suggest storing it as a positive number, and then when you want to use it just multiply it by -1, which will turn it into a negative one.
Example to convert positive number as a byte to a negative number:
    negativeNumber = positiveNumberStoredAsByte * -1


text:
Entering integers as bytes in serial monitor
I am doing some byte manipulation in Arduino, but when I enter an integer into the serial monitor, such as 1, and my program stores it as byte incomingByte, the value stored in incomingByte is 49 and not 1. How do I enter the ASCII equivalent of an integer?

The serial monitor is meant to let you enter text, not arbitrary binary data. You can parse the text into numbers in the Arduino.

You can convert it in your program. For a single digit you can easily convert using value = incomingByte - '0'; For multiple digits you need to separate the ascii out into digits, subtract 48 ('0' is a simple way to do that without having to remember the ascii value of 0)  and then add them together with the appropriate *10^n scale factors.

Using the Arduino IDE Serial Monitor, there's not much you can do. But you can use a different serial-port terminal such as RealTerm (for Windows, if that's your thing) which allows for a wide array of serial port nitty-gritty details.

Check out the ASCII table.
When you enter 1 into the Serial Monitor you are telling it to send the (ASCII) character 1 - which is represented by the decimal value 49, so the byte that is sent is 49.
I don't believe it is possible to enter the decimal value 1 into the Serial Monitor (you'd have to find some way of entering SOH via the keyboard), so the only option is to recognize and accommodate that on the Arduino end.
The usual way to do this is to subtract 48 from the received value. However this is typically written as - '0' which is actually subtract the ASCII value of 0 (this helps indicate that you converting from ASCII)
So...
int intVal = incomingByte -'0';
... should work fine for you if you are receiving single digit integers.
However, if you also want to accommodate multi digit integers (e.g. 123) then it becomes more complex requiring converting each byte to it's integer equivalent and then multiplying it by 10 to the power of it's position/column...
123 = (1 * 10^2) + (2 * 10^1) + (3 * 10^0)
This is a fun little coding task in itself, but if you're not into that kind of thing then parseInt('123'); will get you going faster...

You can do this little trick:
void loop()
{
while (Serial.available() == 0); //waiting for input
int val = Serial.parseInt(); //read as integer
}


text:
XBee: How do I create a packet?
I am currently using a simple protocol I created to send three bytes (unit information, data, and XOR) individually over an XBee radio (3 bytes are considered a single transmission). However, this is not always reliable if a byte is dropped. For this reason I'd like to encapsulate each individual byte as a packet in a way that the Arduino could identify which byte is which and if a byte is lost then just wait for the next transmission. What I am not sure about is creating a packet. I haven't been able to find any tutorials or example code.

The biggest mistake people always make with serial communications of any form is to just send raw data over the connection. While you might just about get away with that on a 100% reliable direct serial connection over a short distance, as soon as you introduce anything with any form of uncertainty to it you are, as you have seen, doomed to failure.
So you have to come up with a reliable method of transferring data in such a way that the receiver knows that it has received valid data, and how to find valid data.
So you need to create a packet. That's not something where you just wave a magic wand and a packet is created. A packet starts it's life in your own head.
In order to reliably transfer data there are a few things you need to consider from the point of view of the receiver:

Where is the start of my data?
How much data is there?
Is this data correct?

The receiver has to have some way of knowing where the start of a packet is amid the torrent of bytes it is being sent. It needs to look out for something unique, something it cannot mistake for anything else. This is called synchronisation. It is often done with a specific sequence of bytes (known as a preamble) that can, through various means, never appear anywhere else.
And at that point things start to get a little more complex, for now you need some way of wrestling that kind of thing into a system that can only send bytes of 0 to 255 with no way of distinguishing raw data from control information like this synchronisation sequence. And that is where the concept of escaping comes in. This is where you nominate certain byte values as control bytes and decide that these bytes will never appear in your data without some kind of marker to say they are data bytes. A common escape marker is 255 (used in the telnet protocol) or 27 (the ANSI ESC character) although any character can be chosen.
For instance if you choose to have a synchronisation sequence of 0xAA, 0x55, you can then decide that neither of those bytes will ever appear in your data without first being preceeded by character 0xFF. So if you happened to have that sequence in your data you would expand it out to 0xFF, 0xAA, 0xFF, 0x55.  But what if you want to send the value 0xFF, in your data? How do you handle that? Well, you also escape 0xFF as well. 0xFF, being the escape character, has no actual value in the data. It only says that the next character must be interpreted as data. So to send 0xFF you would actually send 0xFF, 0xFF. Your receiver sees the first 0xFF and thinks "ah, the next byte that arrives, whatever it is, just be data." It then gets a second 0xFF and knows it is data. (Actually this is the opposite of escaping which says the next character is a control character, but the underlying concept is the same).
If it ever sees 0xAA, 0x55 then it knows, without a shadow of a doubt, that this is the start of a packet, or random noise. And that is where the next two points above come in: Validating your packet.
If your packets are always the same size then all you need to know is how many bytes to expect, which can be hard coded into your software. If you have different sizes of data to send then you also need to tell the receiver how big the data is. This forms part of the packet header. A small block of meta data that preceeds the actual data that holds information about the packet. Depending on your topology that could be things like the size of the data, where the packet came from, where it is going, etc, and maybe a checksum, though some people like to put the checksum after the data since it simplifies sending.
And then there is the checksum. Possibly the most important thing next to the synchronisation. And so easy to get wrong.
Having a checksum that is too simple is not so good. It can be fooled. That is, if values get corrupted in the data with a simple checksum it is far more likely that the checksum still says it's correct than with a more complex checksum. You should read up on existing checksum algoritms, such as Cyclic Redundancy Check (CRC) and things like the checksums used in IP packets. All are good lessons on how to deal with checksums properly.
So far we have just tackled the serial equivalent of UDP - throw a packet at a receiver and hope it gets there. Doing anything more reliable becomes much more complex. If you want to know if your packet actually got there you will need your receiver to acknowledge reception, possibly including some information about the packet it received, such as a sequence number. If the transmitter never receives that acknowledgement it needs to send the packet again, which means it needs to remember what the packet is that it sent. So you need a packet buffer, or even better, a packet queue. And timeouts. And sequence numbers.
That latter is most important. A sequence number is a unique (or unique over a reasonable period of time) identifier for a packet. When a transmitter doesn't receive an acknowledgement is it because the receiver never got the packet, or that the receiver did get the packet but the acknowledgement never made it back to the transmitter? If the latter then the receiver is liable to get the same packet multiple times through retransmission. By including a sequence number the receiver can go "hang on a moment, I have seen this packet already" and it can throw it away sending a new acknowledgement in the process.
So as you can see, reliable communication isn't as simple as just sending data, or even sending data in the form of a struct. There is a whole lot more to learn and understand.
I suggest you read some of the IP networking RFCs to learn more about reliable packet transmission and reception.
Oh, and I haven't even touched on sliding window reception and such like for how to best program your receiver software...

Perfect! This is far superior to anything else I have read online

The x-ctu xbee config tool has a few options worth exploring
such as error checking. This means the xbee would do the work.

OR using the Arduino(s)

Adding a couple more bytes to you your current system with a checksum
of the first 3 bytes would be a simple way to check for a valid
packet.
You could also use a struct of values (along with a checksum).
      Bill Porter has written an Arduino Library called Arduino Easy    Transfer. The library is designed to send and receive a
struct    along with checksum validation. This is an overview page for the library.
Sending and receiving structs over Serial is also covered here


text:
Where can I find the Arduino Mega core code?
I am looking to modify the receiving hardware serial buffer size for the Arduino Mega. To do so I need to redefine it in HardwareSerial.h in the core code. However, I can't seem to find a copy of the Arduino Mega core code. A search for HardwareSerial.h on my computer returns no results. I am using Windows 10.

And how / where on your computer did you search? Did you look inside the Arduino software itself?

Here https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/HardwareSerial.h

Arduino Mega is part of the Arduino AVR Boards core. The location of that core depends on whether you are using the core version included with the Arduino IDE or have updated the core version using Boards Manager(in which case there will be multiple copies of the core installed on your computer but only the updated version will be used). The easiest way to find it is:

Tools > Board > Arduino/Genuino Mega or Mega 2560
File > Examples > EEPROM > eeprom_clear
Sketch > Show Sketch Folder
Move up folder levels until you reach the avr folder.
If there is a version number folder in the avr folder then open that folder.
HardwareSerial.h and the rest of the core files are located in cores/arduino.

Remember that you will need to redo any changes to the core after any Arduino IDE and/or Arduino AVR Boards updates.


text:
How to get the rightmost four bits from a byte
I have a byte that I am looking to break into 2 nibbles. The leftmost nibble I can get easily via shifting right 4 times. However, I can't figure out how to get the rightmost nibble. Any ideas?

Just mask it with an AND operator:
val = var & 0xF;


text:
Receiving a packet via XBee radio
I am sending a packet of sensor information over an Arduino XBee setup. The first byte of the packet is the packet header for synchronization. The second byte is the number of bytes in the packet (excluding header and packet size byte). The first byte of the packet payload is an identifying number for the sensor. The second payload byte is the data from the sensor. The third payload byte is an XOR for simple error checking. The first payload byte for the sensor ID will never need to be escaped, but the other two payload bytes may need to be escaped. The following is code I wrote for sending a single packet:
Serial.write(PACKET_HEADER); // Packet header for synchronization
Serial.write(calculatePacketSize(data, XOR)); // Size of packet
Serial.write(unitInfo);
// Check if the data byte needs to be escaped
if(data == ESCAPE || data == PACKET_HEADER) {
    Serial.write(ESCAPE);
}
Serial.write(data);
// Check if the XOR byte needs to be escaped
if(XOR == ESCAPE || XOR == PACKET_HEADER) {
    Serial.write(ESCAPE);
}
Serial.write(XOR);

What I am unsure about is how to process a packet on the receiving end. One issue I see is that because there are a variable number of payload bytes, I cannot check via Serial.available() whether or not there are enough bytes to process the payload during this run through of loop(). How do I go about processing a packet, and making sure the packet was received error free? I need to just discard incomplete packets or anything without a header.

A state machine is what you want. That and to increase your preamble to two bytes, not one.  The reason being is that due to the escaping of the preamble character in the data it is impossible to have that character twice in a row. By then having it twice in a row as the preamble it is unambiguous that it is the preamble.
You should also (if needed) escape the packet size:
Serial.write(PACKET_HEADER); // Packet header for synchronization
Serial.write(PACKET_HEADER); // Packet header for synchronization
uint8_t ps = calculatePacketSize(data, XOR); // Size of packet
if(ps == ESCAPE || ps == PACKET_HEADER) {
    Serial.write(ESCAPE);
}
Serial.write(ps);
Serial.write(unitInfo);
... etc ...

You might like to abstract the escaping into a function:
void sendEscape(uint8_t c) {
    if (c == ESCAPE || c == PACKET_HEADER) Serial.write(ESCAPE);
    Serial.write(c);
}

Then you can just call:
sendEscape(calculatePacketSize(data, XOR));

etc.
Now for receiving. Implement a Finite State Machine. In that machine you have a number of states, such as look for first preamble, look for second preample, look for size, look for id, and look for data. As bytes arrive they trigger the next state.
So you start by looking for the first preamble byte. When that arrives it triggers looking for the second preamble byte - any other byte besides the second preamble byte causes the FSM to reset. If it arrives, then it triggers the reading of the packet length. And so on.
In pseudocode it may be something like:
State is idle.
If character available:
    Read character into variable C

    Select on state:
        State IDLE:
            If C is PACKET_HEADER:
                Set state to PREAMBLE
        State PREAMBLE:
            If C is PACKET_HEADER:
                Set state to GETSIZE
            Else
                Set state to IDLE
        State GETSIZE:
            If C is ESCAPE and you haven't just seen ESCAPE
                Remeber you had an escape
            Else
                Store C in variable SIZE
                Clear array DATA and prepare for reception
                Reset Seen ESCAPE flag if needed
                Set state to GETID
        State GETID:
            If C is ESCAPE and you haven't just seen ESCAPE
                Remeber you had an escape
            Else
                Store C in variable ID
                Reset Seen ESCAPE flag if needed
                Set state to GETDATA
        State GETDATA:
            If C is ESCAPE and you haven't just seen ESCAPE
                Remeber you had an escape
            Else
                Append C to array DATA
                Decrement variable SIZE
                Reset Seen ESCAPE flag if needed
                If SIZE is 0
                    If checksum matches
                        Process packet
                    Set state to IDLE

The main thing to watch is the remembering (and subsequently forgetting) that you have just seen an ESCAPE. That way you can know if you have two ESCAPE characters in a row and you only discard the first one - the second gets handled as a real character.
The beauty of an FSM is that at any point in the sequence, if you decide that the packet is invalid (maybe the size is too big, or the sensor ID is invalid) you can just reset the FSM to the IDLE state and reset any flags/counters and you instantly start looking for a new packet.


text:
Esp8266 not working
I connected all the pins as in datasheet, except ch_pd.
But when I connect ch_pd to 3.3 V , the red light on esp8266 goes dim. I used 3.3 V, 250 mA power supply. What is the reason for this?

Link to datasheet? Link to ESP8266 device used? Image of how you have wired it up?

Recommended power supply sourcing capabilities are about 1A. In the firmware upgrading mode WiFi is possibly disabled, so it needs much less power.


text:
how to make transmitter and receiver for quad copter?
I want to make a transmitter and receiver for quad copter for that I am using two arduinos(UNO and nano).I am using 4 pots for controlling the brushless motors.For that I am sending 4 integer values of the pots and with that integer value PWM signals are generated at receiver by the arduino.Now I want to know how to send that 4 integer values of the pots serially using arduino.

The APC220 radio module provides a simple and economic solution to wireless data communications. Integrates an embedded high speed microprocessor and high performance IC that creates a transparent UART/TTL interface, and elminates any need for packetizing and data encoding. Use this module as this works as a pair and more intriguing part is that "it" can transmit over a km away.
link ~http://www.dfrobot.com/index.php?route=product/product&filter_name=apc&product_id=57#.VWeKIVWqqko

Thanks,that's fine,but I want to know how to convert parallel data to serial data of the integer values using arduino.

Just elaborate on the data type you are talking about, then may be you can be directed properly


text:
How to call a file from the arduino?
I am aware of the simplicity of the question.  Nevertheless...
I need to code into the arduino the execution of a file.  More precisely a .exe.
To put things in perspective.  I have little to no knowledge of coding.  Yet I need to put together a photocabin.  I have the arduino to count the coins inserted to my coin collector and I need to take a picture when the precise ammount is reached.  Then reset the ammount to avoid taking more pictures.
here is what my code looks so far: (taken from the examples on the arduino page)
const int coinInt = 0;
//Attach coinInt to Interrupt Pin 0 (Digital Pin 2). Pin 3 = Interrpt Pin 1.

    volatile float coinsValue = 0.00;
    //Set the coinsValue to a Volatile float
    //Volatile as this variable changes any time the Interrupt is triggered
    int coinsChange = 0;
    //A Coin has been inserted flag

void setup()
{
  Serial.begin(9600);
//Start Serial Communication
  attachInterrupt(coinInt, coinInserted, RISING);
//If coinInt goes HIGH (a Pulse), call the coinInserted function
//An attachInterrupt will always trigger, even if your using delays

}

void coinInserted()

//The function that is called every time it recieves a pulse
{
  coinsValue = coinsValue + 0.05;
//As we set the Pulse to represent 5p or 5c we add this to the coinsValue
  coinsChange = 1;
//Flag that there has been a coin inserted
}

void loop()
{
  if(coinsChange == 1)
//Check if a coin has been Inserted
  {
    coinsChange = 0;
//unflag that a coin has been inserted

   if(coinsValue >= 0.30)
  {
       here goes the code to open a file, then the code to reset coinsValue

  }
  }
}

Thanks a million.

There is no way the Arduino can run a .exe on your PC. At most it can send some kind of signal to say "Hey! PC! It's time to run the program!". Simplest thing would be to send it through the serial port. You need some process on the PC side listening for this signal and acting accordingly. How you do that is more a Windows programming issue than a real Arduino question.

How do you tell apart different type of coins?
What do you use to take the picture?

That was not your original question and is probably best as a question in itself.

@igor I use a coin colector sending out pulse signals to tell different coins apart. from sparkfun.com I will be using either a webcam software or eos utility I have not yet decided.

First of all you need to develop a windows app. You can achieve this by downloading visual studio express for windows desktop from here. Then you must create a project in your language of your preference. You will have to add a serial port component and set the properties to match your arduino serial ones. Then from the event that handles the "data available" of your serial port you can check if there is an incoming character from your arduino and create an if statement that runs the .exe file. Then you must add serial.print('c') to your code when there is a coin inserted. By doing so, you will manage to communicate between arduino and your windows app.
More info and full guide can be found here

Tried the solution and have managed to implement it so thank you.

I used the following code to run a program, not from the arduino, but from software listening to a specific character sent from the arduino.  Thanks for your help.  I share the code that I used.  It doesn´t need to print the character, but I copied it exactlyy from microsoft help pages (lost the link). I just aded the if statement and the start.process part (I got this from a stackoverflow answer).  Without any further delay:
using System;
using System.IO.Ports;
using System.Diagnostics;

class PortDataReceived
{
    public static void Main()
    {
        SerialPort mySerialPort = new SerialPort("COM3");

        mySerialPort.BaudRate = 9600;
        mySerialPort.Parity = Parity.None;
        mySerialPort.StopBits = StopBits.One;
        mySerialPort.DataBits = 8;
        mySerialPort.Handshake = Handshake.None;
        mySerialPort.RtsEnable = true;

        mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

        mySerialPort.Open();

        Console.WriteLine("Press any key to continue...");
        Console.WriteLine();
        Console.ReadKey();
        mySerialPort.Close();
    }

    private static void DataReceivedHandler(
                        object sender,
                        SerialDataReceivedEventArgs e)
    {
        SerialPort sp = (SerialPort)sender;
        string indata = sp.ReadExisting();
        Console.WriteLine("Data Received:");
        Console.Write(indata);
        if (indata == "c")
        {
            Process.Start(@"C:\Users\Laptop\Desktop\print.ahk");
        }
    }
}


text:
Starter Kit for Arduino Cookbook
I have this book here about Arduino. What kind of Kit should I purchase to get started? Would this work?

I'm not yet sure about what I'd like to do with Arduino, so I may prefer a pretty Universal Kit in order to cover a pretty wide range of projects.
Except this, I won't need any advanced stuff, at the moment, as a beginner I may want to understand the fundamentals, so will surely need LEDs, maybe screens, and other basic stuff like that.
Later on I may try to go for Wireless modules, but not at the moment as a beginner.
Any ideas? Hope to have clarified more or less what projects I'm aiming to, yeah the range is wide, but restricted to basic beginner projects.

I'm not yet sure about what I'd like to do with Arduino - Arduinos are a lot of fun, and you can learn a lot from them. However asking for a suitable kit for "I don't know what" is a big ask. I suggest a minimal kit (or just a plain Arduino) and do some of the tutorials. I think this question should be closed as too broad, but I'll leave it to my fellow community members to make that decision.

The advantage to a kit is it includes a lot of stuff. You'll have a big selection of sensors and parts to choose from.
The disadvantage to a kit is it includes a lot of stuff. You'll have bought and paid for a big selection of sensors and parts, some of which you may never use.
Since you linked to Amazon, I assume you are someplace where shopping on line is convenient. In that case I'd start with a small handful parts and let your developing skills and interests guide your future purchases.
A bag of LEDs with resistors included is really basic - start there. I make up a dozen or so of them with a resistor permanently soldered to the cathode (ground) side of the LED (it doesn't matter which side you choose, just be consistent for your own sanity later on!) These are quicker to wire up on a breadboard than using separate LEDs and resistors, and they make a quick and dirty logic-probe ("Is there 5v on this board?", "Is this pin HIGH or LOW?") or output device.
A handful of push-buttons, often called "Tact switches", a few analog thermo sensors (LM34 or LM35 f/ex), and a light sensor, would start you off inexpensively while providing you opportunities to learn how connect these devices, some basic electronic theory, and some programming skills.
By then, you'll have a much better idea what kinds of projects you want to pursue and the parts necessary to build them.

Yeah guess you're right! Bought a very basic kit without an LCD and other stuff, this way I'll save some money and get a separate LCD for just 3€ instead of spending 20€ more for another kit which includes an LCD screen but even lots of other stuff I'm not sure I'll use it, at least at the moment..

The Stack Exchange format is not well suited for opinions.  That said, people are apparently giving the kit good reviews.  And I see hardware that appears to allow for several projects (LED arrays?, motors?, ultrasonic-distance-measurement?, IR-remote-control?, Alpha-numeric-LCD?, 7-segmet-LED-display?, ect).  Which is more than you need for basic Arduino projects.
In general, it would make the most sense to find a kit with a book rather than obtain a book and a kit separately. This is because slight differences between the written material and independently obtained hardware will cause confusion.  This is generally not a problem for experienced embedded developers.
Keep in mind that embedded processor projects are half hardware and half software.  Since the hardware has already been collected, the majority of activity will be in software.  If this paradigm agrees with you, good luck & have fun.

Mmm you have a Kit to suggest?

The end goal for Stack Exchange is to have a list of clear questions with concise answers that can be searched through.  Opinions do not fit into that paradigm. But, no, I have no specific kit to suggest.  Only, for a beginner, to find a kit with a book so it is clear how to proceed.  While there are many standards for electronic parts, there are also many variations.  It sometimes only takes 1 or 2 variations to make a part unusable to the beginner.  That is why I am suggesting  to buy a kit and book together.

I'll add this...  I did not see a servo motor in that kit.   Servo motors are more expensive because they contain a computer-to-motor interface inside.  Most beginning Arduino uses find servo motors fun to work with.  And they are easy to interface (both hardware and software) to an Arduino.  You can easily pick up servo motors that work with Arduinos independently of buying an Arduno kit.


text:
How to make a Smart Light Bulb?
I was wondering what I would need and what I should do, to make a Smart Light Bulb, like the Hue one from Philips.

I know these light bulbs can be controlled by their Apps from the smartphone, is there a way I can achieve this too?
What components would I need to purchase?
Is there a reference or a tutorial on how I should program this light bulb?

What has this got to do with the Arduino? I'm going to close this question. Feel free to edit it with new information. Thanks for your understanding and cooperation!

This is a question of how to achieve this with Arduino, that's why I posted it here @NickGammon

Which Arduino were you planning to insert into the light bulb? Your question is still incredibly broad. You may as well say "I would like to fly to the moon - is there a way I can achieve this?". What components would I need to purchase? - well, a light bulb and an Arduino? This sounds like you are trying to get us to do a project for you, sorry.

I asked what to start with, if you got it in that way I'm sorry as It isn't meant to be that. @NickGammon

You could use an ESP8266 NODEMCU. There is an example for making it emulate a Hue bridge ( https://github.com/probonopd/ESP8266HueEmulator ).
To have the official bridge control your lights would take Zigbee and finding out the protocol that Philips uses. Their API is open source, however the zigbee protocol they use is not afaik.
ESP8266 is a very cheap solution that works with arduino ide and does not need an arduino. There are powerplugs which have an ESP8266 in them (https://www.itead.cc/smart-home/sonoff-sv.html)

Mh cool, thank you, will have a look at it tomorrow morning and then will let you know :)

Oh, so this would work with iOS too right? I mean, the bulb would be then controllable by the iOS hue app? Or not?

yes it will work with any Hue app !! so also on iOS :)

oh when getting an esp8266.. make sure it is esp8266-12e. the older ones only have 2 outputs and very limited compared to the newer model. you be up and running for around $10.

Oh, and the light bulbs, how should I make them? I mean the first link is for the hub, the second one for the light bulb?

yep :) the second link is esp8266 with a relais connected to a gpio port, you can load the bridge software on there or get a seperate esp8266 to play bridge and get more bulbs to listen to your Leonardo Hue ....

Alright! Will get to work asap and will let you know! So for now this is the right answer, thank you!

Let us continue this discussion in chat.


text:
How to get started?
I'm a guy who loves the tech world, but more in particular the Robotic one.
I wanna start developing/making my first creations of robots or sort of.
I won a little board from Texas Instrument from the Maker Faire here in Rome, but I don't really know how to get the best out of it, and specially what to buy as extra stuff to start making. I guess the best way to start would be a kit (?) So I saw the Arduino one (Genuino one as I'm out of the USA).
My question then is: What's the best way to start diving into this world? Feel free to consider or ignore the fact I got that little board.
My Board:
http://www.ti.com/tool/msp-exp430f5529lp

This is a very broad question. Can you focus it? Tell us what you're wanting to learn to do next & a bit about what you already know how to do.

The launchpad isn't even an arduino board...

I know @TheDoctor

Robotics is a very large field covering a lot of disciplines, such as:

Motor and sensor control and interfacing
Mechanics and kinematics
Visual and optical processing

And many more.
The Arduino side of things is mostly concerned with the first point - the interfacing and control of motors and sensors, etc.
For robotics probably the most important thing to get to grips with is servo motors.  If you can leave the mechanics side of things to someone else for now (to build a robot from the ground up would require metal working skills, welding, and more, which we're not really able to help you with) and start with a "kit" robot of some form to get you going that would be the best entry point IMHO.  One such kit that I have been looking at recently and is easily available on eBay is the "6DOF" robot arm (note: the servos are sold separately normally).  Just add cheaply available standard model servos and interface them to an Arduino and you have a robot arm you can program to do things.
And that's when the fun starts.  Learning to program for robotics does often involve some more advanced mathematics, so be prepared to have to do some study...
As for what board to use?  Your MSP430 board is more than capable of controlling robotics.  Not sure about the programming aspect of it - in general it's TI's own IDE and programming environment, but I do know that some of their boards (not sure about that one) are supported by a port of the Arduino IDE.

First, thank you for the really well detailed answer. Second, I saw this kit from Arduino, what do you think would be better? I have some programming skills but I lack on C++ atm (shame on me). So what's your opinion again?

@LeonardoFettucciari That kit is great for getting to grips with basic sensors and programming.  It may be a good start for you and then maybe think about buying some kind of robotic kit (there's all sorts of styles around) at a later date once you get into the idea of how things work.

Alright, I'll take advantage of these days deals then, and will surely let you know how I'll find that kit. For now, thank you for your opinions and helpful advices!


text:
ESP8266 and Arduino bidirectional streaming from and to a website
I was looking for some easy tutorial on bidirectional communication via ESP8266 connected to Arduino UNO. I want to send and receive strings from and to JQuery based website.
However, I couldn't find any answers on this because most of them are about working directly with ESP. It's probably easy thing to setup but I'm totally new in working with network communication ;(
At this moment I know how to set AT for ESP as client and receive messages with pin number to toggle:
AT+RST
AT+CWMODE=1
AT+CIPMUX=1
AT+CWJAP="user","pswd"
AT+CIPSERVER=1,80
AT+CIPSTO=10

And JQuery for buttons (data is their ID) form one of tutorials:
$(".led").click(function(){
    var p = $(this).attr('id');
    $.get("http://192.168.1.14:80/", {pin:p});
});

Problem with this is whenever I send something the ESP gets the value and prints info but then it disconnects after 10 seconds (defined time) and when I hit the button again it reconnects and I can't do more (for example: send another value) during the time when it's connected.
Is it normal behavior? How to make it possible to send many messages when it's still connected to the port without waiting to reconnect? Can I make it in more "streaming" way? And how to make this bidirectional? Any advice on configuring the device will be helpful.


text:
2 way RF with Virtual Wire / 315 / 433 MHz
I am trying to figure out how to get 2 Arduinos to talk back and forth from one another using cheap simple RF modules. I have a total of 4 RF modules (2 receiver and 2 transmitter) and 2 Arduinos. I need Arduino A to send about 3 variables to Arduino B, and I need Arduino B to send 1 variable back to Arduino A.
When I attempted 2 way communication, I programmed Arduino A to broadcast constantly, while having Arduino B trade off between receiving once, then sending once on every other loop. This resulted in Arduino B also only broadcasting, and was not receiving any signal from Arduino A.
My other attempt was to have Arduino B send for about 250 ms, then receive for 250 ms, and repeat. This worked as long as Arduino A was only broadcasting, but as soon as I had Arduino A doing the same thing, the clock on each seemed to be slightly off and there would be periods where both Arduinos were sending, or where both were trying to receive, so it was also very unreliable.
Is there a reliable way to do two way communication with this kind of hardware, or would I need transceivers to do this kind of project?

What bit rate are you using? And what is the message size? I would start by increasing the receive period and add a listen-before-send logic.

You should synchronize communication, instead of relying on just time. E.g. send 250ms after a message was received.

@MikaelPatel 2000 bps and a 4 byte message size. I tried increasing the receive period when I had it trading off with my first attempt. I wound up having it send once for every ~2000-4000 times it would read. That was the minimum it took for me to actually get it to receive anything, but that doesn't work well because when I have the other arduino do that same thing, they don't send frequently enough to reliably receive messages.

If the RF Modules you are mentioning are the ones I am thinking of they do seem to be very special bits of kit.  I have tried Bluetooth you can get cheap HM05 modules (Might be the wrong number you want the one that can be the master or slave).  These were a bit better but don't have the range.
My personal fav at the moment would be a ESP8266, no I have never hooked one up to an Arduino, but it can be done fairly easily.  You should get 100m range (in ideal circumstances) and you can get aerials to boost that.  You can also set one up as a repeater between two wifi segments.
Whatever you decide you might want to change your code slightly so that one Arduino sends a time signal and the other doesn't send its data until its turn.  Or give them GPS receivers and pull the time from there.

With VirtualWire, an Arduino can only send, or only receive. It can't do both at once. It is basically like software serial, but with Manchester encoding of the message.
Write your code for the sender to send once, and then listen for a response.
If no response after some interval, try sending again, and then go back to listening.
Perhaps try one more time.
Write your code for the receiver to always be listening, and not reply until a message is received.
Add some code to indicate when a good message is received as an aid to debugging.
You should be able to connect Tx to Rx and Rx to Tx (and Gnds) between the two Arduinos and get the sequence to work back and forth, and then connect the RF modules and have them work as well.
I think the encoding done by Virtual wire adds 37 bytes to the message, which the library takes care of, so the end result is only the data that was sent.
You might also try the RadioHead library, of which VirtualWire is one part now.

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


text:
Convert Long to binary - least signifant bit first
I have found an Arduino function which converts a 2-bytes-long-value to a binary value.
e.g. I call sendCommand(0x05) And it gives me an output:
00000101
void sendCommand(unsigned long command){
  for (unsigned long  mask = 1UL << (7);  mask;  mask >>= 1) {

    if (command & mask) {

    Serial.print( "1" );
    } else {

    Serial.print( "0" );
    }
  }
}

my Problem is, that I want to have the Least significant bit first. How do I have to adjust this function to achieve this?
e.g.
sendCommand(0x05)
shall give an output:
10100000

void sendCommand(unsigned long command){
  for (unsigned long  mask = 1UL; mask<256UL;  mask <<= 1) {

    if (command & mask) {

    Serial.print( "1" );
    } else {

    Serial.print( "0" );
    }
  }
}

PS a long is actually 4 bytes long. But your code only uses 1 byte of it.


text:
Digital Input with long cable - flickering values
I have an Arduino Nano with two attached Motion sensors "PIXNOR HC-SR501". This sensor puts 5V on its middle Pin, when it detects motion. I have connected this Pin to my Arduino and read the value with digitalRead
Here is the simplified code of my loop:
void loop() {
    motion1 = digitalRead(motion_pin1);
    motion2 = digitalRead(motion_pin2);

    if(motion1== HIGH) {
      if(debug){
        Serial.println("Motion 1");
      }
    }
    if(motion2== HIGH) {
      if(debug){
        Serial.println("Motion 2");
      }
    }

    // Wait 1,0 Second
    Sleepy::loseSomeTime(1000);
  }

Problem is... This used to work fine, but I had to extend the cable to the motion sensors from ~10 cm to 500 cm. Now I have the problem, that the Arduino sometimes (quite often) detects voltage on the motion pins, although there is no motion. I guess the Input-pins are is too sensitive?
What can I do to prevent this flickering?

That device (datasheet) puts out 3.3V on the OUT pin, not 5V:

◦ TTL output: 3.3V, 0V

The excess cable is most likely picking up EMI and creating spurious pulses on the input. There are two basic ways of combating this:

Increase the drive strength (especially the sink capacity) of the output
Implement a balanced line communication system

You can combine both those quite easily, whilst at the same time boosting the output voltage to 5V using a 74HCT04 hex inverter chip (make sure it's the HCT variant).  Powered from 5V it will boost the logic level from 3.3V to 5V, and it will have a greater drive strength than the PIR chip alone.
Then the trick is to use multiple gates in the right way to make a crude balanced line system:

Basically you're double-inverting the signal so it remains the same logic level (high = high, low = low) but has higher drive strength, and you're also single-inverting the signal so it has inverted logic (high = low, low = high).  You then connect those to two different IO pins on the Arduino. Read both pins (instead of just one) and as long as the signal are opposite (Q = HIGH and !Q == LOW) then you have a valid signal. If both signals are HIGH then you have noise and you can ignore it.
You also need to ensure you select the right kind of cable. Ideally you need a cable with at least one twisted pair in it so that the Q and !Q signals are twined around each other. This ensures that if EMI is induced into the wire it's induced into both signals equally.  CAT5 Ethernet cable is often quite a good choice.

Thank you for this very detailled information and for pointing out my mistake with the 5V output of the sensor!

For implementing a balanced line, the MAX487 transceivers are quite cheap (less than 3 € apiece). You can feed a 3.3 V logic signal to the sending one (VIH(min) = 2.0 V) and you get 5 V on the receiving side.

Ouch, that's expensive. 74HCT04 can be purchased for just a few pence each in SMD, or a few tens of pence in DIP.


text:
Simple network protocol to communicate between N slave arduino and 1 central arduino?
i am looking to communicate text ( 40 char for each message ) between N arduino and a central one ( Communication is one way slaves to Master).I am looking for wire communication with 1 to 5 m distance.Does anyone know the best approach to do that ?
Vincent

You have quite a few options available to you as your requirements are filled by quite a few protocols, I am not going to list all. You can use things such as I2C, CAN, RS-485, RS-232.
You can find a few good examples from this EE.SE post from a search.
The CAN option is quite a good one for your application and is easy to set up and there are quite a few libraries available for the common chip MCP2525 and MCP2551. Yo can also get a 'shield' with this functionality from sparkfun.
The other options are discussed in the linked EE.SE post with regards to RS-485.
I2C can be implemented with the Wire library of arduinos and other libraries.
You can use RS-232, but I don't think it will be immune to noise at the distance you want, but you can still try. What you can do is use a multiplexer, such as this one CD74HC4067, and use it to multiplex the TX line from each node to the RX of the master.
From SFE's site:

For example, you could use it to connect the TX pins of 16 devices to one RX pin on your microcontroller. You can then select any one of those 16 devices to listen to. If you want two-way communications, you can add a second board to route your microcontroller’s TX line to 16 device’s RX lines. By using multiple boards, you can create similar arrangements for I2C, SPI, etc.

You will probably want to add some sort of checksum/CRC to the data you send over the network too.

IMHO you should first decide your network topology.
If you want a "star" network, i.e. a network when every node is directly connected to the central one, you can use any protocol. Maybe even a multiplexed serial interface.
If you want a daisy chain interface or a bus one use can or RS485.
Personally I'd avoid I2C (it's good for on-board communication, but if the device is a few meters away the noise can break it).
My suggestion: use serial over half duplex RS485: you can get very low price physical interfaces. Since it is half duplex, only one can "speak", so the master first sends an address, then puts itself in listen mode and waits. The slave whose address was told puts itself in sending mode and sends the data.
This way you will have a bus (so you can simply attach a node to another node without having to place a wire till the masater) and you'll have a simple bus logic which will prevent the information to collide. And, most important, RS485 is very strong (up to 1km if I remember well).
CAN can (sorry) be simpler to use, since the anti-collision is "embedded" in the protocol, but it's a bit more complicated to use (you'll need a transceiver and to implement the whole logic in the microcontroller instead of using a dedicated peripheral like the serial interface).

Hello,Thanks for your answer,I am looking at a star network topology ( i don't want to have the complexity of collision management).It seem more complex than i thought because RS485 will require quite some component outside the micro-controller.I may have been naive thinking i could just code something in the micro-controller and they will talk together ( like I2C ).

With a star network topology you will have to use N interfaces on the uC or a multiplexer. N interfaces are fine if N < 4-5, but if it is larger you will need a multiplexer. And if you use that, well, you will definitely need a sort of handshaking (you don't want to turn the multiplexer in the middle of a "packet"). So you will have to deal with something analogous to collisions. As for other hardware, RS485 transceiver are usually 8 pin ICs that do not require external components. And I2C is a bus network where you need handshaking (just one master and N slaves) so the problem remains


text:
Arduino on breadboard Tension is 4.4V instead of 5 V,looking for some guidance
I build a circuit that work on breadboard now i try to prototype it,so i start solder it on a prototype board and the arduino is out of sync.So i check the tension and for some reason it's 4.4~4.6 on the Vin pin of Atmega328 so i try to find how to debug.I don't have a lot of theorical knowledge on electronic,but my thougt was as long as everything is plug in parrallel the tension should remain the same ( and i don't have any thing in serie) so for the tension to drop i may have something acting as Resistor, and i try to find how and what.
I use 22AWG 0.7mm wire o create a 5V line and my GND line on each side of the Atmega ( roughly 7 cm on each side),i start to wondering if it was not a bad idea. I have picture of my prototype bellow,but it's messy so not sure it help. My question is how to you proceed to troubleshoot this thing ? What are the step you do to find out where is the problem

Please edit your question and add a schematic diagram and a picture of the other side of the board.  Also say what your power supply is and if there is a voltage regulator on the board.  If your power supply puts out  4.4 to 4.6 V then it's ok for the "5V" line to measure  4.4 to 4.6 V.

Hi thanks,My input is 5V ( i measure it and it's from a generator ). The other side look like that frontside , i am drawing the schematic.

It's quite hard to see because a lot is in shadow. It sounds like, though, that you have shorted 5V to Gnd. Try doing a continuity test with a meter.

The yellow-boxed 5V and Gnd buses on the freetronics.com.au ProtoShield Basic for Arduino [like you used] already have copper strips connecting the holes.  The strips run on both sides of the board and the holes are plated-through, so there's no need (for this kind of circuit) to have additional bus wire running along above the boxes.  Having that extra wire there gets in the way of making changes, whether for debugging the circuit or for adding or replacing components.
From the frontside picture, it appears you may have a voltage regulator on board.  (However, I don't see the connections to 5V and Gnd, so might be misinterpreting things.)
If your board input is 5 VDC from an external supply, feeding that 5 V into a regulator will lose half a volt or so, which may account for what you are seeing.
However, let's instead suppose you are putting 7 to 12 VDC into an on-board 5V regulator and then measuring 4.4-4.6 V out.  One possibility is the regulator isn't working.  This can happen if the regulator's input or output capacitors are the wrong sizes or wrong kinds, and cause oscillation.  Diagnosing that kind of problem is straightforward if you look at the 5V line with an oscilloscope.  Another possibility is something drawing a lot of current (eg a couple of amps) and taking the 5V line out of regulation.  That's usually easy to diagnose because of all the resulting smoke and heat.
Drawing a good schematic is an excellent step to take to allow better problem debugging.
Other steps to take:

Measure the amount of current the whole board is drawing, or that the NRF24L01 is drawing.  (For the latter measurement, you might need to lift your ground lead off the NRF24L01 board and put the ammeter into the ground circuit.  In general you want all the grounds to be at the same voltage, so the voltage drop across the ammeter is a problem, but not much of one.)
Pull the '328P chip and see if that makes any difference.  In general, it's a good idea to work out a prototype board's power supply problems – such as shorts, reversed electrolytics, incorrect resistors – in advance of installing a microcontroller chip onto the board.
Remove the NRF24L01, if feasible, while debugging the power supply.  If you can't easily remove it, check your schematic and see if all of its pins except 5V and Gnd are open when the '328P chip is pulled.  If so, you can detach the NRF24L01  ground lead to take it out of the circuit.  If, during testing, you unsolder and remove the NRF24L01 board, consider making a socket for it from two 5-pin female header strips.

Thanks a lot ! I am looking at that ( i am trying to finnish my schematic,but my kicad skill are not the best). The onboard regulator is too convert 5V to 3.3V for my NRF24 and RFID-RC522.
Vincent

This is my schematic link . Btw does is a good way to post my kicad file on this forum ?


text:
Do I use 3,3V or 5V, when device supports both?
I have a general question regarding the power-supply of the electronic components, that are attached to an Arduino.
If I have a device that operates at voltages between 3,3V and 5V (e.g. this RS232 to ttl converter), what is the best way to connect it with the Arduino?

Connect 3.3V or 5V power supply between VCC and GND

I know, that you can not draw as much current out of the 3,3V Pin like on the 5V Pin. But what if I don't need much current anyways (like in the linked example)?
What ware the advantages / disadvantages of connecting it to 3.3V and 5V?

Using the MAX3232 data sheet , which is what the TTL Converter has on it's board :
The main difference between using 3.3v or 5v is on the receiver data line "R" (or Rout as it is called on the MAX3232).
Simply put, you want to power the TTL converter from the same voltage as your Arduino is using (3.3v or 5v). Meaning the voltage that your I/O pins will put out and accept.
The received data line R will go between 0 volts and Vcc.
You would NOT want to power the TTL converter at 5 volts if you are using the converter for a 3.3v Arduino, as the received data line would go to 5 volts when high. Actually Vcc - 0.1 volts (typ.)  (5 - .1 = 4.9)  as per this specification :

If you power the TTL converter from 3.3 volts, the received data line (Rout) switches between 0v and 3.3v   as shown here :

@Marla You didn't finish explaining what happens when you connect a 5 volt signal to a 3.3v Arduino pin (I know, it's obvious).

@linhartr22   Arduino says, "Owww", and then won't behave afterwards (permanent damage).  Some devices are tolerant to over voltage, and mention it in their specifications)


text:
port name showing up as gibberish
I'm running arduino 1.6.6 sketchbook, and been using the sketch book for my arduino uno for a couple of months. A week ago roughly it started acting weird, for a reason I haven't been able to figure out even after extensive googling.
I got Windows 10 educational version (free version thx to my uni).

In device manager, the board shows up correctly (named itself COM3 Arduino Uno)

I suspect it might have to do with drivers somehow, but reinstalls, updates, and every option I have tried so far has failed. The error that the sketchbook gives is avrdude: ser_open(): can't open device "\.\COM3?ðÕ&¬ôÕ&´æiúd??þÿÿÿÈð": The system cannot find the file specified.
Has anyone seen something similar before?

Can you bring up command line and run arduino.exe --port COM3 (you may have to first cd to the path where arduino is installed). See arduino manpage Just curious, did it stop working after the Tuesday update?

just did that, the load-in page for arduino runs for about 1 sec, and then the process kill itself.
About that update, it might be related, although haven't paid attention to updates so can't say for sure.

yes, as it should, but then when you re-launch the arduino IDE, it should remember the port setting as COM3. The menu will probably still be messed up, but the status bar should at least have the right port selected.

Correct, but doesn't solve my issue, as the status bar had the correct port selected already from before.

Ah well, that's why I didn't post this as an answer... I don't have a win10 system to test on. I thought maybe Arduino IDE was sending wrong port name to avrdude, but the --port setting should have fixed that.

Just noticed you're using Arduino 1.6.6 which was released only a couple weeks ago, can you try using the stable version 1.6.5 instead? Maybe this is a regression bug.

It looks like a badly terminated string in C - except it's java. Maybe you need a new version of Java installed?

I just tried installing the version 1.6.5, and downloaded&installed the latest version of Java, and restarted the computer. Didn't work though. Any other suggestions?

Problem was caused by the jdk, updating that solved it. Majenko's comment was helpful. Thanks

Unfortunately this problem is persistent. Same problem came back, and updating the jdk again doesn't fix it again. Any other ideas?

Try updating the IDE or restarting the computer.


text:
How to avoid that my arduino clicks eternally?
I have accidentally implemented a program that imitates the click of the mouse.
The problem is that now I can´t delete the program because each time that I connect the USB, the computer starts clicking everything and it is not possible to upload a new program.
Can I solve this problem?

That is actually pretty funny. Now I'll be sure never to write a program on my Arduino that resets my computer :+)

Hold the RESET button as you plug the Arduino in and keep it pressed all the time it's plugged into your computer.  Load Blink.ino into the IDE and compile it.  Press the UPLOAD button in the IDE and move the mouse to somewhere "safe".  Release the RESET button.
Do those last three steps in rapid succession and you should be fine.


text:
Using interrupts for two MCP23017
I am creating a simple shield with two i2c MCP23017 chips. Each MCP23017 has two interrupt pins, but the Arduino Uno only has two interrupt pins (pin 2 and pin 3).
The way I understand it, interrupts are there to tell the Arduino something has changed, so it can then poll the MCP23017 for the latest pin reads.
How can I connect the 4 interrupt pins to my Arduinos 2 pins?

Read the datasheet for the MCP23017. It tells you how to turn the two interrupt pins into one.

I see There are two interrupt pins, INTA and INTB, that can be associated with their respective ports, or can be logically OR’ed together so that both pins will activate if either port causes an interrupt. but I'm new to electronics so I'm not sure what this means. Do I need to connect a chip to the two pins then connect the output to one of the interrupt pins?

No, you need to keep reading, down to where it tells you what all the registers do.

The MIRROR bit controls how the INTA and INTB pins
function with respect to each other.
• When MIRROR = 1, the INTn pins are functionally
OR’ed so that an interrupt on either port will cause
both pins to activate.
• When MIRROR = 0, the INT pins are separated.
Interrupt conditions on a port will cause its
respective INT pin to activate.

This MIRROR bit is set by software?

Yes. You can also set the ODR bit to make it open drain, then you can wire both chips into one int pin with a pull-up, should you wish.

Thanks so much for your help - for my purposes I have two chips and two interrupt pins so enabling mirroring would work well. If you would care to move your comment to an answer I can mark it as accepted.

The MCP23017 (and it's sister the SPI-based MCP23S17) can have their interrupt pins set to "mirror" mode. In this mode both pins are internally joined so when an interrupt occurs on any port both pins activate.  This is done using the MIRROR bit of the IOCON register.  Using this will turn your 4 interrupt pins into just 2, one for each Arduino INT pin.
Should you want to add more in the future, or if you find you want to use one of the interrupt pins on the Arduino for something else, there is also the ODR bit in the IOCON register. This sets the interrupt pins to be open drain, which means that all of them can be wired together into just one INT pin on the Arduino. Add a pullup (or enable the internal pullup) and you have have many IO expanders on one INT pin. Of course, that then means that you have to poll all the expanders to find which of them triggered the interrupt, so could slow things down somewhat depending on how you are using it.


text:
Is there any way to prevent Arduino CLI from closing each time?
I prefer writing code in Vim, so I'd like to get a workflow going with the Arduino CLI. I used to use ino, but I didn't like the restructuring of the project, which meant anyone who downloaded the code having to use ino.
I can build and verify using /Applications/Arduino.app/Contents/MacOS/Arduino --verify MyProject.ino, which pops up a new instance of the Java IDE, then exits after verifying.
While this works, and works well, it's incredibly slow. Is there any way to keep the IDE open to save the few seconds lost from the IDE starting again?

Is there any way to prevent Arduino CLI from closing each time?

I would suggest working the other way around.

Start the Arduino IDE and set external editor in the Preferences (once).
Open the sketch file(s) in the Arduino IDE and VIM.
Edit the sketch file(s) in VIM.
Move to the Arduino IDE and Verify, Upload, Monitor, etc.
Repeat steps 3-4.

The alternative is to use a make based build system. An example may be found in the Cosa build system for Linux.
Cheers!
PS: VIM = any external editor such as GNU Emacs, TextEdit, etc.

I had no idea about the external editor! That would work for now. A Makefile would be the way to go when I have more time to look into it!


text:
All voltage directed to pin 3 when multiple pins are set to out put
I just finished testing a haptic device at university, and when I took it home I got the joy of finding the device not working. Here's what I can trace the problem to: when multiple pins are set to output (pin 2~11), pin 3 writes constantly to high and there is nothing I can do to make it stop.
Using a blinker program one pin at a time produces no problems, however when I run a blinker program that cycles through all pins, pin 3 is set to constant high. My actual code is similar in function but more complex. This program below though gets the same error.
void setup()
{
  for (int c =2; c<12; c++){
    pinMode(c, OUTPUT);
  }
}

void loop()
{
  for (int c =2; c<12 ; c++){
     digitalWrite(c, HIGH);
     delay(100);
     digitalWrite(c, LOW);
     delay(100);
  }
}

Is this a sign my arduino died? My device had been working for weeks on my prior code with no problem (and no updates).

That's a symptom that maybe just the MCU pin 3 is damaged. But it would help to know how your initial circuit (the one that may have caused the damage) and the blinking circuits were wired. Could you please post some schematics?

If your Arduino board holds the MCU in a socket (like the Uno), and you have a spare ATmega laying around, you can try and replace the MCU and test it again with your blinking program to see if pin 3 makes the LED blink. Just to check, you do have current limiting resistors between your IO pins and your LEDs, and you aren't (and weren't) drawing more than 20mA from each pin and 200mA overall from your MCU, right?

That's all assuming you're using ATmega's...

Or, if you don't have a socketed ATmega or an extra one lying around, you may want to acquire a whole other arduino and test with that to see if you can replicate the behavior. You don't necessarily need to buy the exact same model as the one you're experiencing the problem with, but that would be the best way to identify a problem with your code running on your original board.

Could you tell what you have plugged to each of pins 2 to 11? You may get erratic behavior (if not worse) if you source or sink too much current through many pins altogether (Arduino total current limits).

My wiring for testing = using a voltmeter.
The wiring for the actual project is running an array of electromagnets through motorbridges with never more than one pin on at a time. The set-up has worked for weeks with no bugs. It is bread-boarded, so I figured that was the problem at first. However the behavior is reproducible when only connect to a voltmeter.

It is an Arduino Uno, and I replaced the chip using a similar Atmega chip but not the same (ATMEGA328-PU 1135 to a ATMEGA328-PU 1036). The replacement has a different firmware (Duemilanove I think). I could get the blinker test program to run without a hitch, but the new chip doesn't handle serial communications well (something my project relies on) so I couldn't get it to work with my original code.

Here's the actual project here, if that will help anything.

The 4-digit number is a date code. You replaced it with the same chip made almost a year earlier.

imho, breadboards are for only the first moments of a design. Please please please get and use a sensor shield: https://www.google.com/search?q=sensor+shield Fritzing is also invaluable for illustrating circuits.

@e2r2i2k2 Do you use your voltmeter directly between the pin and the ground? It's not the right way to measure a voltage, you should at least put a resistor between the pin and the ground.

@e2r2i2k2 did you flash the UNO bootloader onto the ATmega after you replaced it? By the way, is there a reason why you replaced it?

@jfpoilpret I replaced the chip for debugging. And yes, I was using a current limiting resistor for volt testing. I'm short of a one part to put together a bootloader installer set-up, so I'll try that when the part comes.

If you require a current limiting resistor for voltage testing then your DMM is damaged :/

It is probably a dead chip. Try getting a new ATmega chip for the Arduino (easily found online for ~$5) and see if that fixes it.


text:
PROGMEM char* mangled text
I wrote a program using PROGMEM for massive string arrays. One of the arrays worked, but when I added the second one, the serial output only puts out "th".
Pastebin Code: http://pastebin.com/9U7QZQKn

Perhaps the PROGMEM tag should be removed? The problem seems to be unrelated to PROGMEM.

Also, the essential parts of the code ought to be included here, e.g., in a reduced form (MRE). A similar comment.

Your declaration of char buffers is done like so:
char* move1 = "N/A";

This will only allocate 3 characters with an additional one for null termination i.e. not long enough to hold the name.
You need to do:
char buffer[16];

Where the length is long enough to hold your string.

According to C++ reference on string literals (and C is the same in this topic), "N/A" will allocate 4 characters, the last one being 0: http://en.cppreference.com/w/cpp/language/string_literal

Yes, forgot the termination. For the purposes of the problem though, there are still only 3 characters that you can use, and the code not working is still going to be cause be the same thing.

Ok, I see your point now, granted. Maybe you should copy the line with strcpy to better show where the problem resides, that would make youranswer clearer at first read.

Agree will edit at PC later;

I see one major flaw in your code, related to index usage on arrays.
Arrays in C and C++ are using a 0-based index, meaning that, for an array containing N elements:

the first element is accessible with index 0
the last element is accessible with index (N-1)

However, your code uses TrueRandom.random(1,numPokemon+1); which means you'll get an index between 1 and numPokemon (included), if you get the numPokemon value for your index, then you'll get garbage as it will try access some other part of memory.
Maybe that is not the only problem in your code, but this one is a major bug.


text:
Const Array still using dynamic RAM during compile, causing failure
Using win7 and arduino 1.6.7 IDE
I have a rather large CONST array of chars and upon compile using atmega2560, it fails and says:
Sketch uses 11,216 bytes (4%) of program storage space. Maximum is 253,952 bytes.
Global variables use 8,414 bytes (102%) of dynamic memory, leaving -222 bytes for local variables. Maximum is 8,192 bytes.
processing.app.debug.RunnerException: Not enough memory; see http://www.arduino.cc/en/Guide/Troubleshooting#size for tips on reducing your footprint.
    at cc.arduino.Compiler.size(Compiler.java:319)
    at cc.arduino.Compiler.build(Compiler.java:156)
    at processing.app.Sketch.build(Sketch.java:1108)
    at processing.app.Sketch.build(Sketch.java:1083)
    at processing.app.Editor$BuildHandler.run(Editor.java:2011)
    at java.lang.Thread.run(Thread.java:745)
Not enough memory; see http://www.arduino.cc/en/Guide/Troubleshooting#size for tips on reducing your footprint.
When I delete the CONST array the program compiles successfully, but when I put it back in, the compiler tells me that I'm using too much dynamic RAM.  If I am to understand correctly, consts should store in ROM not RAM.
Here's the even weirder part I put the program in Arduino IDE for Linux and it compiles, but it makes my robot act all crazy.
Any help would be much appreciated.

In a Princeton architecture const arrays are stored purely within the text (i.e., flash / read only / ROM) area.
In a Harvard architecture (which is what the Arduino is) the RAM and Flash both use completely different memory spaces, and instructions that work on RAM don't work on Flash, and vice versa.
Because of that it has to copy the const array from Flash into RAM so it can be accessed as normal variables.
To combat this you can use PROGMEM to force it to remain only in Flash, but then you have to use special functions to access the data - you can't use it like normal variables.
You can read more here: https://www.arduino.cc/en/Reference/PROGMEM

Const data may be stored in ROM but the standards don't require it; you usually have to specify in some (non-standard) way that it be placed there. I.e., const-ness is a necessary, but not a sufficient, condition for locating into ROM. Placing Data into ROM with Standard C by Dan Saks is a short, well-written paper (as is typical of Saks) describing what the standards do and, particularly, do not say about ROMming of constant data. It is well worth a few minutes to read it.


text:
What does "Arduino compatible" mean?
I wanted to buy an Arduino (ATmega) 2560 (8 Bit MCU) via Amazon. But there was no Arduino visible. There was only a

SainSmart 2560 and

SunFounder 2560

On both websides (SainSmart and SunFounder) there is the information that they are Arduino compatible. But all three boards (Atmel-orginal, SainSmart, SunFounder) do not look similar... There are differences. Is it possible to buy one of those boards without:

checking the datasheet differences
having problems with the Arduino Ethernet Shield !?

So, what is compatible ?

It means whatever the manufacturer says it means.

The most frequently annoying difference tends to be how the USB-serial function is implemented, for example with a CH340 instead of an FTDI or an ATmega16u2.  FWIW, an Ethernet shield on an Arduino is generally speaking a bad idea - people have made them work, but it's an absurdly expensive way to get very limited network functionality.

Arduino Compatible can mean many things, but most of the time it means that some company has made something they sell to a customer that supports development with the Arduino IDE.
The thing is that most Arduino Compatible units use the Atmel processors, but some use others too. Third party developers then make "board"-projects that you can add into the Arduino IDE.
Be aware though that you in some cases can run into issues if you dont do your homework, here are some of the issues you can run into:

Some "compatible" boards use different architectures, so even if you can do many things with the Arduino IDE, maybe some sensor libraries are not supported. (Might have to be hacked or updated)
Some "compatible" boards have different USB-circuits (if they have them at all)
Most of the boards you buy off aliexpress, banggood etc. do not come with instructions at all and some times they differ from the "original" design (might be better, might be "the same" or might be worse.).

I'm not trying to scare you off, but just my experiences. You can find a lot of fun things on those sites like clones of lilitiny with the AtTiny 85. One example is in my blog heer: http://mjelde.blogspot.no/2015/12/lilytiny-lilypad-attiny85-wearable-iot.html
The main issue with the clones I've had is that some times they differ in some ways that the first times will make you scratch your head. Like: ESP8266 is Arduino Compatible with the boards manager added ( https://github.com/esp8266/Arduino ), BUT: The input pins are not "correct" marked. So you should then add constants to "remap" them in your code.
Also the ESP8266 does only support 1V analog read, while many Arduinos support 5V. But you can "fix" this with an 16bit ADC (analog to digital converter). The ESP8266 only has 3.3V also, so you cant run sensors that "must" have 5V, without then giving them a different power circuit :)
The AtTiny 85 LilyTiny clone i bought in a pair of 2 from AliExpress works fine and works different than the rest of the Arduinos. Uploading to those for instance means you leave them disconnected and then you hit upload in the IDE. Then it says in the status window to connect it, which you then do.
Then it uploads. It has very few inputs, but it's very cute id say. Primarily it's made for wearable and of course it has a lot of short comings compared to a large arduino board. But you can of course use it to control RGB leds, etc.
Remember to always check specifications (3V vs 5V, how much analog read resolution can it handle, etc). There is the sensor vs board (some sensors work on both 3.3V and 5V, some work only on 5V, some only on 3.3V).
For going to 5V to 3.3V you usually use a voltage divider. Either you can buy pre made ones or you can make it based off three resistors and some math :-)

So you can use the same Arduino software and code to connect to and update the board?

Arduino is an open-source electronics platform. Lots of other manufacturers make Arduino-compatible boards, not just Arduino/Genuino. I have used both Arduino-branded and 3rd party manufactured boards without encountering any issues. I have not used boards by SainSmart or SunFounder, but they look compatible from a specifications perspective.
If you are worried about compatibility with the Ethernet Shield, you could always buy them as a pair (e.g. SainSmart Arduino Mega 2560 + Ethernet Shield for Arduino UNO Mega Duemilanove R3 AVR PIC ATMEL Robot) just to be on the safe side.

The other answer seem to focus on "compatible" meaning "works with the IDE" but that's not what they mean here. "Compatible" in this context means "clone of the original".
You can count on these boards being functionally identical. The microprocessor and pinout are the same, which is what a shield cares about. The peripheral circuitry might vary slightly, but that's not a big deal. They might (as mentioned) have a different USB-Serial chip but that won't cause any issues once you install the appropriate drivers on your PC.