text:
Use ESP8266 GPIOs after Flash Startup
I'm a bit confused about the ESP8266 launching and GPIO behaviour.

When I'm programming the ESP8266 I have to set GPIO2 high and GPIO0 low.
But when I want to use the ESP8266 in my project I have to set GPIO2 and GPIO0 to HIGH, but if they are both high I can't use them as inputs or outputs. So my question is how can I use atleast of the GPIO as an output and starting the ESP8266 without reprogramming it.

but if they are both high I can't use them as inputs or outputs - the state of those pins are important at powerup/reset, not all the time - you can definitely use them as outputs withut any worry, and "carefully" as inputs (i.e. usually as simple as having a pullup resistor connected to each of those pins) - note: GPIO15 also has to be LOW on boot/reset - but I guess you have an ESP01 if you failed to worry about that

they only need the special state for about 50ms at power-on, then it doesn't matter.

Do you know a way how to set it high at the beginning, and then use it as output, without a complicated circuit around it?

you can use pin 2 as output, only don't connect it direct or indirect to ground at startup. it is good for output that is normally HIGH

ESP8266 was developed for 'Serial over WiFi' as system-on-chip based on the Tensilica processor. The GPIO pins of Tensilica where used for different purposes of the system, like antena, flash memory connection, boot setup etc.
The more general use of the ep8266 as micro-controller with WiFi has evolved, but needs to accept the legacy of the original concept. Smart people even found a way how to share SPI with the flash memory of the system.
If you want to use the IO pins of the esp8266 (they are not called GPIO in datasheet), you must accept the required boot state and use only circuit,
sensor or actuator that doesn't disturb it and can handle it.
io0 LOW tels the esp8266 to boot into bootloader flashing mode. It is evaluated by ROM software in the boot process. Pull-up circuit is required to achieve normal boot. So if you want to attach something to this pin, it must accept this conditions. For button it is ideal.
If you want to use io 0 or io 2 as output, use logic that is normally HIGH and make sure it is not connected direct or indirect to ground at startup.


text:
stop running a certain function when sensor picks up something and return to where it stops?
i have a question on how to program a certain sequence for my robot.
lets say if i would to program to make it run from position a to b, i have a sensor attach to it that should it detect x, it would perform an action called y at the position where it detect x, where action y doesnt change its position.
i would like the robot to continue from where it left after performing action y to go towards b. however i do not know how to pause sequence from a to b and continue from where it left off after performing action y. i am controlling only the motor of the wheels so i can only set the speed of the wheels.
is there a pause function in general( not sleep) in c++ and to continue running its lines of code from where it paused?

i know what you mean, but i can only control my wheels(moving from position from a to b) by setting its speed for a certain amount of time. so lets say for simplicity sake i program my wheels to move in a straight line for 10 seconds, and that it detect x and perform action y at 3 seconds of my wheels moving, how can i make it move the other 7 seconds instead of resetting it back to 10 seconds?

im was the one who posted the question, i do not have enough reputation to write a comment. what you mention would work easily if the robot movement were simple, but my motion is to navigate through a maze actually, where i wrote the whole movement under one function. from what im getting from you, splitting up its movement and checking every second before resetting the timing seems to be pretty difficult and irritating to code it out. wondering if there is a simpler way to do this.

You can use different ways:

Pause/sleep, don't use this, since it will block other activities
Poll, poll for time, and check every so-many ms what to do.
Timers/Interrupts, every microcontroller has one or more timers which you can use to generate an interrupt to perform an action. The interrupt can change the mode, and in your main program you can check for the mode what to do (go to another position, pick up something etc.

The last one takes a bit more programming, but is the preferred way to easily make changes later on.
There is no 'pause' function in C, but you can of course pause until an interrupt is triggered. In the datasheet of your microcontroller you can read how this can be used.
So in general your loops look like:
loop()
{
   switch (mode)
   {
   case modeMoveAToB:
       ... move from A to B (just a small portion, like 1 cm)
       break;

   case modeActionY:
       ... Perform action Y
       mode = modeMoveAToB;
       break;
   }

   if (SensorTriggered)
   {
      mode = modeActionY;
      SensorTriggered = false;
   }
}

In the trigger interrupt you set SensorTriggered to true.
Make sure that the modeActionY does not take long, so let it move e.g. 1 cm, so the sensor (SensorTriggered) is checked every 1 cm. If you need other actions, just add them in the case statement. And make the inside of each case statement a function, so you can easily reuse it later and/or keep the functionality clearly divided.

stop running a certain function when sensor picks up something and return to where it stops?

simple:
1) write that certain function as an ISR - that's not used by the mcu;
2) when the sensor picks up something, set the flag of the respective ISR - execution will jump to the corresponding ISR.
3) sit back and enjoy.

source: Stack Exchange

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

sort: votes


text:
Arduino stop the loop
i have a problem with my code, i basically move a motor with the help of 3 relays, when a sensor does not detect the presence of an object part of a call, everything works perfectly, if it was after having called the function CHIAMATA() the arduino loop() stop unexplains, i certainly made a mistake, but i do not understand which.
thanks for your help
this is the code....
#include <swRTC.h>
#include <SoftwareSerial.h>
#include <String.h>

swRTC rtc; //create a new istance of the lib
SoftwareSerial mySerial(3, 2);

const int buttonPin = 19;
const int sensorPin = 9;
const int allarmPin =  13;

int buttonState = 0;
int sensorState = 0;
int relay1 = 8;
int relay2 = 7;
int relay3 = 6;
int var = 0;

// initialize the stepper library on pins 8 through 11:

void setup() {
    rtc.stopRTC(); //stop the RTC
    rtc.setTime(12,0,0); //set the time here
    rtc.setDate(4,6,2012); //set the date here
    rtc.startRTC(); //start the RTC
  Serial.begin(19200); //choose the serial speed here
  mySerial.begin(19200);
  pinMode(allarmPin, OUTPUT);
}

void loop() {

while(mySerial.available()!=0);{}delay(10);

    Serial.print(rtc.getHours(), DEC);
    Serial.print(":");
    Serial.print(rtc.getMinutes(), DEC);
    Serial.print(":");
   Serial.print(rtc.getSeconds(), DEC);
    Serial.println(" ");

//stato riserva croccantini
sensorState = digitalRead(sensorPin);

if (sensorState == HIGH) {
    // turn LED on:
    digitalWrite(allarmPin, HIGH);
    Serial.println("Croccantini esauriti");
    Serial.println("Spia allarme ACCESA");
    Serial.println("Tramoggia DISABILITATA");
    Serial.println("Imposto la chiamata");
    while(sensorState == HIGH) {CHIAMATA(); break;}
  } else {
    // turn LED off:
    digitalWrite(allarmPin, LOW);
    Serial.println("Croccantini OK");
  }
if (sensorState == LOW && rtc.getHours()== 12 && rtc.getMinutes()== 00 && rtc.getSeconds()== 5) {startmotor();}
  //start manuale carico/scarico
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);
  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
    if (buttonState == 1) {
      Serial.print("Pulsante alimentazione manuale ATTIVO");
    // turn on:
  // singlestartmotor();
  }

      }

void startmotor(){
//numero di cicli di carico da eseguire (5)
 while(var < 5){
 pinMode(relay1, OUTPUT);
  pinMode(relay2, OUTPUT);
    pinMode(relay3, OUTPUT);

 digitalWrite(relay3, LOW); //ABILITA TUTTO
 //AVANTI
 digitalWrite(relay1, LOW);
 digitalWrite(relay2, LOW);
 Serial.print("AVANTI");
 delay(1000); // wait 2 seconds

 digitalWrite(relay3, HIGH);//STOP TUTTO
 digitalWrite(relay1, HIGH);
 digitalWrite(relay2, HIGH);
 delay(1000); //ATTESA PER INVERSIONE MARCIA

 //INDIETRO
 digitalWrite(relay3, LOW);//ABILITA TUTTO
 digitalWrite(relay1, HIGH);
 digitalWrite(relay2, HIGH);
 Serial.print("INDIETRO");
 delay(1000); // wait 2 seconds

  digitalWrite(relay3, HIGH);//STOP TUTTO
  delay(5000); // wait 2 seconds

  var++;
}}

void CHIAMATA() {
 mySerial.println("ATD329xxxxx135;");//dial the number, xxxx ix the phone number.
 delay(100);
 Serial.print("Chiamata in corso..."); return loop();}

... return loop(); doesn't do what you think it does...

I've tried them all =P

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


text:
Error while creating file on sd card
I want to create a file and read it form sd card by arduino. I have used sd card module. I have used this following code. In serial monitor it says "SD card is ready to use." But it can't read or write files. I have formatted the card in FAT32 format.
My code is :
#include <SD.h>
#include <SPI.h>

int CS_PIN = 10;

File file;

void setup()
{

  Serial.begin(9600);

  initializeSD();
  createFile("test.txt");
  writeToFile("This is sample text!");
  closeFile();

  openFile("test.txt");
  Serial.println(readLine());
  Serial.println(readLine());
  closeFile();
}
void loop()
{
}

void initializeSD()
{
  Serial.println("Initializing SD card...");
  pinMode(CS_PIN, OUTPUT);

  if (SD.begin())
  {
    Serial.println("SD card is ready to use.");
  } else
  {
    Serial.println("SD card initialization failed");
    return;
  }
}

int createFile(char filename[])
{
  file = SD.open(filename, FILE_WRITE);

  if (file)
  {
    Serial.println("File created successfully.");
    return 1;
  } else
  {
    Serial.println("Error while creating file.");
    return 0;
  }
}

int writeToFile(char text[])
{
  if (file)
  {
    file.println(text);
    Serial.println("Writing to file: ");
    Serial.println(text);
    return 1;
  } else
  {
    Serial.println("Couldn't write to file");
    return 0;
  }
}

void closeFile()
{
  if (file)
  {
    file.close();
    Serial.println("File closed");
  }
}

int openFile(char filename[])
{
  file = SD.open(filename);
  if (file)
  {
    Serial.println("File opened with success!");
    return 1;
  } else
  {
    Serial.println("Error opening file...");
    return 0;
  }
}

String readLine()
{
  String received = "";
  char ch;
  while (file.available())
  {
    ch = file.read();
    if (ch == '\n')
    {
      return String(received);
    }
    else
    {
      received += ch;
    }
  }
  return "";
}

You might want to use SD.begin(CS_PIN) instead of SD.begin().

tried it. but same problem :/


text:
What is the best way to get more RAM for a sound buffer?
The problem:
How to extend the memory for a sound buffer (intensively used) if:

SD card library supports only one file open at a time (and I have one open already)
EEPROM chips are able to stand about 100,000 write cycles only (see the datasheets!)
I can't find anything else to buy! (a standard and durable RAM chip that loses its content when switched off would be the best).

About the 2nd point. Let's assume that the chip is 64KB and I want to use half of it for a circular sound buffer (it's small, I know). Let's also assume that a standard MP3 song is 160kbps and it's 3.5 min long. Given that, the EEPROM chip (with 100k write cycles limit) in this condirions will reach its limit after 3.2GB of played sound, which is about 762 songs, 44 hours. That can be reached in a single week! Replacing a chip every week is not an option. I'm not a fan of planned obsolescence...
Do you know any chip that will be right for the job? (and can be bought on eBay and it's affordable?)
Background:
I have built a WWW-controlled MP3 and online radio player (using ESP8266 and VS1003) and it's working really great, we're using it whole days, but ESP is not fast enough to handle WWW requests and play MP3 at the same time (especially from SD card), so the sound is paused for about 0.5 - 1 sec every time a www page is served (a really small page! Just basic HTML with a title and a list of file links!). SD card content cannot be cached for generating the pages on the fly (not enough heap memory) and two files cannot be opened at the same time by the SD library (one is open for the currently playing file - if not playing an online stream - and I'm currently closing it during reading and sending of requested html page). So I've got two memory problems: 1. serving the www pages and 2. buffering the online stream (usually not needed, most streams can play on my 4KB buffer without a glitch whole day but some of them are jamming very often - depends on the server). I'm thinking about both caching the pages (so I don't have to read them from SD and my music won't be interrupted) and creating a circular buffer (for live streams) in external memory chip. It does not need to keep the data after cutting the power. I've got about 24KB of heap left in my sketch (max) and it can fall even to about 6KB when a single folder's content is loaded to memory. It's not far away from heap overflow... I need to load at least the current folder (with long filenames).

This is a software problem, and properly solved there.  Compared to an ordinary Arduino, an ESP8266 has quite a bit of buffer memory.  The problem is that by not really implementing multiple tasks, you put yourself in the position of needing absurd amounts of buffer.  Your best solution on this platform will be to rework the SD card access library to handle multiple files, or perhaps permit multiple instances to request sectors from the same card.  Then your buffer need only be a few sector's size, which should not be a problem.

A simple SPI SRAM chip. Available up to 128KB, such as the 23LC1024: http://www.microchip.com/wwwproducts/en/23LC1024

This chip is great! Thanks! Although it's very expensive as you compare it. You can get ESP-12 for $2.5 and this little chip costs above $8! For that price you can buy 3 pcs of ESP-12 (or 4pcs ESP-01 or 5pcs ATmega328P-PU!) and make memory out of them (by a sketch), even with WiFi interface... :] That's even more true for these Adafruit non-volatile modules (from JRobert's answer), which have 32KB only!

This is silly way to solve a software problem.

@ChrisStratton Yeah, but it's the typical PC software developer request/solution. Software is running slow => throw more hardware at it.

This is not a software problem. If you download a radio stream from Internet and you don't have a big buffer, then you will eventually always get lags in sound. You can't speed up the whole Internet. I agree that SD library probably could be made better (to handle multiple files) but even then it wouldn't help because I'm getting like 2 sec delays when opening SOME of the files on my SD card! You can't cheat time and memory size by software. It's just physically not possible. Check out by yourself how WinAMP (for example) delays the online radio streams. It's about half a minute!

You should switch to SdFat instead of SD.

An FRAM chip?

Non-volatile (though you don't need that)
SPI or I^2C available on a breakout board from Adafruit
Or roll you own from a bare chip, if you're handy with Surface Mount Devices.


text:
How to compile an official VS1003 / VS1053 example for Arduino / ESP8266?
Have anyone ever successfully run any of the official playback and recording examples for VS1003 or VS1053 on Arduino / ESP8266? I mean, I was able to play sound with VS1003, but I just can't make the official example compile on Arduino IDE... It looks like it should be no problem (just provide a few methods and copy the main method code from the PDF file to the setup() in sketch) but I'm just getting a bunch of stupid compiler or linker errors, like "undefined reference to 'VSTestInitHardware()' " while the player.h header file (containing it) is included. I'm not a C / C++ expert so it's either something stupid I do or it's just not possible on Arduino. Can anyone provide a compilable example? I'm trying it with ESP8266 currently (and it is my desired target CPU), but an Arduino Uno version could help too (it throws different errors but doesn't compile neither). Thank you.

The Arduino IDE should only be used to build Arduino code.

@IgnacioVazquez-Abrams They say (in their examples) that their code is plain C and it can be compiled for ANY microcontroller - you just have to supply the device-specific methods. That is exactly what I'm trying to (and can't) do.

You can't compile plain C in the Arduino IDE, only Arduino code.

@IgnacioVazquez-Abrams I would qualify that as "you can't compile it unmodified". And if all he's using is library routines, wrapping them in extern "C" {} should do the trick.

@JayEye: Can you explain in detail what trick do you mean, please? I was trying making the header file's methods extern but it didn't help. I can live with modifying a little the examples - just don't want to rewrite them in different way, especially I want to test more than one chip version, so I would have to change them all separately.

adding this as answer so I can format properly.

Ok, after long battle with C++ compiler I have a working example (at least for VS1003 and ESP8266) with a checklist how to recreate it (with minimal changes to the example files). I'm sure someone else will have this problem so I'm attaching it:
The things that you need to do in player1003.c:

rename to player1003.h (change file extension only)
remove all 5 includes from the top (stdio, string, stdlib, ctype, "player.h")
turn off REPORT_ON_SCREEN (change #if 1 to #if 0) if you don't want to have a lot of serial output
mass replace "FILE *" to "File " - mind the space (change type of file variables in all methods, mark "Case sensitive" to avoid errors in player1053!)
mass replace fopen( to fopen2(
mass replace printf( to Serial.printf(
mass replace fflush(stdout); to //fflush(stdout); (or Serial.flush();)
remove method: VSTestInitHardware(void)
remove SM_SDISHARE flag from WriteSci(SCI_MODE, SM_SDINEW|SM_SDISHARE|SM_TESTS|SM_RESET); line  (in VSTestInitSoftware(void) method)
in VSTestHandleFile() at the bottom add fp.close(); after VS1003PlayFile(fp); and VS1003RecordFile(fp); lines (especially after the record!). We don't want unclosed files on SD card.

The main sketch (.ino):
#include <SPI.h>
#include <SD.h>
#include "player.h"

using namespace std;

// I use these values below for ESP-12 (ESP8266):
#define MP3_xCS 2
#define MP3_xDCS 4
#define MP3_DREQ 5
#define MP3_xRESET 16
#define SD_CS 15
#define SPI_MOSI 11 //SPI
#define SPI_MISO 12 //SPI
#define SPI_CLK  13 //SPI

#define  WAIT_DREQ()  while(!digitalRead(MP3_DREQ))

File song;

int VSTestInitHardware()
{
  pinMode(MP3_DREQ, INPUT);
  pinMode(MP3_xCS, OUTPUT);
  pinMode(MP3_xDCS, OUTPUT);
  pinMode(MP3_xRESET, OUTPUT);
  pinMode(SD_CS, OUTPUT);

  digitalWrite(MP3_xCS, HIGH);
  digitalWrite(MP3_xDCS, HIGH);

  digitalWrite(MP3_xRESET, LOW); // chip off!
  delay(100);
  digitalWrite(MP3_xRESET, HIGH); // chip on!

  Serial.begin(115200);

  if (!SD.begin(SD_CS))
  {
    Serial.println("Can't initialize SD!");
    return -1;
  }
  Serial.println("SD OK!");

  SPI.begin();
  SPI.setClockDivider(SPI_CLOCK_DIV32);  // Bus SPI at 1MHz (for Arduino: 16MHz / 16 = 1MHz)
  SPI.transfer(0xFF);  // Write something to the bus
  delay(10);
  return 0;
}

void setup()
{
  if (VSTestInitHardware() || VSTestInitSoftware())
  {
    Serial.printf("Failed initializing VS10xx, exiting\n");
    exit(EXIT_FAILURE);
  }
  /* ... */
  /* Playback example. You can call these functions many times in a row
  because they leave VS1003 in a stable state. */
  VSTestHandleFile("TEST.mp3", 0);  // remember to use 8.3 file names format on SD!
  /* Recording example */
  VSTestHandleFile("RECORDED.WAV", 1);  // original example for VS1003 has a bug here (OGG extension)

  Serial.println("Playing recorded file...");
  VSTestHandleFile("RECORDED.WAV", 0);

  Serial.println("THE END");
}

void loop()
{
}

void WriteSci(unsigned char reg, unsigned char hsb, unsigned char lsb)
{
  // for debugging:
  Serial.printf("Setting %s to: %d (%X, %X)\n", RegName(reg), (hsb<<8) + lsb, hsb, lsb);

  WAIT_DREQ();
  digitalWrite(MP3_xCS, LOW);

  SPI.transfer(0x02);
  SPI.transfer(reg);
  SPI.transfer(hsb);
  SPI.transfer(lsb);
  WAIT_DREQ();
  digitalWrite(MP3_xCS, HIGH);
}

void WriteSci(u_int8 addr, u_int16 data)
{
  WriteSci(addr, data >> 8, data & 255);
}

uint16_t ReadSci (unsigned char reg)
{
  WAIT_DREQ();
  digitalWrite(MP3_xCS, LOW);

  SPI.transfer(0x03);
  SPI.transfer(reg);
  delayMicroseconds(10);

  char response1 = SPI.transfer(0xFF);
  WAIT_DREQ();
  char response2 = SPI.transfer(0xFF);
  WAIT_DREQ();

  digitalWrite(MP3_xCS, HIGH);

  unsigned int resultvalue = response1 << 8;
  resultvalue |= response2;

  // for debugging:
  if (reg != SCI_HDAT0 && reg != SCI_HDAT1)  // these registers are filtered out because they are intensively used during recording
    Serial.printf("%s is: %d (%X, %X)\n", RegName(reg), resultvalue, resultvalue >> 8, resultvalue & 255);

  return resultvalue;
}

int WriteSdi(const u_int8 *data, u_int8 bytes)
{
  WAIT_DREQ();
  digitalWrite(MP3_xDCS, LOW);

  for(int y = 0 ; y < bytes ; y++)
    SPI.transfer(data[y]);

  digitalWrite(MP3_xDCS, HIGH);
}

const char* RegName(uint8_t reg)
{
  switch (reg)
  {
    case 0x00: return "SCI_MODE";
    case 0x01: return "SCI_STATUS";
    case 0x02: return "SCI_BASS";
    case 0x03: return "SCI_CLOCKF";
    case 0x04: return "SCI_DECODE_TIME";
    case 0x05: return "SCI_AUDATA";
    case 0x06: return "SCI_WRAM";
    case 0x07: return "SCI_WRAMADDR";
    case 0x08: return "SCI_HDAT0";
    case 0x09: return "SCI_HDAT1";
    case 0x0A: return "SCI_AIADDR";
    case 0x0B: return "SCI_MIXERVOL";
    case 0x0C: return "SCI_AICTRL0";
    case 0x0D: return "SCI_AICTRL1";
    case 0x0E: return "SCI_AICTRL2";
    case 0x0F: return "SCI_AICTRL3";
  }
}

void SaveUIState(void)
{
}

void RestoreUIState(void)
{
}

int GetUICommand(void)
{
  while (Serial.available() > 0)
  {
    char c = Serial.read();
    if (c != 10 && c != 13)
      return c;
  }
  return -1;
}

void exit(int code)
{
  if (code == EXIT_SUCCESS)
    Serial.println("Exited with no error.");
  else
    Serial.printf("Terminated with error: %d\n", code);
  while (true) { yield(); }  // yield() is needed for ESP8266 only
}

File fopen2(const char* fileName, const char* mode)
{
  if (mode[0] == 'w')  // fast workaround!
  {
    Serial.printf("Opening for writing: %s\n", fileName);
    song = SD.open(fileName, O_WRONLY | O_TRUNC | O_CREAT);
  }
  else
  {
    Serial.printf("Opening for reading: %s\n", fileName);
    song = SD.open(fileName, O_RDONLY);
  }

  if (!(song))
  {
     Serial.printf("File not found: %s\n", fileName);
     return song;
  }
  Serial.printf("File opened: %s\n", fileName);
  return song;
}

size_t fread ( void * ptr, size_t size, size_t count, File stream )
{
  yield();  // this is needed for ESP8266 only (otherwise reboots)
  return stream.read(ptr, size * count);
}

int fseek ( File stream, long int offset, int origin )
{
  stream.seek(offset);
}

size_t fwrite ( const void * ptr, size_t size, size_t count, File stream )
{
  return stream.write((uint8_t*)ptr, size * count);
}

int fflush ( File stream )
{
  stream.flush();
  return 0;
}

#include "player1003.h"

(i had to manually clean this file out of my additional code, but I hope it will compile just fine).
I have a request:
If you run this example, please write me in comment whether the recording worked. I can't make my VS1003 module record sound. I have a suspicion that mic in my module is broken. That's why I was trying the official example (with the minimum changes as possible). It records only noise in my case, but plays mp3 perfectly. If you have a working example of recording, please share too.
And one more to the people with more rep (moderators): Please add a VS1003 (and VS1053 and VS1063) keywords and assign it to my questions about VS1003, because I'm unable to do it and it should be done. The chip deserves a keyword. (It's really good and not expensive.)

This is best given with an example.
foo.h contains:
#ifdef __cplusplus
extern "C" {
#endif
extern int foo(const char* s);
#ifdef __cplusplus
}
#endif

foo.c contains:
#include "foo.h"
#include <stdio.h>

int foo(const char* s) {
  printf("foo: %s\n", s);
  return 42;
}

So first, let's create a "library" from foo.c. Since we are compiling with a C, not a C++ compiler, the stuff in #ifdef __cplusplus is ignored.
$ gcc -c foo.c

This creates a file called foo.o, which we can then use to link with.
as24823.cpp contains:
#include "foo.h"
#include <iostream>

int main(int argc, char* argv[]) {
  int f = foo("called");
  std::cout << f << std::endl;
}

Now I can compile the C++ program (as24823.cpp) and use a C library (foo.c):
$ g++ -c ase24823.cpp
$ g++ ase24823.o foo.o
$ ./a.out
foo: called
42

Why is this necessary?, I hear you ask. Well, for reasons that are way beyond the scope of this posting, C++ mangles entry point names. Observe:
$ nm as24823.o
$ nm ase24823.o
...
                 U foo
0000000000000000 T main
...

(I've removed most of the output). What this is telling me is that the .o file has an entry point called "main", and an undefined external reference (something that will be provided by a library) called "foo". Now, if I remove the ifdefs from the foo.h file and recompile, this is what I get:
$ cat foo.h
extern int foo(const char* s);
$ g++ -c ase24823.cpp
$ nm ase24823.o
0000000000000000 T main
                 U _Z3fooPKc
....

What just happened? Because C++ no longer knows that it's supposed to call a C function, it has mangled the external so as to encode the types of its arguments (this is so that overloading can happen).
If you find this confusing, don't worry -- just edit the .h files that come with your C libraries and you'll be fine.


text:
How to change the variable value on arduino program using java?
I am new to arduino and I want to interface it using java . I want to know is there a way to change the variable or set the variable using the input from java :D Thanks For reading Hope you can answer my question .. Sorry for my english not my first language :D

Devise and implement your own custom protocol through the (USB-tunneled) serial connection: the Java side would tell the Arduino “set this variable to this value” and the Arduino would do it.

Although you can't straight-up change variables on the Arduino, you can create your own protocol over a serial connection using processing (https://processing.org) on your computer, and a sketch on Arduino.
Use the function
Serial.begin(9600);

on the arduino to initialise a serial connection to your computer, and then in processing use the lines:
Serial myPort;    // Initialise a serial object (do this at the start of the program)

// Inside the setup() function:
String portName = Serial.list()[0];    // Get the first portname on the list (this may need to be changed to get the right one)
myPort = new Serial(this, portName, 9600);

to connect from the computer.
Once you have done this, you can use the functions
myPort.write();

in processing, and
val = Serial.read();

To recieve data on the arduino.
Source (see here for more info): https://learn.sparkfun.com/tutorials/connecting-arduino-to-processing/all


text:
How to send multiple data from PC to arduino
I have a project in arduino that i interface with java. The arduino is connected to the computer via usb cable , I use the serial communication.
 I have two variables:
//Code in arduino
int ADelay = 1000;
int BDelay = 1000;

I want to change the value of each variable based on the input of the user using the java interface.
Is there a code that let the arduino identify that this data:
2000

Is intended to or for:
int ADelay

and this
300

is for
int BDelay

My only idea on how to achieve this is to add A or B before the number before i send to arduino
A2000
B300

And use Delimeter in arduino to split the data and use if else condition to decide where the data belong , Is there any other way ? Thanks

And how has that failed you?

I want to know if my idea is right or is there other simple way to do it :D

how often do you need to poll the data?

It depends , but maybe twice is the maximum .

The approach noted in the question – having an identifying character at the front of each number – is a workable approach.  Other approaches include:
•  always sending numbers in pairs, eg 2000,300 would denote A2000 B300.
•  encoding the A or B as part of the number; eg, the range 0-4999 could denote A delays of 0 to 4999, while the range 5000-9999 could denote B delays of 0 to 4999.
•  sending A delays via decimal digits, and B delays via letter-substitutes for digits; eg DAA could encode a B delay of 300.
One of the easiest-to-parse approaches is to have an identifying character at the end of each number, rather than at the front.  This allows your code to pick up digits until a letter appears, and then dispatch based on the letter.  Here's some example code:
// Sketch that accepts numbers and action code via serial input.
// Silently ignores any numbers not followed by a valid action letter.
// Does not test for number overflow.      - jiw 3 Nov 2016

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

unsigned int val=0;
void loop() {
  char inc;
  while (Serial.available()) { // Get characters
    inc = Serial.read();
    if (inc >= '0' && inc <= '9') {
      val = 10*val + (inc-'0');
    } else {
      switch (toupper(inc)) {
      case 'A':
        Serial.print("Case A got ");
        Serial.println(val);
        break;
      case 'B':
        Serial.print("Case B got ");
        Serial.println(val);
        break;
      default :
        ; // handle blanks, returns, etc
      }
      val = 0;  // Set val to zero after any non-digit
    }
  }
}

Edit 2: This edit incorporates some code suggestions from comments into the answer.

If you need to know whether a number for val1 has been specified -- that is, if you handle items like 500B as well as 300,500B -- you can set/test/clear a flag:
...
case ',':
  val1=val; v1flag=1;
  break;
...
case 'B':
  if (!v1flag) val1=val1default;
  Serial.print("B stuff with val and val1");
  v1flag=0;
  break;
...

To retain when the power is off, you can write a recordData() function, that when called will write selected data to EEPROM if the value has changed.  In setup(), load data from where you stored it. For data validation, you can store in the cell after a value v its complement, ~v.  If when you reload data it fails the validation test, use a default value instead, and write it to EEPROM for future use.

The code snippet shown next, from kaisarGreat's 8 May comment, has several problems to be corrected:
case a :
  WATEREQFORN1 = val;
  EEPROM.put(0, WATEREQFORN1);
case b :
  WATEREQFORN2 = val;
  EEPROM.put(1, WATEREQFORN2);
case d :
  DELAY = val;
  EEPROM.put(3, DELAY);

Logic or syntax problem: Missing break statements at  ends of cases.  This error will allow execution to flow from one case into the next.  While there are situations where that's useful, this is not one.
Logic or syntax problem: Unless a, b, ... are declared constants they won't work as case designators.  Perhaps use 'A', 'B', ... instead.
Style problem:  Variable names in all upper case.  Conventionally, C and C++ programmers use all-upper-case names to designate defined constants or macros.  Contravening that convention can lead to confusion if other people use or maintain the code.  Instead of WATEREQFORN1 consider waterEq1.
Allocation problem:  Presumably the WATEREQ... variables are multiple bytes in length.  EEPROM.get() and put() read and write data types with multiple bytes using several consecutive bytes of EEPROM.  For example, if WATEREQFORN1 is a real and takes 4 bytes, it will occupy cells 0, 1, 2, 3 in EEPROM.
The following code snippet fixes some of those problems.
enum { WaterAddr1=0, WaterAddr2=WaterAddr1+sizeof waterEq1, DelayAddr=WaterAddr2+sizeof waterEq2 };
...
case 'A':
  waterEq1 = val;
  EEPROM.put(WaterAddr1, waterEq1);
  break;
case 'B':
  waterEq2 = val;
  EEPROM.put(WaterAddr2, waterEq2);
  break;
case 'D':
  Delay = val;
  EEPROM.put(DelayAddr, Delay);
  break;
  ...

Can you give me a code snippet C programing  language on how to pick up digits until a letter appears and make an if else condition based on the letter :D Thanks a lot

@kaisarGreat, see edit for working example

Thank You Sir :D for your help and time :) @jwpat7 it really help me :D

Sir @jwpat7 is it posible to combine the snippet code above you give and one approach you give the sending numbers in pair ? Example I will send 200A300 or 200,300A then put them in separate varables .. 200B300 or 200,300B ..

Yes, you can do that, but handling numbers in pairs complicates the parsing  – it's simpler and easier to handle independent values.  ¶ That said, one approach is to add  case ',': val1=val; break; into the switch, and then when you get the A or B (for a form like 200,300A or 200,300B) do an action using both val1 and val.  That is, the action for the comma case stores a value for future use; while letter cases can use two vals.

I did what you told sir @jwapat7 , I add 'case ',': val1=val; break' then in the both 'case 'a'' and 'b' I add 'Serial.println(val1);' and It works like a charm :) Thanks for your quick reply .

Also, if you need to know whether a number for val1 has been specified -- that is, if you handle items like 500B as well as 300,500B -- you can set/test/clear a flag:  case ',': val1=val; v1flag=1; break; .... case 'B':  if (!v1flag) val1=val1default; Serial.print("B stuff with val and val1");  v1flag=0; break;

@kaisarGreat, please feel free to upvote answer

Sir @jwpat7 I want to upvote your answer but my reputation  is less 15 :D Thanks for the additional Information.

Sir is it possible to save the value send example 200,400A .. then spilt 200 to val1 and 400 to val2 and save them into different variables but remains when the power of arduino is put out .

@kaisarGreat, you could write a recordData() function, that when called will write indicated data to EEPROM if the value has changed.  In setup(), load data from where you stored it.  For data validation, you can store in cell after a value v its complement, ~v; if you load data and it fails the validation test, then write a default value to EEPROM.

I used the above code you give and add some inside the case here is for case a : WATEREQFORN1 = val;            EEPROM.put(0, WATEREQFORN1); case b : WATEREQFORN2 = val;            EEPROM.put(1, WATEREQFORN2); case d : DELAY = val;            EEPROM.put(3, DELAY);   but when i change the value of A , then change the value of B the value on A will also change in random numbers .. how could i achieve writing into eeprom without changing some that i already save in there ..

If you are just looking to send something as simple as 2 integers, your approach should be fine, you just need to set your own protocol to encode the data from java and decode it on the arduino side.
Another easy way would be to set a starting byte, could be anything like 0x6A etc, (with optional checksum if it's through bluetooth or other noisy communication method):
[8 bit starting byte][32 bit integer data A][32 bit integer data B]

On the arduino side you want to keep polling for the starting byte, once you receive the special byte then the next 32 bits would be your data A and the following 32 bits would be your data B.
However if you want something more robust or object oriented you could look into this library:
https://github.com/bblanchon/ArduinoJson
It allows you to decode and encode JSON objects which is very flexible and widely accepted, so you just need to encode the data into a JSON object on the java side and decode it using that library.


text:
Adjusting variables in code without reprogramming?
I'm a teacher, working on eliminating some difficulties of Arduino in the name of getting to the fun stuff. Namely, I am building a small Arduino powered device that will collect simple data from sensors like a DHT11, or an accelerometer. That being said, I want to pass simple settings (sample rate, sensor type, etc.) into the device with out reprogramming the board out right. I'm worried I'm over thinking the challenge. Initially, I wanted to pass the settings over serial in Python script, then save the settings to EEPROM and read them when rebooting...but sending strings over serial from Python is proving to be challenging, let alone the EEPROM.
Long term, this will run on an ESP8266 and I'd try to make a simple interface for entering the SSID and password for the Wifi network we want to connect to. Simply plug in the board over USB, run some simple little Python app that asks for SSID, password, maybe sample rate, sensor type and hit configure.
Is there an easier way to build a user interface for adjusting variables in code already running on an Arduino?

You could just make a library that ran everything with only the 3 parameters you describe appearing in the top level sketch.

If the number of choices is limited (device types, a few selections of sample rate), you might consider a bank or two of DIP switches.

To avoid the serial input and hit the ground running; you could add a simple hardware input like a potentiometer, rotary encoder, or push button that cycled through settings. I would use the Arduino Serial Library to make the configuration viewable on a computer in the IDE serial monitor or terminal. As long as you pull up/down the buttons and separate the inputs properly, a push button and rotary encoder would be easy to keep modular so that it could be safely plugged in and unplugged without an issue. You could also make an interactive menu over the serial interface which asks you for each parameter. The simplest way would be to detect a button press in your application which would take you to 'config mode', which prompts the user for input via the serial monitor. Once everything is entered, save to EEPROM and restart.

Arduino Serial Library
Arduino Serial Streams

If you are determined to take the Serial scripted approach for programming, and are having difficulty with Python, you could repost or update your question to include your code and explain where you are having trouble, or use a different language. I prefer C#, because I use it for so many different things (From websites to XBOX games), and it lends itself well to rapid development. Java would be another good choice particularly if you would like to integrate with Android ;). All of these are easy to integrate with a GUI.
It sounds like you are having difficulty dealing with strings - and don't feel bad about this, strings can be a complex thing because of how they are construed and work. Check out some examples, and re-implement them to suit your application. Try breaking your strings up into characters (which are a byte in size, easy to fit in EEPROM!) and send them byte by byte - this might be simpler.

Arduino and C# Communication
A better C# Example.
Arduino and Java Communication
Arduino and Python Communication

Saving to EEPROM is trivial and well covered in the Arduino documentation. One thing to keep in mind is that the EEPROM is accessed and used in bytes! What does this mean? - Well, if a larger variable is to be stored, like an int (16 bit on Arduino Uno) it must first be split in half. To do this you would use bit shifting. To give you a quick idea on how this is done, see functions below - note this assumes you only ever save integers to EEPROM (this is in the way I choose to address the memory):
// Include EEPROM library
#include <EEPROM.h>

// location is an int from 0-511 using Arduino Uno with 1KB of EEPROM
void SaveValue(unsigned int location, unsigned int value)
{
    // Find addresses to store each half of the integer
    unsigned int saveLocationLower = location * 2;
    unsigned int saveLocationUpper = saveLocationLower + 1;

    // Split the integer into two parts
    byte lowerValue = value;
    byte upperValue = (value >> 8);

    // Save both parts
    EEPROM.write(saveLocationLower, lowerValue);
    EEPROM.write(saveLocationUpper, upperValue);
}

int LoadValue(unsigned int location)
{
    // Find both locations to read using same method as above
    unsigned int saveLocationLower = location * 2;
    unsigned int saveLocationUpper = saveLocationLower + 1;

    // Read both locations
    byte lowerValue = EEPROM.read(saveLocationLower);
    byte upperValue = EEPROM.read(saveLocationUpper);

    // Assemble both halves and return value
    return lowerValue + (upperValue << 8);
}

Arduino EEPROM Read
Arduino EEPROM Write

If you are feeling really outgoing and adventurous, and have good luck with the C# route - you could check out Microsoft's latest Arduino offerings - they are pretty cool. It makes it easy to integrate Arduino devices with Windows 10 and Phone apps.

WIndows 10 IOT, Getting Started


text:
Basic makefile for avr-gcc
I would like to make a makefile for compiling c programs for the arduino. I am somewhat familiar with make but have never used it with avr-gcc. What is the simplest way I could put the commands below in a makefile?
$ avr-gcc -Os -DF_CPU=16000000UL -mmcu=atmega328p -c -o led.o led.c
$ avr-gcc -mmcu=atmega328p led.o -o led
$ avr-objcopy -O ihex -R .eeprom led led.hex
$ avrdude -F -V -c arduino -p ATMEGA328P -P /dev/ttyACM0 -b 115200 -U flash:w:led.hex

Since this is an Arduino forum, it would be more politically correct to compile with -I/usr/share/arduino/hardware/arduino/cores/arduino -I/usr/share/arduino/hardware/arduino/variants/standard and link with libcore.a. :-)

It's no different to working with Make and any other form of GCC.  Just set your CC variable and CFLAGS variable accordingly and work as per normal.
For instance, I just knocked this one up:
CC=avr-gcc
OBJCOPY=avr-objcopy

CFLAGS=-Os -DF_CPU=16000000UL -mmcu=atmega328p
PORT=/dev/ttyACM0

led.hex: led.elf
    ${OBJCOPY} -O ihex -R .eeprom led.elf led.hex

led.elf: led.o
    ${CC} -o led.elf led.o

install: led.hex
    avrdude -F -V -c arduino -p ATMEGA328P -P ${PORT} -b 115200 -U flash:w:led.hex

That's saying that any automatic C compilation will be done with avr-gcc and the flags specified in CFLAGS.  It will by default make the hex file using OBJCOPY, which is set to the avr one, which relies on the file led.elf - so to get that file it runs the led.elf target, which links the object file led.o with the default libraries using whatever was set in CC. To do that it needs led.o, and it makes that automatically using the program specified in CC and the flags in CFLAGS.  You can then optionally to make install which will run avrdude to install the hex file into the chip.
You can make it even more generic so you can copy it in to other projects and make the minimum changes necessary:
BIN=led
OBJS=led.o test.o

CC=avr-gcc
OBJCOPY=avr-objcopy
CFLAGS=-Os -DF_CPU=16000000UL -mmcu=atmega328p
PORT=/dev/ttyACM0

${BIN}.hex: ${BIN}.elf
    ${OBJCOPY} -O ihex -R .eeprom $< $@

${BIN}.elf: ${OBJS}
    ${CC} -o $@ $^

install: ${BIN}.hex
    avrdude -F -V -c arduino -p ATMEGA328P -P ${PORT} -b 115200 -U flash:w:$<

clean:
    rm -f ${BIN}.elf ${BIN}.hex ${OBJS}

That uses "automatic variables" and simple name replacement.  BIN contains the "base" of your binary files, OBJS contains the list of object files.  $@ is the name of the current target, $< is the name of the first prerequisite, and $^ is the list of all the prerequisites.  Just change BIN and OBJS to suit.  As a bonus I have thrown in make clean to remove the compiled files and just leave you with the source.

the posted makefile needs another line near the top; that says: '.PHONY : install clean'

@user3629249 Why? The makefile as posted works perfectly.  You only need .PHONY for targets called as prerequisites, not targets called manually which those are.

@Majenko It's good practice to create a phony target for anything that's not actually a filename. If you create a file called install or a file called clean (shell scripts, perhaps?), then make may think that they're Up to date and do nothing.

@WChargin If you do something as daft as that then you deserve it not to work.  Your shell scripts should be clean.sh and install.sh if you must have them.

The accepted answer is great as it has given me a valuable lesson in all kinds of debugging tools (avr-objdump -D has become a close friend). Namely, the line:
${OBJCOPY} -O ihex -R .eeprom $< $@
is missing the architecture flag and should read
${OBJCOPY} -mmcu=atmega328p -O ihex -R .eeprom $< $@
Without the -mmcu architecture flag, avr-gcc guesses we are compiling for 8515 architecture (definitely not) and it produces the .elf file without initial instructions for initializing, i.e. without instructions to call the "main" function etc.
This results in confusing behavior as any simple program (e.g. blink) with only the "main" function works perfectly, but if you define another function before or after the "main", it runs that function and never calls "main" or it restarts all the time etc.
I am also not a particular fan of avoiding the verification of correct MCU type and uploaded program, so I'd advocate not to use -F and -V and use -v instead.
So, the improved answer could be:
PKG=led
BIN=${PKG}
OBJS=${PKG}.o
MCU=atmega328p

CC=avr-gcc
OBJCOPY=avr-objcopy
CFLAGS=-Os -DF_CPU=16000000UL -mmcu=${MCU} -Wall
PORT=/dev/ttyACM0

${BIN}.hex: ${BIN}.elf
        ${OBJCOPY} -O ihex $< $@

${BIN}.elf: ${OBJS}
        ${CC} -mmcu=${MCU} -o $@ $^

install: ${BIN}.hex
        avrdude -v -c arduino -p ${MCU} -P ${PORT} -b 115200 -U flash:w:$<

clean:
        rm -f ${BIN}.elf ${BIN}.hex ${OBJS}

You wrote: “Without the -mmcu architecture flag, avr-gcc guesses we are compiling for 8515 architecture”. Actually it's avr2: “‘Classic’ devices with up to 8 KiB of program memory.”

I was referring the the Atmel reference http://www.atmel.com/webdoc/avrlibcreferencemanual/group__demo__project_1demo_project_compile.html Are they mistaken?

Maybe they mean the AT90S8515 MCU which, unlike its replacement (ATmega8515), has an avr2 architecture. The page you link to may have been written in a time when “8515” was not ambiguous. And they don't call it an ”architecture”, since it's only one of many MCUs sharing the avr2 architecture.


text:
Verify a code for Traffic Signal
void setup() {
  pinMode(13, OUTPUT);  // Red
  pinMode(14, OUTPUT);  // Yellow
  pinMode(15, OUTPUT);  // Green
}

void loop() {
  digitalWrite(13, HIGH);
  digitalWrite(14, LOW);
  digitalWrite(15, LOW);  // Stop
  delay(20000);           // Wait 20 seconds
  digitalWrite(13, HIGH);
  digitalWrite(14, HIGH);
  digitalWrite(15, LOW);  // Listen
  delay(20000);           // Wait 20 seconds
  digitalWrite(13, LOW);
  digitalWrite(14, LOW);
  digitalWrite(15, HIGH);  // Go
  delay(20000);            // Wait 20 seconds
}

How good is this code and is there any error ?

Other than that it goes from green to red without intermediate yellow it looks alright.

Replace all literal values with named constants. Instead of 13 define "const int RED_LIGHT = 13". It might be difficult to use this code for all traffic lights at a crossing. Define the use case.

There is nothing wrong with your code. But it could use some cleaning to make it efficient.
The code at the moment will be 'deaf' to any user inputs for twenty seconds between light changes.
This can be fixed by using a timer interrupt and changing the lights every 20 seconds and listen for other inputs or do other things. You can use the arduino timer library, this is well documented and you should be able to find examples of its use. Basically you would monitor a variable until it reaches a point and then trigger the lights.
The other option would be to use the millis() and every 20 seconds change a light, but do stuff between those 20s. This can be done like this:
unsigned long previousMillis;  //hold the previous time
unsigned long currentMillis;   // hold the current time

long threshold = 20000;
int count = 0;

int pins[] = {13, 14, 15};

//setup code stuff

//put the following at the top of loop()

currentMillis = millis();

if(currentMillis - previousMillis > threshold){

    previousMillis = currentMillis;

    for(int i = 0; i < 3; i++){
    digitalWrite(pins[i], LOW);  //turn off all

    }

    if(count > 2) count = 0;

    digitalWrite(pins[count], HIGH);

    count++;
}

I don't think this works as a traffic light sequence, I might be reading it wrong, but I think this just switches a light on every few seconds.

@Matt - the code does switch a light on every few seconds, 20s, but that is as it is an example based off the OPs code where they used 20 second delay for each transition. The code does not change the sequence to match traffic lights but that would be each with a few if() statements to change the delay and keep the amber on.

There is nothing wrong with the code that I can see although you do have some redundant statements:
When you go to "Listen" you set the red and green pins high and low respectively, but they are already high and low from the previous state.  Not a big issue, being verbose adds clarity so there is some argument for leaving it as is.
I would consider using #define macros to number the ports and set the delay times.  This adds readability and also means you can make changes easily without having to search through the code and match up appropriate instances of the port number that you want to change, for example:
#define RED_PIN 13
#define DELAY_BETWEEN_CHANGES 20000
...
digitalWrite(RED_PIN, HIGH);
delay(DELAY_BETWEEN_CHANGES);

This also means that you can get rid of comments in your code as it becomes pretty self explanatory.  I personally believe that comments are bad.  If you write code and put a comment explaining what it does, when you have to modify the code you also have to modify the comment.  Make the code understandable in the first place, no need for comments.
Final point (not related to code): What happens after "Go"?  I'm from the UK so we have another phase after Go.  It reminds me of an old driving test joke:
Instructor: What is the sequence of traffic lights?
Student: Red, red and amber, green.
Instructor: What comes after green?
Student: How would I know?  I've always gone by then!

also in this case not so important but in large projects where you reuse the information, the variable can save some space, specially if you use the ATTiny85 that only have 8 kb flash memory

I have a similar requirement, this gives you a little more flexibility , My traffic light code is controlled by a PIR outside my door , if the PIR detects an individual the lights turn to stop when the PIR clears the lights turn to green.
the code and hardware are still in the test phase.

#include <EasyTransfer.h>

int D_Status_Word = 0;
int Status_Word = 0; //sets all bits to  zero
int Light_Threshold = 150; //the light level that constitutes an unusual entry
int Active = 0;
int Passive = 100;
int Counter = 100;
int Green_Pin = 7;
int Amber_Pin = 8;
int Red_Pin = 9;
int Photocell_Pin = 1;     // the cell and 10K pulldown are connected to a0
int Photocell_Reading;
int Sensor_Frequency = 0;

struct SEND_DATA_STRUCTURE {
  //put your variable definitions here for the data you want to receive
  //THIS MUST BE EXACTLY THE SAME ON THE OTHER ARDUINO
  int Out_Word;
  int LDR_Level;
};

SEND_DATA_STRUCTURE My_Tx_Data;

//create an object for themessage
EasyTransfer ETout;
int D_Sensor_Pin [] = {
  2, 3, 5, 6
};
// pin hallwaypir, 3 doorpir, 5 door sensor, 6 hallpir

void setup() {
  Serial.begin (9600);
  // put your setup code here, to run once:
  ETout.begin(details(My_Tx_Data), &Serial);
  for (int i = 0; i <= 3; i++)// read the two state sensors
  {
    pinMode(D_Sensor_Pin [i], INPUT);
  }
  pinMode(A1, INPUT);//set the analoge u ldr pin ot input mode
  pinMode (Green_Pin, OUTPUT);
  pinMode (Amber_Pin , OUTPUT);
  pinMode (Red_Pin , OUTPUT);
}

void loop() {
  Scan_Sensors();
  if (D_Status_Word != Status_Word)
  {
    Sensor_Frequency = Active; // high frequency sampling because a sensor has activated
    //send a data packet to the mega with mem card via serial.
    Send_Data_Packet();
  }
  if (bitRead (Status_Word, 1) != bitRead (D_Status_Word, 1))
  {
    if ((D_Status_Word, 1) == 1)
    {
      Traffic_Light_Stop();
    }
    else
    {
      Traffic_Light_Go();
    }
  }
  Status_Word = D_Status_Word;

  delay(Sensor_Frequency);// 1000= waits for a second
}

void Scan_Sensors()
{
  byte readings = 0;
  Photocell_Reading  = 0;
  for (int i = 0; i <= 3; i++)// read the two state sensors
  {
    bitWrite(readings, i, digitalRead(D_Sensor_Pin [i] ));
  }
  //test to see if any sensors have trivggered (readings>0)
  if (readings > 0)
  { // a 2 state sensor has triggered, reset the Counter to 100
    Counter = 100;
  }

  //read threshold sensors
  Photocell_Reading  = analogRead(Photocell_Pin);
  {
    bitSet(readings, 4); // 4 becaus there are 4 2 state sensors (0 to 3)
    //we write 1 because thelight is below the threshold
    Serial.print ("photocell Reading = ");
    Serial.println(Photocell_Reading);
  }
  D_Status_Word = readings;
  Counter -= 1; //decrement the Counter
  if (Counter <= 0)
  { //the Counter has counted 100 scans since a 2state has triggered
    //rest freqenvcy to Passive
    Sensor_Frequency = Passive;

  }
}
void Send_Data_Packet()
{
  My_Tx_Data.Out_Word = D_Status_Word;
  My_Tx_Data.LDR_Level = Photocell_Reading;
  Serial.print ("photocell Reading = ");
  Serial.println(Photocell_Reading);
  Serial.print ("status word = ");
  Serial.println(D_Status_Word);
  ETout.sendData();
}

void Traffic_Light_Stop()
{
  //lights turn from green to yellow to red
  digitalWrite (Green_Pin, LOW);
  digitalWrite (Amber_Pin, HIGH);
  digitalWrite (Red_Pin, LOW);
  delay(750);
  digitalWrite (Green_Pin, LOW);
  digitalWrite (Amber_Pin, LOW);
  digitalWrite (Red_Pin, HIGH);
}

void Traffic_Light_Go()
{
  //lights turn red to red and yellow to green
  digitalWrite (Green_Pin, LOW);
  digitalWrite (Amber_Pin, HIGH);
  digitalWrite (Red_Pin, HIGH);
  delay(750);
  digitalWrite (Green_Pin, HIGH);
  digitalWrite (Amber_Pin, LOW);
  digitalWrite (Red_Pin, LOW);

}


text:
How do I connect this SPI serial display to an Arduino?
I've recently purchased a screen on DX without really thinking about it, because I have no idea how to connect it to my Arduino.
It is this screen:

The description says that it uses the SPI serial protocol but I don't know how to connect that ribbon to my Arduino, is soldering cables to it the only way?

I believe that this may be the specification: http://www.elecfreaks.com/store/18%E2%80%99%E2%80%99-tft-lcd-tft0118sp-p-671.html

There are a ton of pins coming out of that LCD.
I could imagine that it needs some kind of driver chip (which might be controlled through SPI).
I've recently ordered one (which looks rather similar) but with a "breakout" or driver board (http://www.sainsmart.com/sainsmart-1-8-spi-lcd-module-with-microsd-led-backlight-for-arduino-mega-atmel-atmega.html/).

That kind of connector is most commonly directly soldered on to a PCB.  You can buy adaptor boards with the various different pitch pads on them for soldering it to.

Also there is no mention of what chip the screen uses (I am unfamiliar with "XS057" as a chip, so that is probably the model of the screen not the chip).  At that resolution it's probably an ILI9163, but without being sure all you can do is stab wildly in the dark and try different drivers.

That looks like exactly what I need! Thanks.
And I did find the datasheet on this website, so once I get that PCB I can most likely find my way. Thanks again!

You might find this useful: https://www.youtube.com/watch?v=R698z9QaypY

Ah, it's an ST7735. That would have been my second choice.  Same basic chip as is used on the adafruit 1.8 shield: http://www.adafruit.com/products/802

On the datasheet I found this specification, so that means I need an adapter for 0.40mm correct?

No, that's the pad width.  The one you are interested in is the "P+1.0 * 23 = 10.40", but that makes little sense to me.  The 10.40 is key though.   My calculations say that if you have 20.90 full width, with 5.25 gutter each side, that leaves 10.40 for the connector width (correct). With 14 pads that's then 13 spaces between them (from the center of the first to the center of the last), which is 10.40 / 13 = 0.8mm pitch.

if you have the pinout you should be able to solder the hookup wires directly to the pins if you know how to use solder paste and a heat gun and skill if you are a beginner you need to put it in a box and order something from other suppliers more friendly to newbes.

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


text:
What is the difference between a motor driver and a motor shield?
what is the difference between a motor driver(like L293D) and a motor shield?
what are the advantage?disadvantages of both?
And which one do you suggest ?

A motor driver is a chip that drives motors.  A motor shield is a circuit board with connections on it that contains a motor driver chip that drives motors.
A shield is convenient since you can just plug it in to your Arduino and wire the motors direct to it, but it lacks the flexibility of a raw driver chip which you can wire up precisely as your project demands.

Not sure if it's correct, but my definition of shield is: something that is pluggable on the arduino, iow has connectors and board that allow for stacking. There are a variety of boards that are not stackable and must be connected with wires, even if they contain more than just the driver.

The differrence is usablilty and, in some cases, the protection of your chip; if there is a surge of more than 5V to your driver it will fry, which is why some drivers have onboard voltage regulators and a heatsink for overheating problems. Advantage of motor driver is that you can use it as per your requirements, whereas a shield is fixed and you cannot change any aspects.

A motor driver is a chip that drives motors. A motor shield is a circuit board with connections on it that contains a motor driver chip that drives motors.
A shield is convenient since you can just plug it into your Arduino and wire the motors direct to it, but it lacks the flexibility of a raw driver chip which you can wire up precisely as your project demands


text:
Three phase sine wave inverter using Arduino
I want to design three phase sine wave inverter using Arduino I found this link with circuit diagram and simulation results but he did not provide code. can anyone help me with code http://microcontrollerslab.com/three-phase-sine-wave-inverter/

The author explains the design of the code in http://microcontrollerslab.com/spwm-generation-using-pic16f877a-microcontroller/

It's a pretty cool article-Bilal Malik varies the duty cycle of a 20kHz PWM with a look-up table to produce 50 PWM cycles of a rising quarter-sine-wave, 50 cycles back down, then switches the polarity and does it again, using it to drive an H-bridge feeding a transformer.

This guy is doing the same. His code is free of charge. http://www.eprojectszone.com/how-to-generate-three-phase-spwm-signal-with-arduino/

At the end of the page you are linking to, there is this notice:
"Code for three phase inverter is not free of cost. If you want to purchase code, you can contact me at bilalmalikuet@gmail.com"
If you are Bilal Malik, you should already have the code since you are offering to sell it - unless you want someone here to write it for free so you can sell it afterward.
If you are NOT Bilal Malik, you should not impersonate someone else here.
I am not a huge fan of the concept of intellectual property, but it seems you are trying to do something shady here.

It is a Roger Finer who asked the question. Why do you think he could be Bilal Malik?

@PimV: When you change your name in your stackexchange account, all your previous posts suddenly show your new name. So it is possible for a question to be asked by "a", and then show it was asked by "b".


text:
Will writing to serial when no serial is available cause problems?
I have an Arduino UNO, and use the serial for debugging purposes. What happens if I run the arduino on batteries and try to write to serial? Will the code stop running until a serial connection is availible?

What will happen is the data will dribble out of the unconnected port and drip onto the floor.  Data stains can be a real pain to get out of carpet, so put some newspaper down first.

No, that will not cause any problem.
What might hurt you is the fact that if you want to leave your Arduino in low power mode, but keep the serial potr disconnected and the serial port is a wakeup source, it might pick up sporadic (but frequent enough to cause be noticeable) noise that will trigger wakeups and spam with meaningless data your RX.
This, however, is not specific to the serial port, but it can happen to any wake up source that is enabled and left dangling.

It's not left dangling. The RX and TX are connected to the ATMega16u2 that does the USB-to-Serial conversion.

ok. Actually there is a way to disable the USB to serial converter. If you short its reset pin, like in the procedure required to update its firmware with dfu utils, it should do in high impedance mode (I think).

I seem to recall the Arduino core or bootloader code activating an internal pullup on the serial input line anyway.


text:
How is the diode here effective?
I'm working on project 9 of the arduino starter-kit - the motorized pinwheel.
Here is the schematic:

The diode in question (and the only one here) is toward the bottom right of the breadboard. It is to prevent the back-voltage from the motor from harming the circuit.
According to the above img, would the backvoltage travel back down the motor's supply of energy (the red wire)?
If so, what is the diode preventing here? That whole energy strip will just have current running through it and the diode's cathode will prevent it from running to the transistor - which would also happen fi we just didn't connect anything to that power strip.
If not, and the back-voltage is running through the black wire (our ground), then I still do not see how the diode is helping. The diode seems to want to pull the extra energy back to our power strip (which is why the anode is facing toward the left, where the motor's output is. But this doesn't prevent the current from still hitting the green wire which leads to the transistor's 'source'.
So how is this diode working?
Thanks!

Think about what the diode would do if it was just the diode and the motor, and you turned the motor in the opposite direction to normal (generated "back EMF").  It's just the same whether the rest of the circuit is there or not.

Thanks for the response. I'm still not understanding this. What happens if we just take the diode away here. Where is the back-voltage going? To the battery?

+1 Excellent question. Something puzzling that seemed not to make sene -> major lesson learned. (Hopefully :-) )

Please note that only fast diodes are effective there, as most H-Bridges that require external diodes will specify on their data sheets. If you are using a transistor like in your circuit, it's always a good idea to go for the fast version of a diode. For example, don't use a 1N4007, but an UF4007 (Ultra Fast) instead.

Under normal operation the + connection of  any inductive component (motor, relay, etc) is at a higher potential than the - connection.
During a "back EMF" event (the collapsing of the magnetic field) a large voltage of the opposite potential is generated.  That means that the - connection suddenly becomes a much higher potential than the + connection.
That is very bad for anything connected to the - pin of the inductive load.
With the diode connected backwards like that across the inductive load, under normal operation, it does absolutely nothing.  However, when the - pin becomes a higher potential than the + pin the diode will become forward biased and start to conduct.  That allows a very low resistance path for all the energy stored in the coil of the inductive component to flow from the high potential to the low potential, which is what it wants to do.
Without it, the only way for that energy to get from the high potential to the low potential is through the rest of your circuit, which it won't like.
The excess energy at the - side of your motor wants to get to the + side. That's the only place it wants to go.  It'll (crudely speaking*) take the shortest, quickest, route to get there.  That means it goes through the diode and nowhere else.  Straight from the black wire to the red wire of your motor.

* Note: In actuality the energy will take all possible routes at once, but in varying proportions depending on the resistance of the route.  The lower the resistance the greater the proportion. Because the diode is such low resistance it gets the majority of the energy and only a very negligible proportion takes the other possible routes through your circuit. Unless your circuit is incredibly sensitive it won't even notice it's there.

This makes sense. Thank you. I have the same question to you as I do with the above answer. Can you check my question in the comments to that answer? After that, I should be good to go. Thank you!

See my edit.  It should cover it for you.

Flywheel Diode.
When the transistor shuts off, the stopping of the motor generates back EMF (ElectroMotive Force) . This manifests itself as negative potential difference (voltage) across the motor. In plain English the collector of the transistor, connected to the -Ve side of the motor, is raised to a damagingly high voltage. If you include the diode, this voltage is siphoned immediately back to the positive rail, so the damage is averted.

This makes sense. I now get that the diode is trying to conduct the extra charge back to the positive rail. Still, won't some of that extra (harmful) voltage still reach the transistor through the greenwire? Or can that simply not happen because of the presence of the diode?


text:
Critical sections in Arduino, interrupt consuming data
We all know the interrupts, but how do they really work?
The problem:
In my sketch an interrupt method (invoked when pin goes high) is consuming data from a buffer and the main loop() is filling the buffer at random speeds (from Internet - I'm using ESP8266, not the Arduino). Although I think there shouldn't be any threading problems with this buffer - I might be wrong - the program hangs up after random number of seconds (about half a minute average - and then the built-in watchdog resets it after few seconds). When I detached the interrupt method and merged it into the main loop() code, the problem disappeared (but I can't leave it like that). So it's probably either that I'm doing something illegal in the interrupt method (maybe it's just taking too long - how much time can an interrupt method take?) - or the second possibility - it is a threading problem.
The questions:
The main question is: how to correctly synchronize the interrupt method? How to create a critical section if the interrupt method cannot wait (for a semaphore) and if I leave it, it won't be invoked again because the pin is already high? And the detailed questions:

How to create a thread-safe variable (a bool flag), so that interrupt method can skip the critical section if the main loop has entered it? (I understand the interrupt method is "safe" - it won't be interrupted - but how to secure the regular code?)
If I detach an interrupt method that is triggered when a pin goes high when it is low (for just a few fast instructions), the pin gets high in that time, and then I'll re-attach the method to this pin again, will it be invoked? The same question for noInterrupts(); How to make sure it will be invoked, if I can't check the pin and invoke (or not) the method manually in an atomic transaction with re-attaching the method?
If I detach this method (in main loop), is it possible that it will be invoked before the control is back from the detachInterrupt() method? (because the pin got high from external device in this very moment) And the same question for noInterrupts();
I've read that noInterrupts(); causes some things, like reading incoming serial data, to be skipped. Can this method be even used if I don't want that? Or can I have guaranteed that it won't happen if the method is fast enough? (if so, please define the "fast enough"!)

So, is there a common template for creating a critical section between an interrupt method and the regular code? Or at least synchronizing a variable access? And if not, how to make sure the detached/blocked pin method will be invoked after re-attaching/re-enabling it?
The common buffer code:
(if you want to check whether this can cause any "threading" problems)
class Buffer
{
  protected:
    byte *buf;
    int len, readpos, writepos;
    bool wasFull, wasEmpty;
    long ratioSum, ratioCount;

  public:
    Buffer(int length)
    {
      len = length;
      buf = new byte[len];
      readpos = writepos = 0;
    }

    bool isFull()
    {
      bool full = writepos - readpos >= len;
      wasFull &= full;
      return full;
    }

    bool isEmpty()
    {
      bool empty = readpos >= writepos;
      wasEmpty &= empty;
      return empty;
    }

    void write(byte b)
    {
      if (isFull()) { if (!wasFull) { wasFull = true; Serial.println("Error: Buffer overflow!"); } return; }
      int pos = (writepos++) % len;
      buf[pos] = b;
      if (readpos >= len && writepos >= len) { readpos -= len; writepos -= len; }
    }

    byte read()
    {
      if (isEmpty()) { if (!wasEmpty) { wasEmpty = true; Serial.println("Error: Buffer underflow!"); } return 0; }
      int pos = (readpos++) % len;
      if (readpos >= len && writepos >= len) { readpos -= len; writepos -= len; }
      return buf[pos];
    }

    int available()
    {
      return writepos - readpos;
    }

    void measureRatio()
    {
      ratioSum += available();
      ratioCount++;
    }

    int getRatio()
    {
      int ratio;
      if (ratioCount > 0)
        ratio = 100 * ((float)(ratioSum / ratioCount) / (float)len);
      else
        ratio = 100 * ((float)available() / (float)len);
      ratioSum = 0;
      ratioCount = 0;
      return ratio;
    }
};

PS:
I have discovered that printing to Serial in the interrupt method (even without a flush() is causing my program to crash after max half a second. Is it just a duration of printing or is it something else? Also if you're thinking that the warning printing in my Buffer code can cause the crashes, then I assure you that they're not because I always check isEmpty() and isFull() before each read and write operation, so they just can't occur.

For people looking for a really good interrupts tutorial and detailed deep info how they work, I have found this great article by Nick Gammon:
http://gammon.com.au/interrupts

Warning: I am not familiar with the ESP8266 hardware, and some of my
answers below may be only valid on the AVR architecture.
The simplest way to synchronize your main code with your interrupt
service routine is to define a critical section in your loop() that
wraps access to the shared data, and to make sure this critical section
cannot be interrupted:
noInterrupts();
buffer.write(data);
interrupts();

This should be fine as long as you make the critical section as short as
possible. Majenko's recommendation, to inspect the write() method with
“a fine toothed comb” in order to minimize the critical section, is
definitively good advice.
To understand the relevance of the “as short as possible” requirement,
think about what could happen if the interrupt triggering event (the pin
going high) happens while interrupts are disabled. If this happens
once, it's not a problem: the interrupt is put on hold (technically,
an interrupt flag is raised), and then it's serviced as soon as
interrupts are enabled again. However, if the pin goes high twice
while interrupts are blocked, then, when you enable interrupts again,
the interrupt handler will be called only once. Whether this is a
problem or not I cannot say, it all depends on what job the handler is
supposed to do.
Now, to the specific sub-questions:

How to create a thread-safe variable (a bool flag)

Chances are the boolean can be read and set atomically, so it's
inherently thread-safe. On an 8-bit CPU, like the AVR, access to a
multi-byte variable has to be protected inside a critical section. But
since you have a 32-bit CPU, I bet you have atomic access to variables
up to 32-bit wide.

If I detach an interrupt method that is triggered when a pin goes high
  when it is low (for just a few fast instructions), the pin gets high
  in that time, and then I'll re-attach the method to this pin again,
  will it be invoked?

Hard to say without reading both the datasheet of the hardware and the
source code of attachInterrupt(). It may be safer to keep the handler
attached and start its code with something like
if (doNotRunInterruptHandler) return;.

The same question for noInterrupts();

Yes, it will be invoked, but at most once.

If I detach this method (in main loop), is it possible that it will be
  invoked before the control is back from the detachInterrupt() method?

Yes, the interrupt can fire while detachInterrupt() is checking to see
whether you gave it valid parameters.

same question for noInterrupts();

Check the implementation. On the AVR, noInterrupts() is atomic.

I've read that noInterrupts(); causes some things, like reading
  incoming serial data, to be skipped.

Nothing like this will happen if your critical section is fast enough.

please define the "fast enough"!

It depends on how long you can afford to delay the interrupt service
routine. For example, if you are reading serial data at 115200 bps
and the UART has only a one-byte buffer, then a 86 µs critical
section can make you loose one byte.
Then, there is the risk that several interrupts of the same kind fire
during the same same critical section. As said before, the interrupt
will only be serviced once. If this is a problem, then you should not
block interrupts for longer than the minimum possible period of the
triggering event.
Also, there is always the risk that several, unrelated interrupts fire
during the same critical section. Then, the one with the lowest priority
will have to wait for the critical section to finish and then for the
higher priority interrupt to be serviced.

"Chances are the boolean can be read and set atomically, so it's inherently thread-safe." - if that's even true, it doesn't solve the problem of reading a flag, and if it's false then setting it to true (a flag that acts like semaphore for critical section). The interrupt can happen between reading and writing the flag, so both "threads" can enter and "think" that they're alone. There should be an atomic exchange instruction that inverts values between two variables (registers) - this is the only way to make it safe as far as I know. Is something like that in Arduino/ESP?

Firing the delayed interrupt only once is not a problem in my case because it's a "ready for more data" signal. So, if I understand correctly, the only safe way for me is the noInterrupts() and wrapping write() with it, because after this line I can be sure that the interrupt won't be fired and it won't be skipped if the pin got high during critical section. Knowing that, I've wrapped the write() in it, removed substracting positions from read() method (write() is now safe) and also blocked the Serial printing (just to make sure) - and it is still crashing... How is it possible?

@P.W.: There is no support for atomic exchange in the Arduino library: you may need to look low level, at the instruction set. The AVR architecture only supports this in the XMega cores, and I know no Arduino using these cores. As for why your program is still crashing, I do not know.

Ok, so knowing that the program works fine when the interrupt method is just called from loop() instead attaching it to the interrupt, knowing what I just did (the comment above) and looking at the "critical" buffer code - are you sure that there are no "threading" errors left? The code should work and there is nothing left that can be done? (The interrupt method just reads the buffer and forwards it through SPI in very small portions and at high speed). PS: Thank you for the useful facts in your answer.

Man! You gave me the answer but even you didn't realize that! See my own answer for details - thank you!

The trick here is not to make your interrupt routine, or your main routine "thread safe" - instead you need to make the single item that is shared by the two "thread safe". That means your Buffer class.
You need to go through that with a fine toothed comb and work out which bits could possibly be accessed by the two contexts at once and protect them.
The bits that jump out at me immediately are the calculations and manipulations of writepos and readpos. Accesses to those variables need to be made as atomic as possible.  One of the best ways of doing that is to massively restrict the actual access to those variables and wrap those accesses in critical sections (disable / enable interrupts). That keeps the critical sections as short as possible.
For instance, instead of directly manipulating the variables, as you enter the function you first create "cached" copies of the variables you will modify that could be modified at the same time (such as writepos being written to in the ISR):
cli();
int cachedWritePos = writepos;
sei();

Then you do your manipulations and calculations on those cached variables. Finally, just before you exit the function, you write your now safely changed cached variable values back to the member variables:
cli();
writepos = cachedWritePos;
sei();

The critical sections are then as brief as possible, and any heavy calculations (I count the modulus operator % as a heavy calculation) don't block the interrupt from firing.
Of course that is not a foolproof method and doesn't protect against two contexts changing the same variable and it getting out of step. To counter that you will have to use a mutex. There's no getting around that, other than ensuring that your program never changes the same variables from two different contexts. The only mutex you really have access to is a manually implemented spinlock.
On that note, I am having some trouble following the logical flow of how your buffer works. There are bits that don't look quite right to me, such as this bit:
if (readpos >= len && writepos >= len) { readpos -= len; writepos -= len; }

According to my way of thinking both readpos and writepos have to have reached (or exceeded) the end of the buffer for them to wrap around to the start again.  That can't really happen properly in a function that is only writing, or a function that is only reading. I think you want to only be checking writepos and wrapping that in the write function, and only checking readpos and wrapping that around in the read function, not both in both functions.
As far as using Serial in an interrupt goes, the general rule is: don't do it.  I don't know about the ESP8266's serial code, but certainly on the Arduino it relies on interrupts being used to take each character from the TX buffer and transmitting it through the UART interface. If you are in an interrupt routine and your (64 byte) serial TX buffer fills up any attempts to write to that buffer (Serial.print) will block until the interrupt that sends the characters has made some room for you - and of course that interrupt will never happen while you're blocking because you are in an interrupt at the time.
On systems with multiple priority levels of interrupt (such as a PIC32) the same holds true if you are in an interrupt routine that is at a higher priority than the Serial interrupt. If you are in a lower priority one the serial interrupt can still interrupt your current interrupt routine and function correctly.

“I count the modulus operator % as a heavy calculation”. Modulus is cheap if the compiler can optimize it to a bitwise AND, i.e. if the dividend is unsigned and the divisor is both a power of two and a compile-time constant. This is not the case in the OP's code, but that could probably be fixed.

Regarding to the line if (readpos >= len && writepos >= len) { readpos -= len; writepos -= len; } - it's logically OK. It's just for preventing readpos and writepos from exceeding the range of an int and becoming negative. And they should be checked and modified together, because if you would substract only the writepos (which first crosses the line) then it would become less than the readpos, meaning that there were more bytes read than written. It doesn't matter when this substraction is done, as long as it is done together and is thread-safe (and it isn't!). Thanks for tips!

You might want to consider a circular buffer (unless that is what you are attempting, I am not sure with your code).

Yes, I think that a circular buffer is what I just did here - but what do you mean by that? Are you thinking about some specific class? (I'm not very good at C++ so I may not know some obvious common classes).

The logic of your system looks like an attempt at a circular buffer but hasn't quite got it right. I have a CircularBuffer library you are welcome to pull apart and see how it should work: https://github.com/MajenkoLibraries/CircularBuffer

Thanks, but do you see any logical errors in this code? Because it works just fine (if not invoked from an interrupt!). Worked for almost 1.5h and didn't crash (while on interrupt it's about 30 seconds).

I am still concerned about how you think the circular buffer is meant to work with that code I highlighted in my answer. Despite your explanation it still makes absolutely no sense to me. The write function should never have any need to change the read pointer, nor the read function the write pointer. Ever. Full stop. Reading and writing are completely separate things.

@Majenko I agree it's not a good idea and unnecessary (and maybe I'll even change that later) but it makes perfect sense: writepos - readpos means how many bytes is writing ahead of reading. When any of them reaches the size of buffer, it is wrapped around (by modulo) so the buffer is written/read from start again. If both of them are greater than the length of the buffer and you substract a buffer size from both of them at once then both data positions (calculated by modulo) and writepos - readpos value does not change. It's for preventing overflow (size of int) only.

That still makes no sense at all. When you write you should wrap the write pointer. It won't overflow. When you read you wrap the read pointer. It won't overflow. If the write pointer would equal the read pointer after a write then the buffer must be full so you block waiting to write or discard data depending on what you are doing.

@Majenko You don't understand, the writepos and readpos are not wrapped - they are just incremented (and that's why I have to worry about int range). The modulo is calculated only at the moment when accessing the byte of data. If you don't believe me this code ok then create some unit tests and check it out. This is for 100% not the cause of the problem.

It's no wonder it isn't working then, and no wonder I cannot understand the logic of your program. That is certainly not how you create a circular buffer!

Let us continue this discussion in chat.

My problem with crashing is fixed! :) I will share here what was wrong - maybe someone will have similar problem in the future.
But first...
I have marked Edgar Bonet's answer because he answered most of the difficult questions that were bothering me and for pointing me out that reading a 16-bit variable on 8-bit processor is not atomic (it was the most significant clue) and for helping me to understand that noInterrupts() is the safe and only way to synchronize with the interrupt method in my case. Thanks Edgar! But credits also go to Majenko because I wouldn't have guessed it without him. He pushed me into the right direction in our chat discussion - that I have to secure all the methods accessing readpos and writepos. Thanks Majenko. I agree with him that my Buffer code is ugly and it's not a good way to implement a circular buffer, but it was still logically OK - it just needed one more thing...
The solution
You probably know it already. The key is the non-atomic reading of readpos and writepos. For example: the code from loop() starts to read readpos, reads the first byte of it, then the interrupt happens, readpos changes there and the loop() continues reading the other (changed) half, which is then glued with the old (out of date) half - so - a random value. Or another one: the loop writes first byte of writepos (as it fills the buffer) and then interrupt fires and reads the first (changed) byte with the old (out of date) second byte. So the solution is to just wrap all access to those variables with noInterrupts() - and the whole code works perfect! :) Thank you guys! Not only for helping me to fix it, but for helping me to understand it.
Here is how it looks like now (non-crashing version):
class Buffer
{
  protected:
    byte *buf;
    const int len;
    int readpos, writepos;
    bool wasFull, wasEmpty;
    long ratioSum, ratioCount;

  public:
    Buffer(const int length)
      : len(length)
    {
      buf = new byte[len];
      readpos = writepos = 0;
    }

    bool isFull()
    {
      noInterrupts();
      bool full = writepos - readpos >= len;
      wasFull &= full;
      interrupts();
      return full;
    }

    bool isEmpty()
    {
      noInterrupts();
      bool empty = readpos >= writepos;
      wasEmpty &= empty;
      interrupts();
      return empty;
    }

    void write(byte b)
    {
      if (isFull()) return;//{ if (!wasFull) { wasFull = true; Serial.println("Error: Buffer overflow!"); } return; }
      int pos = (writepos++) % len;
      buf[pos] = b;
      if (readpos >= len && writepos >= len) { readpos -= len; writepos -= len; }
    }

    byte read()
    {
      if (isEmpty()) return 0;// { if (!wasEmpty) { wasEmpty = true; Serial.println("Error: Buffer underflow!"); } return 0; }
      int pos = (readpos++) % len;
      //if (readpos >= len && writepos >= len) { readpos -= len; writepos -= len; }
      return buf[pos];
    }

    int available()
    {
      noInterrupts();
      int result = writepos - readpos;
      interrupts();
      return result;
    }

    int free()
    {
      noInterrupts();
      int result = len - available();
      interrupts();
      return result;
    }

    void MeasureRatio()
    {
      ratioSum += available();
      ratioCount++;
    }

    int getRatio()
    {
      int ratio;
      if (ratioCount > 0)
        ratio = 100 * ((float)(ratioSum / ratioCount) / (float)len);
      else
        ratio = 100 * ((float)available() / (float)len);
      ratioSum = 0;
      ratioCount = 0;
      return ratio;
    }
};

I'm glad it's working now. Thank you for sharing this final summary.


text:
Arduino PWM Pins Interrupt
I am creating pwm from an arduino pin with 50% duty cycle. I just want to know how can i detect its every falling edge using timer interrupt? I don't want to connect that PWM pin to an external interrupt pin. Please help me.

You can define an interrupt service routine (ISR) for each Timer and PWM pin that it handles. These are known as TIMERn_COMPA_vect, TIMERn_COMPB_vect and TIMERn_COMPC_vect. The Mega has six Timers (n=0..5).
ISR(TIMERn_COMPA_vect)
{
// Timer/Counter compare match A
}

Check the PWM configuration for how the pin is set, cleared or toggled.
Cheers!

Besides creating the ISR(... you also need to enable that interrupt (e.g. TIMSK1 |= _BV(OCIE1A))

Referring to the datasheet of ATMega328P: If you want to generate an interrupt every falling edge you must know if the Pin is inverse mode or not. As you can see from the timing diagram the Pin stays high until the compare unit matches (current value of the TCNCT == value stored in OCRn ) and then goes low in the normal mode or works as opposite in the inverting mode.
This could be regulated by changing the bits COMnx in the TCCRn register. If, for example: COM0 = 1 and COM1 = 1 the table says: Set OC0A on Compare Match, clear OC0A at BOTTOM, (inverting mode).
Now with these settings the falling edge happens when the timer overflow, so the ISR must occur when the timer reach its maximum value.


text:
Photoresistor Switch
How would I use a photoresistor like a switch. My issue is it is always bleeding out a little bit of power and always on. Is there a way to connect it to a digital pin and when a resistance of xxx is ment, set another digital pin to On?

First off, what is the circuit you are using with the photoresistor. What is the type, you get ones which have a light blocking casing allowing only IR through, or is it clear, if its clear it will pick up any light that leads to another point you can add, where is the sensor placed. There are other things to use other than an arduino, like a comparator. Have a look at this http://arduino.stackexchange.com/a/13318/2944 it has a few points there for you to start with

Without a schematic, how can we help you?

To turn an analog signal into a digital signal, at some sort of threshold xxx, you need to either condition it in electronic circuitry, with something like an amplifier or a comparator, or read the analog signal directly and apply the threshold in software.
You likely need to connect the photoresistor as half of a voltage divider, as in Why do you need a second resistor when using a photoresistor/LDR?


text:
avrdude.conf: programmer type must be written as "id_type"?
I'm trying to compile & run using ino.
At the ino upload step I get the following error:
avrdude: error at /usr/share/arduino/hardware/tools/avrdude.conf:332: programmer type must be written as "id_type"
Relevant section of avrdude.conf:

programmer
  id    = "wiring";
  desc  = "Wiring";
  type  = wiring;   # line 332
;

I've seen various posts around the internet that suggest I just delete the config & refresh it, but I'd like to find the correct syntax and actually understand & fix the issue.

Which version of the IDE are you using? Did you download it from the Arduino site, or install using apt-get?

I'm not using an IDE, just ino: http://inotool.org/

After looking at the source repo it looks like quotes are now required:

  type  = "wiring";


text:
How to program an nRFL01 RF module that is connected to a pc via a USB to UART/TTL adapter?
In a few of my previous questions I was told that the nRF24L01 RF Module can be connected to a pc using a USB to UART/TTL adapter. After a bit of research I understand that one way to use it is to connect it to an arduino- and then to use certain dedicated libraries like RF24.h, and nRF24L01.h to send and receive data. Though I've not been able to find any tutorial outlining the procedure for programming the nRF24L01 once its been connected to the pc.
  How do I send and receive data using my pc-interface? What software do I write and how do I write it?

No, it needs a USB to SPI interface, not USB to UART interface. That's the FT2232 not the FT232 (confusing I know).

@Majenko - actually, I believe you can do SPI with the FT232H and possibly even very slowly the everyday FT232RL.  But you are right that this is not UART functionality but a different operating mode and its corresponding host side API, and also the FT2232H/FT44232H are much better at it.

In short: whatever software you use on the remote end (rf24.h for example) you have to re-write on the PC using whatever language you can interface to the FT2232 with. That means having intimate knowledge of:

The USB to SPI adapter you choose (NOT USB TO UART!)
The low-level control and interfacing of the nRF24L01+ chip
The exact protocol used by your chosen Arduino library.

That's a lot of understanding which (by the level of your questions) is most likely way outside your area of ability.
If you equate time to money then the cost of doing what you want to do is far higher than just using a small Arduino to act as an intelligent interface between your PC and your chosen wireless system. You can discount points 2 and 3 above since they have already been done for you by the Arduino libraries and tutorials. Point 1 becomes considerably easier since you are then just talking to an Arduino using a protocol which you yourself have come up with.
So do yourself (and us) a favour and come to your senses and just plug the nRF24L01+ into an Arduino then plug the Arduino into your PC and program the Arduino to do the RF communications according to commands and instructions you send to your sketch from the PC.


text:
What options do I have to wirelessly connect my computer to an arduino?
For my project I have an arduino Uno connected to my robot. I need to control it wirelessly. I have thought of using a bluetooth module , but I need a larger range. Then I thought of using an RF-module like the Xbees and the 2.4 Ghz nRF24L01. However I can't use the Xbees due to budget issues. As for the nRF24L01- I understand that using the trasmitter and receiver modules I can transmit information between 2 arduinos- however I need to transmit from my computer to my remote arduino. I want to achieve this without using a second arduino at the transmitting (computer) end. Is there a way to achieve this?

How about using wifi?
The esp8266 costs as low as 3$ and has good range.
here's a quick tutorial
What you'll need to do is send a command to the esp8266 and in turn it'll communicate with the arduino via Serial (or Software Serial) and tell it what to do.

It is also not very cheap, but you can easy use wifi shield. The one I sent you is from arduino, but there are chinese analogs which are cheaper. You can use them either to connect your arduino to computer or to connect it to the other devices. Have fun!


text:
How to connect an RF module directly to a PC without using an arduino?
I know that in xbees i can connect the xbee module directly to my pc using the USB explorer. But I'm using the nRF24L01 RF modules. I want to transmit from my pc, via the RF transmitter to my RF receiver, which is connected to my arduino. How do I connect this RF module directly to my PC?

There's a version of the nrf24 chip with a USB interface, often sold assembled as a data link for quadcopters, but its not cheap and there would be new things to learn.  A simple  MCU board, Arduino or otherwise, that you are already familiar with may be best.

The nRF24L01+ uses SPI. PCs don't (usually) have an SPI interface. So you will need some piece of hardware to provide the PC with an SPI interface.
That could be an Arduino, or it could be a dedicated SPI dongle, such as one based around the FT2232 chip.
Of course, you then would need to write software to use that SPI interface and work with the nRF24L01+ connected to it, including using the same message format / packet system, which won't be a simple task. So you may be better off just using a small Arduino to do the communication and present you with a simple serial interface for sending / receiving messages. That way you can then use the same nRF24L01+ software that you are using elsewhere in your setup.


text:
Can the EWRF 3022 module be directly connected to the pc totransmit data from the pc wirelessly?
In my project I want to connect my pc to an RF transmitter. The receiver will be connected to an arduino on my robot. However most of the RF modules I looked up couldn't be directly connected to my computer- in all of them I needed to use an arduino on the transmitter end too. Then I came across this:

 EWRF 3022

Can this be directly connected to my computer? If so, how is it done?

How many modules are you going to ask the same question for? You can find out for yourself: Look to see if the module has a PC interface - that is (generally) a USB or RS-232 interface. If it has then yes you can. If it hasn't then no you can't.

If you use a USB to TTL UART adapter, such as an FT232 dongle, then yes you can communicate to it from a PC.
It will not directly connect to a PC though without you getting that extra hardware.

Thanks. Also, what are some other similar, more popular, modules having a PC interface? I mean, is there one which is more commonly used for this purpose?

The only common wireless systems that have a direct PC are WiFi and Bluetooth. Anything else people design a dongle.

What about xbees? They have a USB explorer board, by which they can be directly connected to a pc.  The only problem with them is the cost.

That is really no different to using an nRF24L01 with an Arduino, or whatever that is you linked to above with a TTL to UART adapter. I don't see what you have against using extra hardware, especially when you yourself then suggest using extra hardware.

In another answer, you said that using a TTL to UART adapter will require writing more software, right? If I remember what I read correctly, the xbees involve significantly less coding right? How so?

I don't know, I have never used an XBee. I think there is some kind of configuration program that sets them up. However, you will still need to write some software to do the communicating.

Ok. I see. Could you also elaborate on what software I have to write to make it work?

No, I can't. What software you need to write depends on what you are doing and what you are doing it with.