text:
How to detect if more than one button was pressed
I am designing a turn signal bicycle blinker using two pushbuttons as input, one for each side, with a corresponding light for each button.
The idea is this:

Pressing one side makes same side start blinking;
Pressing same side again to turn it off;
Pressing other side turns off this side and turns other side on;
(now the tricky part!) if both buttons are pressed (or more precisely, if one button is pressed before the other is released), then - and only then - I start blinking both sides ("warning signal" feature).

As I see it, the problem is that I need to wait until I release a single button (that would be one complete click) to turn a single side on, because if I press the second while the first remains pressed, that would be another event/gesture ("both_click", for lack of a better name).
Another design option would be to turn a single light on immediately on press, and if I press the second before release the first, then in would also turn the other light (thus comprising the "warning", both-lights-blinking mode). While that sounds feasible, there is all the debouncing logic in the Button ("Botao") class, and I am afraid I painted myself into a corner with the specific object-oriented design choices I've made.
EDIT: a third design option would be to add a run method on each button and, instead of only running the tested "pseudo-event" method, save the current state and event in variables, testing those variables in loop() (property button.wasPressed instead of method button.wasPressed(), for example).
I'm posting my current code (relevant parts only). Note there is a comment in the loop where I think I should detect double click.
Main .ino file:
#include "PiscaPisca.cpp"
#include "Botao.cpp"

PiscaPisca pisca;

Botao botao1;
Botao botao4;

void setup() {

  pisca.configure(LEFT, RIGHT, BUZZER);

  botao1.configure(BUTTON1);
  botao4.configure(BUTTON4);
}

void loop() {

  // HOW SHOULD I DETECT BOTH WERE PRESSED??
  // if (bothPressed()) { pisca.toggleWarning(); }

  if (botao1.wasPressed()) { pisca.toggleLeft();  }
  if (botao4.wasPressed()) { pisca.toggleRight(); }

  pisca.run();
}

Botao.cpp (this is a button class with debounce)
#include <Arduino.h>

class Botao
{
    int _pino;

    const int DEBOUNCE_DELAY = 30;

    int buttonState;
    int lastState = HIGH;

    int lastDebounceTime;

    public : void configure(int pino)
    {
        _pino = pino;
        pinMode(pino, INPUT_PULLUP);
    }

    public : boolean wasPressed()
    {
        return debounce(LOW);
    }

    public : boolean wasReleased()
    {
        return debounce(HIGH);
    }

    public : boolean debounce(int state)
    {
        boolean gotEvent = false;

        int reading = digitalRead(_pino);

        if (reading != lastState) {
            lastDebounceTime = millis();
        }

        if ((millis() - lastDebounceTime) > DEBOUNCE_DELAY) {
            if (reading != buttonState) {
                buttonState = reading;

                if (buttonState == state) {
                    gotEvent = true;
                }
            }
        }

        lastState = reading;

        return gotEvent;
    }
};

PiscaPisca.cpp (the state-machine itself)
#include "Arduino.h"
#include "PwmPin.cpp"
#include "Beeper.cpp"

typedef enum {
    NONE        = 0,
    RIGHT_LIGHT = 1,
    LEFT_LIGHT  = 2,
    BOTH        = 3
};

class PiscaPisca
{
    PwmPin _left;
    PwmPin _right;

    Beeper _beeper;

    long _timeReference = 0;

    const int PERIOD = 350;

    boolean
        _running = false,
        _lightState = false;

    int _sides_to_turn = NONE;

    public : void configure(int leftPin, int rightPin, int buzzerPin)
    {
        _left.configure(leftPin);
        _right.configure(rightPin);
        _beeper.configure(buzzerPin);
    }

    public : void run()
    {
        evaluateBlink();
    }

    public : void toggleLeft()
    {
        checkRestart(LEFT_LIGHT);
    }

    public : void toggleRight()
    {
        checkRestart(RIGHT_LIGHT);
    }

    void checkRestart(int lightSide)
    {
        _timeReference = 0;

        // some clever bit-twiddling can never hurt too much:
        _sides_to_turn = lightSide & ~_sides_to_turn;

        Serial.println(lightSide);
        Serial.println(_sides_to_turn);

        if (_sides_to_turn > 0)
        {
            _running = true;
        }
        else
        {
            lightsOff();
            _running = false;
            _lightState = false;
        }
    }

    void evaluateBlink()
    {
        if (!_running)
        {
            return;
        }
        else
        {
            long currentMillis = millis();
            if (currentMillis - _timeReference > PERIOD) {
                _timeReference = currentMillis;
                _lightState = !_lightState;
                performBlink();
            }
        }
    }

    void performBlink()
    {
        if (_lightState)
        {
            _beeper.beepIn();
            lightsOn();
        }
        else
        {
            _beeper.beepOut();
            lightsOff();
        }
    }

    void lightsOn()
    {
        if (isLightSet(LEFT_LIGHT))
        {
            _left.on();
        }
        if (isLightSet(RIGHT_LIGHT))
        {
            _right.on();
        }
    }

    boolean isLightSet(int lightSide)
    {
        return (_sides_to_turn & lightSide) == lightSide;
    }

    void lightsOff()
    {
        _left.off();
        _right.off();
    }

};

Where is your state machine?

@IgnacioVazquez-Abrams I'm posting it, see my edit.

Interesting question, and tricky to get perfect. :)
I wrote a switch manager class a while back. It's just a .h file which you can put in your libraries folder (or add to your sketch).
SwitchManager.h
#include <Arduino.h>

class SwitchManager
  {
  enum { debounceTime = 10, noSwitch = -1 };
  typedef void (*handlerFunction) (const byte newState,
                                   const unsigned long interval,
                                   const byte whichSwitch);

  int pinNumber_;
  handlerFunction f_;
  byte oldSwitchState_;
  unsigned long switchStateChangeTime_;  // when the switch last changed state
  unsigned long lastLowTime_;
  unsigned long lastHighTime_;

  public:

     // constructor
     SwitchManager ()
       {
       pinNumber_ = noSwitch;
       f_ = NULL;
       oldSwitchState_  = HIGH;
       switchStateChangeTime_ = 0;
       lastLowTime_  = 0;
       lastHighTime_ = 0;
       }  // end of constructor

     void begin (const int pinNumber, handlerFunction f)
       {
       pinNumber_ = pinNumber;
       f_ = f;
       if (pinNumber_ != noSwitch)
         pinMode (pinNumber_, INPUT_PULLUP);
       }  // end of begin()

     void check ()
       {
       // we need a valid pin number and a valid function to call
       if (pinNumber_ == noSwitch || f_ == NULL)
         return;

        // see if switch is open or closed
        byte switchState = digitalRead (pinNumber_);

        // has it changed since last time?
        if (switchState != oldSwitchState_)
          {
          // debounce
          if (millis () - switchStateChangeTime_ >= debounceTime)
             {
             switchStateChangeTime_ = millis ();  // when we closed the switch
             oldSwitchState_ =  switchState;  // remember for next time
             if (switchState == LOW)
               {
               lastLowTime_ = switchStateChangeTime_;
               f_ (LOW, lastLowTime_ -  lastHighTime_, pinNumber_);
               }
             else
               {
               lastHighTime_ = switchStateChangeTime_;
               f_ (HIGH, lastHighTime_ - lastLowTime_, pinNumber_);
               }

             }  // end if debounce time up
          }  // end of state change
       }  // end of check()

     unsigned long getLastStateChangeTime () const { return switchStateChangeTime_; }
     unsigned long getLastStateLowTime ()    const { return lastLowTime_; }
     unsigned long getLastStateHighTime ()   const { return lastHighTime_; }

  };  // class SwitchManager

More details here.
Put that into a folder called SwitchManager, put that into your sketch folder -> libraries folder and restart the IDE.
That basically handles:

debouncing
detecting state changes (eg. now on, was off)

Using that we can now write a sketch that does the indicators:
#include <SwitchManager.h>

typedef enum {
    NONE,
    LH_DOWN,
    RH_DOWN,
    LH_LIGHT_ON,
    RH_LIGHT_ON,
    BOTH
};

const unsigned long BLINK_INTERVAL = 500; // ms

// pin assignments
const byte LH_SWITCH_PIN = 2;
const byte RH_SWITCH_PIN = 3;
const byte LH_LIGHT = A4;
const byte RH_LIGHT = A5;

SwitchManager LHswitch;
SwitchManager RHswitch;

byte state = NONE;

void handleLHPress (const byte newState, const unsigned long interval, const byte whichPin)
  {
  // switch down?
  if (newState == LOW)
     {
     switch (state)
       {
       // if other switch down, switch to warning mode
       case RH_DOWN:
         state = BOTH;
         break;

       // if already on or warning signal, turn all off
       case LH_LIGHT_ON:
       case BOTH:
         state = NONE;
         break;

       // otherwise switch is now down, but not yet released
       default:
         state = LH_DOWN;
         break;
       }  // end of switch
     return;
     }  // end of LH switch down

  // switch must be up

  if (state == LH_DOWN)  // if down, switch to down-and-released mode
    state = LH_LIGHT_ON;
  }  // end of handleLHPress

void handleRHPress (const byte newState, const unsigned long interval, const byte whichPin)
  {
  // switch down?
  if (newState == LOW)
     {
     switch (state)
       {
       // if other switch down, switch to warning mode
       case LH_DOWN:
         state = BOTH;
         break;

       // if already on or warning signal, turn all off
       case RH_LIGHT_ON:
       case BOTH:
         state = NONE;
         break;

       // otherwise switch is now down, but not yet released
       default:
         state = RH_DOWN;
         break;
       }  // end of switch
     return;
     }  // end of RH switch down

  // switch must be up

  if (state == RH_DOWN)  // if down, switch to down-and-released mode
    state = RH_LIGHT_ON;
  }  // end of handleRHPress

void setup ()
  {
  LHswitch.begin (LH_SWITCH_PIN, handleLHPress);
  RHswitch.begin (RH_SWITCH_PIN, handleRHPress);
  pinMode (LH_LIGHT, OUTPUT);
  pinMode (RH_LIGHT, OUTPUT);
  }  // end of setup

unsigned long lastBlink;
bool onCycle;

void blinkLights ()
  {
  lastBlink = millis ();
  onCycle = !onCycle;

  // default to off
  digitalWrite (LH_LIGHT, LOW);
  digitalWrite (RH_LIGHT, LOW);

  // every second time, turn them all off
  if (!onCycle)
    return;

  // blink light
  switch (state)
    {
    case NONE:
      break;

    case LH_DOWN:
    case LH_LIGHT_ON:
      digitalWrite (LH_LIGHT, HIGH);
      break;

    case RH_DOWN:
    case RH_LIGHT_ON:
      digitalWrite (RH_LIGHT, HIGH);
      break;

    case BOTH:
      digitalWrite (LH_LIGHT, HIGH);
      digitalWrite (RH_LIGHT, HIGH);
      break;

    }  // end of switch on state

  }  // end of blinkLights

void loop ()
  {
  LHswitch.check ();  // check for presses
  RHswitch.check ();  // check for presses

  if (millis () - lastBlink >= BLINK_INTERVAL)
    blinkLights ();

  // other stuff
  }  // end of loop

The state machine has a number of states:

NONE  -> all lights off
LH_DOWN  -> LH switch depressed, not yet released
RH_DOWN  -> RH switch depressed, not yet released
LH_LIGHT_ON  -> LH switch depressed, and released
RH_LIGHT_ON  -> RH switch depressed, and released
BOTH  -> Warning lights mode (flash both lights)

If we get a LH down while the RH is still pressed, or vice-versa, we switch to warning mode.
On a button release we switch from "switch down" to "switch released".
A second press, while either or both lights are on cancels them.
Note that my switches were wired to ground with the internal pull-up, so they are LOW when pressed and HIGH when not pressed.

Amazing! Well this is a lot of stuff to digest, and as you said it's a bit hard to fully understand, but surely I'm gonna test it tonight and bring some feedback. Thank you very much for now!!


text:
Arduino Mini Pro 3.3 V Issue with Bluetooth Mate
I have an Arduino Mini Pro 3.3 V powered from a coin cell(3.6 V, CR2450) and connected to Bluetooth Mate Gold. I have checked the connections and they are fine. I can also connect to the bluetooth from while trying to upload the file and also from Android bluetooth terminal.I am not sure if it could be bootloader issue as I have checked 2 Arduino Mini Pros that give the same problem running the sample sketch on the bluetooth hookup guide.

Arduino: 1.6.5 (Mac OS X)
Board: "Arduino Pro or Pro Mini, ATmega328 (3.3V, 8 MHz)"

The error is:
Sketch uses 2,412 bytes (7%) of program storage space. Maximum is 30,720 bytes.
Global variables use 210 bytes (10%) of dynamic memory, leaving 1,838 bytes for local variables. Maximum is 2,048 bytes.
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00

I burned the bootloader again but no success.
I get the same with UNO. However with UNO, when I press the reboot button before the program uploads is works.
Could someone point me out to the solution to this? Thanks

How did you connect the arduino reset pin to the BT-module?

@Gerben I used this hookup guide. For Pro-Mini the pins just match. Isn't it?

That guide doesn't connect the reset. So you have to manually reset the arduino just before programming.

source: Stack Exchange

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

sort: votes


text:
How do you send data via I2C without the wire library?
I have the following digital potentiometer: DS1803-100 which, according to the datasheet, can be controlled using a two-wire serial interface. I have managed to get it working using Wire, however I can't seem to get it working using only digitalWrite (link to code). Can somebody tell me why? For reference, 0x50 is the address + r/!w bit, 0xA9 is the command (write to pot 0 in my case) and the next 0xA9 is the value to write. I know there's something wrong with the code, however I cannot figure out what. Thank you in advance!
EDIT: Here is the code
int PIN_SCK = 12;
int PIN_SDA = 11;

const int delayvalue = 10;

void setup(){
    digitalWrite(PIN_SCK, 1); // I can first declare the state
    digitalWrite(PIN_SDA, 1);
    pinMode(PIN_SCK, OUTPUT); // then turn them on
    pinMode(PIN_SDA, OUTPUT);

    delay(1000);

    digitalWrite(PIN_SDA, 0); // start bit

    shift_out(PIN_SDA, PIN_SCK, 0x50);
    shift_out(PIN_SDA, PIN_SCK, 0xA9);
    shift_out(PIN_SDA, PIN_SCK, 0xA9);

    digitalWrite(PIN_SDA, 1); // stop bit

}

void loop(){

}
// uint8_t is the same as 8 bits aka one byte
void shift_out(uint8_t datapin, uint8_t clockpin, uint8_t val){
    uint8_t i;

    for (i = 0; i < 8; i++)  {
        digitalWrite(datapin, !!(val & (1 << (7 - i))));
        delay(1);
        digitalWrite(clockpin, 0);
        delay(delayvalue);
        digitalWrite(clockpin, 1);
        delay(delayvalue);
    }

    digitalWrite(datapin, 0); // to enable stop bit
    delay(100); // wait fro aknowledgement

}

What code would that be? Feel free to post the code here.

All right, edited the code in.

Well, short answer: It was the acknowledge bit, I forgot to send a clock pulse in order to receive it (duh! my device generates the clock for the attached potentiometer, I was waiting for the device to "send" me a bit, I needed to "request" the bit on a rising edge of the clock).
Long answer: the code looks like this now:
int PIN_SCK = 12;
int PIN_SDA = 11;

const int delayvalue = 10;

void setup(){
    digitalWrite(PIN_SCK, 1); // I can first declare the state
    digitalWrite(PIN_SDA, 1);
    pinMode(PIN_SCK, OUTPUT); // then turn them on
    pinMode(PIN_SDA, OUTPUT);

    delay(1000);

    digitalWrite(PIN_SDA, 0); // start bit
    delay(10);
    digitalWrite(PIN_SCK, 0);
    delay(10);

    shift_out(PIN_SDA, PIN_SCK, 0x50);
    shift_out(PIN_SDA, PIN_SCK, 0xA9);
    shift_out(PIN_SDA, PIN_SCK, 0xA9);

    digitalWrite(PIN_SDA, 1); // stop bit

}

void loop(){

}
// uint8_t is the same as 8 bits aka one byte
void shift_out(uint8_t datapin, uint8_t clockpin, uint8_t val){
    uint8_t i;

    for (i = 0; i < 8; i++)  {
        digitalWrite(datapin, !!(val & (1 << (7 - i))));
        delay(1);
        digitalWrite(clockpin, 1);
        delay(delayvalue);
        digitalWrite(clockpin, 0);
        delay(delayvalue);
    }

    digitalWrite(datapin, 0); // to enable stop bit
    delay(10);

    // Here I handle the AKNOWLEDGE signal which happens after
    // each byte sent. Be it address, command or value
    digitalWrite(clockpin, 1);
    delay(10);
    digitalWrite(clockpin, 0);
    delay(10);

}

So basically I followed and reproduced the signals in this timing diagram faithfully with one small exception: I did not generate a rising edge when I expected the acknowledge bit (basically the diagram but with SCK being 0 right below the acknowledge bits).
Hope this helps somebody!

I2C is a lot more complex than just shifting bytes out.
See: I2C - Two-Wire Peripheral Interface - for Arduino
Your code does not seem to take any of that into account.
Why do you not want to use the Wire library? The hardware on the chip (what chip do you have?) supports it. Why ignore that and try to do it yourself?

I have no problem using the wire library, however I was wondering why that code didn't work in the first place, since in my mind it should have worked. And yeah, I already ended up using Wire on my Arduino Pro Mini. Thanks for the info! :)

I am really curious on what I did wrong in my code. Did I not take into account the acknowledge bit, I just waited 100 ms for the slave to send this bit and than carried on, or what did I do?

Well I managed to make it work, I'll post the answer a bit later.

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


text:
Is there an equivalent to Grbl for Excellon PCB drilling?
For CNC milling we have code such as Grbl Controller in the PC, and Grbl itself in an Arduino, and these handle the appropriate G-code files. Is there an equivalent package to handle Excellon files and drive a 3-axis drilling machine?

Most PCB software will export to Gerber-files. There is already software that does pcb milling, including hole-drilling. I'm not into this stuff, but a google search for "gerber cnc" might give you better results.

Thanks Gerben. I will look into the pcb milling packages. If there is one that will talk to Grbl and if it has a sub-menu that will handle a drill file as a separate operation, then that could be the easiest way to go.

No, there is no existing Arduino library to parse Excellon format drill files in order to control a drilling machine. Looking at the specification it looks to be very similar to G Code, and some brief googling shows that there are various utilities for converting it to G Code that could be run from something like grbl.

Thanks Jake. See my comment to Gerben. If there isn't a direct pcb package, then yes, I guess I'll have to do an Excellon --> Gcode then through say, Grbl Controller --> Grbl.


text:
Cannot pass objects of non-trivially-copyable type 'class String' through '...'
I'm attempting to send data from a serial connection to a GSM modem, but having problems.
The string from rx looks like this:
1.0 2.0 3.0 4.0

Here's my code to replace the spaces and then I just want to pass the whole string on, regardless of what's inside (there could be negative values too).
                data_current[data_index++] = ',';
                char received = bike_port.read(); //bike
                char test[32];
                inData += received;
                  if (received == '\n')
                  {
                      String nospace = inData;
                      nospace.replace("\t",",");
                      debug_println("Data: ");
                      debug_println(nospace);
                      inData = ""; // Clear recieved buffer
                      delay(1000);
                  }
                  sprintf(test,32,"%d,%d,%d,%d",(String) nospace);
                //strtok(received, tmp);
                for (int i=0; i<strlen(test); i++) {
                  data_current[data_index++] = test[i];
                }

I have also tried
sprintf(test,32,"%ld,(String) nospace);

What I get now is this error
cannot pass objects of non-trivially-copyable type 'class String' through '...'

Without the sprintf line I can successfully echo the string to debug_println (Serial Monitor).
What am I doing wrong?

Your sprintf() line doesn't seem to make sense. What are you trying to get it to do?

I basically just need 'nospace' to be added to data_current. Maybe I should try
    for (int i=0; i<strlen(nospace); i++) {
              data_current[data_index++] = nospace[i];

The basic problem here is that you're trying to pass a String object to sprintf(). That isn't possible because String is a C++ class, and sprintf() is a C variadic function. The only way to pass a string to it is as a char *.
The rest of your call to sprintf() doesn't seem to make sense either, although I suspect it's not what you actually want here. You'd normally use sprintf() if you want to format several values into a string.
As you've suggested in the comments, adding the contents of nospace to data_current character-at-a-time would be the sensible approach. You could do it something like this:
for (int i = 0; i < nospace.length(); ++i) {
    data_current[data_index++] = nospace[i];
}

Note that strlen() won't work on nospace because it's a String object not a char array.
This is all assuming that there's enough space in data_current though. Without seeing the rest of your code, I can't tell you if it will definitely work or not.

Update:
As an alternative, you could use memcpy() to do a block transfer:
memcpy(data_current + data_index, nospace.c_str(), nospace.length());
data_index += nospace.length();

I'm not sure there's much benefit to doing that though. It's hypothetically more efficient, but it probably won't make a noticeable difference unless your string is moderately long and it's being called very frequently. (It's trading-off the loop overhead against a function-call overhead.)

There should be enough space, if not, I know where to change it. But is there a way to add the whole content of nospace, not a character at a time? Because it then gets sent through GSM. I don't know what the exact character length will be, but I do know the maximum.

@Fid You could use memcpy() in theory, although I don't know how much difference it will really make. I've updated my answer with details anyway.

"But is there a way to add the whole content of nospace, not a character at a time?" Yes and no: Yes, you can express it that way in C++; adding strings translates into concatenation. No, because for most processors, and for AVR's in particular, it ultimately involves a character by character copy. In other words, write it however it reads best to you. It won't make much difference at run time.

Let me get this straight. You want to change:
1.0 2.0 3.0 4.0

to:
1.0,2.0,3.0,4.0

Right?
How about:
  char indata[32] = "1.0 2.0 3.0 4.0";

  int len = strlen (indata);
  for (int i = 0; i < len; i++)
    if (isspace (indata [i]))
      indata [i] = ',';

  Serial.println (indata);   // prints: 1.0,2.0,3.0,4.0

Only problem is that when I change "1.0 2.0 3.0 4.0" to the actual incoming read (bike_port.read()), than I get error ...

In that case, as Jake C said, modify the incoming byte like this:
 char received = bike_port.read(); //bike
 if (isspace (received))
   received = ',';

This works wonderfully. Only problem is that when I change "1.0 2.0 3.0 4.0" to the actual incoming read (bike_port.read()), than I get error "array must be initialized with a brace-enclosed initializer".

As a companion to Nick Gammon's excellent answer, here is a streaming version of that (assuming this is coming in one serial port and out another to the modem).
if (Serial.available()) {
  int inByte = Serial.read();
  if (inByte == ' ')
    Serial1.write(',');
  else
    Serial1.write(inByte);
}


text:
Can I Implement a PLL on an Arduino?
Is it possible to create a system like a PLL using an Arduino?
I ask this because there are some parts in the PLL system, such as: phase detector, VCO, divider, and I don't know how to make for each part in Arduino board.

The ATTinys have a build in PLL.

thanks gerben, so if i use aduino uno all i have to do to make a PLL is just to coding it right??

An Uno does not use an ATtiny, so no.  You may be able to build a frequency locked loop in software, but right now the major problem with your question is that you don't specify the details of your goal

Uno uses an ATMega328. You can e.g. use a bare ATTiny85 chip, or a board based on that same chip, like a Trinket, or Digispark. (There are other ATTinys beside the 85, but that one is the most popular).

thanks again greben, i forget that one point, this is for my final project my goal is to create a signal (pll output) from the reference signal that come from function generator.
my lecturer said the reference signal i have to give is following the working frekuency and amplitude of arduino uno. so it's doesn't need special req. right?

A PLL is a very complex device which is not something that can easily be created purely in code.
Many microcontrollers include a PLL as part of their oscillator systemm which allows them to run internally at a higher speed than their external crystal.  This is not a programmable peripheral that you can use for your own things, but an integral part of the workings of the microcontroller.
While it may be possible to write one in software the results would be very somewhat limited. The best you could hope for is to use timers to measure an incoming frequency and use the results to output another frequency through some means, maybe PWM.
To create a real PLL you would be best off using either a dedicated PLL chip (which you can buy off the shelf) or use some form of programmable logic like a CPLD that has a built in PLL block.
Some microcontrollers, most notably the Cypress PSoC range, have programmable logic blocks built in that may be more suited to your task than an Arduino.
A typical digital PLL looks something like this:

Implementing all that in code would be both tricky and somewhat slow on a little 8-bit MCU with no floating point support.  However, the basic principal of what a PLL can be summarised in one simple sentence:

The frequency coming in determines the frequency going out.

The PLL, or Phase Locked Loop is just one method of achieving that desired result.
Another method, which is not using any form of PLL, is purely algorithmic and consists of just three things:

Three simple blocks, all of which the Arduino is, to a certain extent, capable of performing.
The first block, the Frequency Detector, works out what the frequency of the incoming signal is.  That could either be by counting the number of pulses that arrive over a certain time frame, or measuring the time between successive pulses.  Which method you use (Frequency Counting or Frequency Measuring) is really down to what frequency ranges you are using.  Frequency Counting is better for higher frequencies, whereas Frequency Measuring is better for low frequencies.  There are many examples on the web of how to do both of those using timers on the Arduino.
The Decision Making is basically working out what your output frequency wants to be according to your input frequency.  This could be as simple as "Output = input * 2", for instance, or something more complex like "Between these frequencies I want to output this frequency, between these frequencies this other frequency, etc".  It's entirely up to you.
The third block just takes the decided-upon output frequency and generates it.  That could be done using the hardware PWM generation of the Arduino.
All this, though, will be limited to relatively low frequencies (tens of kHz maximum really) though with clever coding you could push it up slightly higher.
One thing that really makes this method differ from a PLL is that you don't get the "PL" portion of it - that is, the phase of the incoming frequency is lost, and the output frequency is running entirely with its own phase.  There is little or nothing you can do to synchronise the phases of the input and output like you get with a full PLL.

thanks majenko, sadly i already propose this title for my final project so i have to build this system using arduino. and i think what i aiming is that complex. do you have any idea?

thanks @majenko, i'll consider it by using arduino due just like jack said.
and i'll be concern about the output that arduino gives..

Addendum: Use an output oscillator with reset function. Detect the "reset point" of the input waveform. (The Arduino supports interrupts, for example)

thanks for that @MickLH.. i've already considered by using arduino, despite it might be expensive but i has already propose it..

For countable frequencies, you can easily get the PL phase information by using sort of a Bresenham algorithm counter, incrementing by a quantity for each output pulse, and decrementing by a quantity for each input pulse. (eg, for a 100Hz output from a 1PPS,  bresenham++ each output pulse, and on each PPS bresenham-=100; and adjust the output interval.  When they are in phase, the count is stable.    If they are out of phase, the Bresenham count would tell you which way and by how far, and you could use that phase information for decision making.

There are two types of PLLs, hardware PLLs and software PLLs. Majenko has already addressed hardware PLLs so I will leave you to his answer for that.
Software PLLs perform the same function as regular hardware PLLs, but with code, and as a result are constrained by the clock speed and sample rate of the controller they are running on. Usually this means you are limited to sub MHz frequencies. The math and computation necessary to perform this is quite complicated, and I do not expect you would get particularly good performance out of your standard Arduino controller, as all of them lack a floating point unit to perform these types of computations.
If you were to still try and attempt this you would have to do it using integer math only. The faster the CPU, the higher the frequency it will be able to lock on to. The fastest Arduino available today is the Arduino Due. Aside from being fast, the Due can perform 32-bit arithmetic in a single cycle, which should be handy. The frequency limit will be dictated by how many cycles all of your calculations take.

thanks jake, that's all i need.
i only need a low frequencies in range of KHz, and the amplitudes is follow the maximum input voltage of arduino right?
and which arduino can you suggest?

I've added to my answer a few extra notes on attempting this. All I can say is: Good Luck! Software PLLs are tricky; there are a lot of resources out there about how to do it theoretically, but very few on real world implementations of them.

thanks a lot jake, well i have a lot of work right.. maybe i'll ask you more about it while i'm working on it could i?

You can absolutely make a PLL using an ATMega microcontroller, and I have made one myself using a ATTiny45. The way I did it is by setting the clock source to the internal RC oscillator, and using that as my VCO (or in this case, Numerically Controlled Oscillator). The internal oscillator can be tuned between 50% and 200% of its nominal frequency by adjusting the OSCCAL register, which can safely be done without stopping the processor. I used the ADC to read the input signal. For the phase detector I programmed the MCU to alternatively add, then subtract the ADC registers from an accumulator register. This is mathematically equivalent to multiplying the incoming signal by a square wave from the local oscillator, and integrating the result. After a fixed number of cycles, I checked to see if the accumulator was negative or positive. If its negative, I set OSCCAL to a "high frequency" which is definitely higher than the input signal. If its positive, I set it to a "low frequency", which is definitely too low. Of course this is a form of Bang–bang control, so its never stable per se, but I found works perfectly. Its much better than my attempts at a PID controller. Looking on my oscilloscope, the is almost no jitter visible between the input system and the internal RC clock, which I outputted on the CLKO pin by setting the appropriate fuse bits.
Although I used GCC and USBTinyISP, I see no reason why my system can't be implemented on Arduino. Setting the fuse bits will require a bit of work though, you can read more here:
http://forum.arduino.cc/index.php?topic=124879.0
If there is enough interest, I can add more detailed information to my answer.

Thanks for your answer @Misha and ya, i'm little bit interest with your detail. And first at all to implement pll using arduino, how can i used adc to read the input signal if it come from function generator for example?


text:
avrdude : stk500_get sync<> attempt 10 of 10 not in sync : resp=0x20 how do i get pass this error for ardunio uno board
When I first started with a bare minimum code. The compiler compiles the code, but when I try to upload, this is the error message I get:
 AVRDUDE: STK500_GETSYNC<> ATTEMPT 10 OF 10 NOT IN SYNC :RESP=0X20

How do I fix this?

Search for: attempt 10 of 10 not in sync, in the search box on this page. This question is asked frequently.

See my lengthy post about Have I bricked my Arduino Uno?.
Also the popular question Some dude named avr won't let me upload my program, aka “avrdude: stk500_getsync(): not in sync: resp=0x00”.

There are multiple reasons why you are getting this error.

Bootloader is either missing or corrupted. This is fairly unlikely.
Wire connected to pin 0 (RX)
Wrong COM port is chosen within the arduino IDE.
Drivers are not installed. You can update it within the Device Manager if you are using Windows.

Here is a link to an article explaining the causes and how to fix them, http://www.instructables.com/id/A-solution-to-avrdude-stk500getsync-not-in-syn/


text:
WizNet chip on Ethernet Shield oddly hot
I'm making a thermometer and, so I can graph the data, I have an Uno with the WizNet shield sending the data to a LAN ip. The chip itself is oddly hot, its temperature measures at around 110-120ºF (43.33-48.89ºC). I want the program to be running almost 24/7. Is it okay for the chip to be this hot?

According to the WizNet forums this is normal for these shields. Their justification being that it is a PHY and controller on a single chip. (Note this post only specifically mentions the W5100, which is among the more commonly used chips on these kinds of shields, however, I suspect that this is typical for most of the WizNet line, e.g. W5200 etc.)


text:
Arduino web server: redirect to mobile site on SD card?
Is there any way to have an Arduino web server redirect the client to a file on the SD card only if the client is using a mobile browser?
(My arduino server is already successfully serving pages on http://192.168.0.180, and successfully processes GET requests).
I was thinking of having this javascript code on the main page that's served by the arduino:
<script type="text/javascript">
  <!--
  if (screen.width <= 800) {
    window.location = "http://192.168.0.180?mobile";
  }
  //-->
</script>

My first thought was that maybe it's possible for the server to process that GET request and then serve a page from the SD card, instead of the regular page it serves.
Do you think this is possible, and how would you recommend to do it?

Yes, it is perfectly possible. you just have to look at the right bits.
Fundamentally there is no difference between an Arduino and any other website, it's just somewhat simpler in how it operates.
All browsers follow the same rules - if they didn't they wouldn't work on the web.  Two of the rules you are interested in are:

Browsers identify themselves along with their OS.
Browsers respond to the "result" code the website provides in a specific way.

Besides the GET request a browser also sends a list of headers.  These contain lots of extra information about the request, including the domain name of the website that is being accessed (so the web server knows which site you want - it's not one webserver per site, that would be impractical.  For instance, the request to show this page from Firefox on Linux has these headers:
Host: arduino.stackexchange.com
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0 Iceweasel/31.6.0
Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
Accept-Language: en-gb,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: (I won't bore you with this lot)
Connection: keep-alive

The header of note is the User-Agent: one.  That tells the web server that I am using firefox from a 64-bit Intel Linux computer.  If I were to do it from my Android phone it would tell you it's from Chrome on Android.
By looking for that header and parsing it for certain keywords you can find if you're serving to a mobile device or not.
Now the second bullet above - browsers respond to the response code in different ways.  Normally you send the response code 200 which means "I accepted your request and here is the page you asked for".  Another response code that is useful is code 301 which means "The page you asked for isn't at this address any more - here is the new address you should go to instead".  That will then cause the browser to go to the newly provided address instead.
So instead of responding with
HTTP/1.0 200 OK
Content-type: text/html

<web page content here>

You could instead respond with:
HTTP/1.0 301 Moved Permanently
Location: http://myarduino.local/mobile

And the browser will redirect to the new address you give in the Location: response header.
The full list of response codes is here: https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
If you want to avoid the overhead of a browser redirect you can just serve different data to the browser depending on what the User-Agent header specifies.  After all, it's entirely down to you what is sent as the content of the page.  Whether you get that from purely programmatical means, or by reading a file off an SD card, is entirely up to you.

Does it make sense that serving a file from the SD card will be noticeably slower than just using "client.println" statements to serve the page? This is the code I'm using to read the file from the card (using the SDfat library, which is supposed to be faster than the main SD library): char c;     while ((c = mobileFile.read()) >= 0) {     client.write(c); }
edit: sorry I couldn't figure out how to properly format the code in the comments section.

It depends how big the file is. If it's a large file, like an image or lots of static text, then a file on the SD makes sense.  If it's just a few bytes then there's no point in using the SD.

Thanks! I ended up moving both files from the SD card onto the main program, because it ended up to be noticeably faster. It's big and clunky, but at least it does what I need it to do. :)


text:
How to input keyboard commands using Arduino Mega 2560?
I have an Arduino Mega 2560 connected to a Windows 8 laptop. I want to program it to send keystrokes to the attached computer (when a pin's digital read goes from HIGH to LOW.)
The trouble is, I cannot find any way to program my Arduino Mega to send keystrokes.
The supposedly "core" Keyboard and Mouse libraries only support 32u4 boards, and other libraries that give the Arduino keystroke functionality are out of sight. When I googled the issue, I found no question or explanation of how to send keystrokes on the Arduino Mega. When I searched further, I thought the V-USB library would be a potential workaround, but the library throws numerous errors when imported into an Arduino sketch (even on the 1.0.0 IDE it was designed for.)
After hours of searching, two final workarounds seem to have popped up:

Some method to run a Python code to send keystrokes to the PC, and then connect the Arduino code to Python. (I don't know Python...)
Use some program called Gobetwino, which runs between the Arduino and PC, to   convert Serial commands into keystrokes somehow. (Pressing and releasing a key can't be simulated very well by repeatedly sending Serial commands, I think.)

Both are very unideal, very tedious, and are equally likely to just not work. I have spent hours on this.
Does anyone have any suggestions to get me out of this hell? Libraries, workarounds, anything?
(Feel free to PM me questions for clarification.)

Both the Mega 2560 and the Uno R3 have the same second MCU, so I'm marking this one as a duplicate.

The V-USB library is the only practical way. You need a couple of resistors and zener diodes. I suggest you post the exact V-USB library you are attempting to use, and the exact error messages.

However reflashing the USB interface chip is not really an ideal solution.

Scrap the Mega2560 and use a Leonardo.

Why do you want to send keystrokes? What do you want to achieve? Wouldn't it be easier to just signal the pin change via different means?

You are right, the mega can't do what you want unless something in the middle catches the serial/IO and translates to a keystroke command.
Another option, more expensive, is to buy an Arduino Leonardo which is also available as a small usb stick type of device. Then use serial/analog or ano from the mega to the Leonardo.
The Leonardo boards can emulate any usb device such as keyboard, mouse, joystick etc.
Maybe not of interested but also look at Teensy 3.1. It can do what the Leonardo does but is 32 bit and very flexible. The only benefit of the mega is the massive number of pins. Teensy costs about $20.
It all depends on what your project requires.

Untrue.  The Mega2560 hardware is capable of both USB HID (see comments) and PS/2 keyboard interfaces.

Not sure if that is true. It is the ATmega8U2 usb on the same board as the mega that could do this but requires some difficult non-arduino re-programming? The Leonardo is programmed via the sketch as normal so it's a simple solution designed for this purpose. Please correct me if I am wrong about this?


text:
Adjust time calculation after Timer0 frequency change
I have an Arduino Nano with an 328P and need all 6 PWM pins.
Thus, I had to adjust the prescaler and WGM Mode of Timer0.
It is now in phase correct PWM mode with a prescaler of 1.
TCCR0A = _BV(COM0A1) | _BV(COM0B1) | _BV(WGM00);
TCCR0B = _BV(CS00);

Now I need a working time calculation for other libraries, but since
Timer0 had that duty everything is out of order now.
I tried adjusting the wiring.c
// the prescaler is set so that timer0 ticks every 64 clock cycles, and the
// the overflow handler is called every 256 ticks.
#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(64 * 256))

to this
#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(1 * 510))

But it's like I didn't change anything.
(tested other settings that were changed so it was compiled anew )
Whole Code:
void setup() {

  // Set Timer 0, 1 and 2
  // Register A: Output A and B to non-inverted PWM and PWM mode to phase correct.
  // Register B: Pre Scaler to 1.
  TCCR0A = _BV(COM0A1) | _BV(COM0B1) | _BV(WGM00);
  TCCR0B = _BV(CS00);

  TCCR1A = _BV(COM1A1) | _BV(COM1B1) | _BV(WGM10);
  TCCR1B = _BV(CS10);

  TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM20);
  TCCR2B = _BV(CS20);

  pinMode(8, OUTPUT);

}
void loop() {

  digitalWrite(8, LOW);
  delay(65000);
  digitalWrite(8, HIGH);
  delay(65000);

}

All of your settings are correct. My best guess if you maybe modified the wrong wiring.c. The best way to diagnose this is to go to File > Preferences and check the compilation checkbox under "Show verbose output during". Then click verify, copy the output into a text editor and search for wiring.c and see where it is pulling it from, then open the file and verify that your changes are there.

When I clean the tmp folder and verify anew he shows:
This.
And that is also the wiring.c I corrected :(

I don't know what to say, by all means that should work. Another option would be to just scale the times yourself. You could wrap this in a macro a la #define SCALE_UP(x) x<<6 and then use it like such delay(SCALE_UP(1000))

That is the weird thing, the real value seems to be really arbitrary.
I tried two nanos and one Uno, both have the same results.
And when I try to calculate the the value for delay I get 64000, but when I
insert that it's only like 800ms instead of 1000ms. For testing purpose I already threw out all #includes it's just the Register change and digitalWrite and delay now.

How are you measuring? Do you have an oscilloscope by chance?

No I don't have one.
I have an LED that blinks with the code above and now I added
a Serial output to the arduino IDE. When I put the delay at 200000 I get approx. 1050ms

Oh I just noticed... when I can use millis() to measure the, well, millis and they seem correct, then this implies that the internal timekeeping is alright.
Just delay seems to have a bug. sigh
Anyway. Thanks for helping Jake!

Ah, that makes sense due to how these functions are set up in wiring.c. Can you try something for me, try running delayMicroseconds(1000000); and let me know if that is more accurate.

Also, what version of Arduino are you using?

It seems that delayMicroseconds() has the bug aswell. it doesn't even cause a ms delay.

Strange, delayMicroseconds() uses a different mechanism than delay() so I was wondering if it might not be affected by this. I've posted an answer summarizing our findings.

It seems that delayMicroseconds() has the bug aswell. it doesn't even cause a ms delay. - Please post code that supports this assertion.

The code from above, just replace the delay(65000) with delayMicroseconds(). I put the value to 16000000L because I have a 16Mhz CPU. The LED just looks dim, but doesn't turn off and on every second. If I compare it with a simple millis() - startMillis the delay takes 5ms with 16000000L and 9ms with 128000000.

Fixing the timekeeping functions with your PWM settings is not so
simple. You should at least try to rewrite ISR(TIMER0_OVF_vect),
micros(), and probably delay(). Here is why:
First, there is a rounding problem. Time is kept using two global
variables:
volatile unsigned long timer0_millis;
static unsigned char timer0_fract;

The first one is what millis() returns. The second one keeps track of
how much time has passed since the last full millisecond, and it does so
in units of 8 µs. The two variables are incremented by
ISR(TIMER0_OVF_vect) like this:
m += MILLIS_INC;  // temporary copy of timer0_millis
f += FRACT_INC;   // temporary copy of timer0_fract

On a normal Uno configuration, the ISR is called every 1024 µs.
Then MILLIS_INC is 1 and FRACT_INC is 3. With your timer
configuration, the ISR is called every 31.875 µs (510 cycles), then
MILLIS_INC should be 0 and FRACT_INC should be 3.984375. But since
we are dealing with integers, it will be rounded down to 3, and your
millis() will tick about 25% too slow.
A simple fix would be to
#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(1 * 512))

in order for FRACT_INC to be 4 and millis() to be 0.4% too fast. Or
you could make timer0_fract a 16-bit variable and have it count clock
cycles, just to avoid this error. Either option should fix millis(),
but you still have a problem with micros().
micros() works by reading both timer0_overflow_count (incremented by
1 in the ISR) and the actual counter value. Since your counter is now
going alternatively up and down, it will be harder to compute a
microsecond count from these readings. Maybe you could take two
consecutive readings of the counter, just to know whether it is going up
or down...
And then there is delay(), which relies on micros(). If you fix
micros(), delay() should work fine. If not, You could rewrite
delay() to use millis() instead, which should be easy but you will
loose some accuracy.

Thanks for the sophisticated answer! At this point also thanks to @jakec for discussing the problem with me!

Since your counter is now going alternatively up and down Why is the TCNT0 going up or down? It's going up and every time it overflow the ISR is called. Am I missing something? I tried to solve this by increasing the timer0_overflow_count once every 64 times only, and on the micros() function return the time as return ((m << 8) + (t % 64)) * (64 / clockCyclesPerMicrosecond()); So I do a mod on the TCNT0 counter as my Timer is ticking 64 times faster. But although the micros() seem to be ok delay() is still running faster and I'm not understanding why...

@Lefteris: The counter is going up and down because the OP configured it in “phase correct PWM” mode.

Correction on the above, modulo was wrong, I'm dividing by 64 on the return function now: return ((m << 8) + (t/64) ) * (64 / clockCyclesPerMicrosecond()); Still the problem remains with delays function which I don't understand

@EdgarBonet If I have understood correct, the TCTN0 register increases every CLK/64 tick. So it is only going up. It is reset every time it overflows and TIMER0_OVF_vect ISR is called. So still not understanding what phase correct PWM has to do with this.

@Lefteris: Read the datasheet: “The Phase Correct PWM mode is based on dual-slope operation: The counter counts repeatedly from BOTTOM to TOP, and then from TOP to BOTTOM.”

@EdgarBonet Yes I've just read this. Thank you

You have set MICROSECONDS_PER_TIMER0_OVERFLOW to a proper value, however, this is only ever used by MILLIS_INC, which in turn is only ever used by millis(). This means that the other timing functions, such as micros(), delay(), delayMicroseconds() break when timer0 is changed. This is kind of a bug, and it may be fixed in a future version, but for now, the Arduino libraries are expecting you to leave timer0 alone. The best workaround is to only use millis() for your timing critical functions.

THIS IS AN INCOMPLETE ANSWER - Edgar knows what he's talking about, listen to him
I am currently working with this same thing but in an ATMega2560. This website helped me understand the millis() function better. The timer overflows every 510 counts (see datasheet, pg 123 for the atmega2560). I believe it is 510 and not 512 because it counts up and down, but does not repeat a count at the top or bottom - for example if you count starting from 1 up to 10 and then back down (without repeating 10) you will have counted 19 times, not 20. This counter starts at 0, counts to 255, and then back to 0, triggering an overflow before hitting 0 again. This is is 256 (count up including 0 and 255) + 254 (count down, not including 255 or 0) = 510.
I wrote a python script to visualize the effect of these changes and trying to account for them. This counts to 10 million, so it takes time to run, but by the end, even with scaling, the error if simply adjusting millis() after the fact could be ~7 seconds.
#! /usr/bin/env python
import numpy as np

realT = np.zeros(10000000)
timer0_millis = np.zeros(10000000)
timer0_fract = np.zeros(10000000)
i=0

for i in range (1,10000000):
    timer0_millis[i] = timer0_millis[i-1] + 1
    timer0_fract[i] = timer0_fract[i-1] + 3
    realT[i] = i*31875
    if timer0_fract[i-1] >= 125:
        timer0_fract[i] = timer0_fract[i-1] - 125
        timer0_millis[i] = timer0_millis[i-1] + 1

adjusted = timer0_millis*510/(256*64)

print "after 100 timer interrupts millis() will read %d, actual millis is %.6f, adjusted millis is %.6f" % (timer0_millis[99], realT[99]/1000000, adjusted[99])
print "after 1000 timer interrupts millis() will read %d, actual millis is %.6f, adjusted millis is %.6f" % (timer0_millis[999], realT[999]/1000000, adjusted[999])
print "after 10000 timer interrupts millis() will read %d, actual millis is %.6f, adjusted millis is %.6f" % (timer0_millis[9999], realT[9999]/1000000, adjusted[9999])
print "after 100000 timer interrupts millis() will read %d, actual millis is %.6f, adjusted millis is %.6f" % (timer0_millis[99999], realT[99999]/1000000, adjusted[99999])
print "after 1000000 timer interrupts millis() will read %d, actual millis is %.6f, adjusted millis is %.6f" % (timer0_millis[999999], realT[999999]/1000000, adjusted[999999])
print "after 10000000 timer interrupts millis() will read %d, actual millis is %.6f, adjusted millis is %.6f" % (timer0_millis[9999999], realT[9999999]/1000000, adjusted[9999999])

You wrote: “I believe in phase correct mode the timer overflows every 510 counts, not 512 as indicated by Edgar”. Please, read my answer again, and do not misquote me.

Sorry, I was refering to this line "#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(1 * 512))" - I have updated my comment, correct me if I am wrong here, I didn't intend to misquote

There is a very good reason for having 512 instead of 510 in this line. Read my answer and you will understand.

Okay, so you are adding two timer counts, each being 62.5ns, to account for the error caused by the forced round-down?

In my application I could not modify wiring.c, so as a quick fix I inserted a coefficient to scale relative values returned from millis(). With that said I was trying to model what my changes looked like compared to the proper fix - which I count this as. Also, does this error matter as much when millis() is used for relative timing, such as now=millis() and while(millis() - now < 100) (i.e. is it a constant error or does it vary; can it be used to scale the condition)?

Yes. With 510, rounding makes millis() 25% too slow, whereas 512 makes it 0.4% too fast. As for your second question, you may try to formulate it as a proper question, and show in code how exactly you “inserted a coefficient”.

If it is 25% too slow, could this account for the error: now=millis() and then while(millis() -now < x*100) with x=4/3? I'm sorry, this is my first time posting on this forum and I thought I had included some useful information, but I guess I should leave the answers up to the experts.

Edgar, if you would like to continue helping me I decided that instead of answering a question with questions of my own and potential misinformation I would ask a question

Thanks to Edgar's answer and Nebsie's explaination on how the counter exactly works I could come up with my own implementation of how to rectify delay and micros() that - so far - seems to work fine on my Arduino Uno.
I'm not saying that this is the most precise implementation, especially I have my doubts on micros() if for example an timer overflow occours between reading t1 and t2, but it is one that so far for me works well.
First thing - according to Edgar's recommendation I defined:
#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(1 * 512))

However this doesn't affect timing of micros() or delay().
Function micros() I changed to read two times from TCNT0 - to determine whether it is counting upwards or downwards. This is done with the "if (t1 > t2)" clause. The overflow count "m" is multiplied by 510, because the counter elapses after 510 steps. Then the calculated counter value "t" is added to this, divided by the number of clocks per Microsecond. (Note: Prescaler = 1, therefore no further multplication).
unsigned long micros() {
    unsigned long m;
    uint8_t oldSREG = SREG, t1, t2;
    uint16_t t;

    cli();
    m = timer0_overflow_count;
#if defined(TCNT0)
    t1 = TCNT0;
#elif defined(TCNT0L)
    t1 = TCNT0L;
#else
    #error TIMER 0 not defined
#endif

#if defined(TCNT0)
    t2 = TCNT0;
#elif defined(TCNT0L)
    t2 = TCNT0L;
#else
    #error TIMER 0 not defined
#endif

    if (t1 >= t2) {
        t = 510 - t2;       // counter running backwards
    } else {
        t = t2;             // counter running upwards
    }

#ifdef TIFR0
    if ((TIFR0 & _BV(TOV0)) && (t2 > 1))        // if overflow flag is set -> increase m
        m++;
#else
    if ((TIFR & _BV(TOV0)) && (t2 > 1))
        m++;
#endif

    SREG = oldSREG;

    return ((m * 510) + t)  / clockCyclesPerMicrosecond();
}

HOWEVER - this seems to work fine but I had issues to begin with (before editing this again). Due to the counter running much faster, every 268 seconds the unsigned long datatype of micros() overflows and starts from zero again. This led to an unwanted lockup of delay(), especially if long delay times, like in my case delays of one second per loop iterations are used. Therefore I also had to add an overflow detection to the delay() function in arduino wiring.c.
If the overflow occurs, timing might not be very precise. But since this is once overy 268 seconds it may be acceptable. So far with this change the delay function works fine again on my side.
void delay(unsigned long ms)
{
    uint32_t start = micros();
    uint32_t elapsed = 0;

    while (ms > 0) {
        yield();
        while ( ms > 0 && (micros() - 1000) >= (start + elapsed)) {
            ms--;
            elapsed += 1000;
        }
        if( start > micros() ) {    // overflow detected
            start = micros();       // reset start
            elapsed = 0;            // reset elapsed
        }
    }
}

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


text:
Can I use analogRead to read a digital pin?
analogRead(nGPIO_max + lockerVal) were nGPIO_max(maximum digital pins in Arduino Uno is 13) and lockerval is 2. Which pin is it reading?

13 + 2 = 15, so pin 15.  I'll give you a clue: A0 is pin 14.

To answer the question in the title: No, you cannot use analogRead() to read a digital pin. A digital pin cannot behave as analog because it isn't connected to the ADC (Analog to Digital Converter).
If you call something equating to analogRead(15) on an Uno, then it should read pin A1. You can see the pin assignments in the board-specific versions of pins_arduino.h (shipped with the IDE):
static const uint8_t A0 = 14;
static const uint8_t A1 = 15;
static const uint8_t A2 = 16;
static const uint8_t A3 = 17;
static const uint8_t A4 = 18;
static const uint8_t A5 = 19;
static const uint8_t A6 = 20;
static const uint8_t A7 = 21;

Using those raw numbers directly is generally not a good idea though as it obscures your code's meaning, and will potentially make it non-portable to other boards. It's better to call something like analogRead(A1).
It's worth noting that the Arduino library fudges the pin numbers slightly. Calling analogRead(1) has the same result as calling analogRead(A1). That means that even if you tried to use analogRead() on a digital pin, it might actually end up reading an analog pin instead. Alternatively, it might just return a meaningless result, depending on the pin number you give it.


text:
Arduino communication with ROS via UART
I am trying to program an Arduino Mega(Crius) from a Minnowboard Max A2 via an UART (Hardware Flow Control Off) interface.
I can successfully communicate with the ROS (robot Operating System) on the Ubuntu 12.04 installed on the Minnowboard Max via the UART1 port available on the Minnow Board.
The Crius UART has a FTDi compatible port with a DTR pin.
Unfortunately the MinnowBoard does not have any DTR pin to communicate with the Arduino (Only CTS/RTS pins for 1 of the 3 UART ports). Thus I cannot upload any sketch to the Arduino via the Minnowboard over the UART. I must always connect to the onboard FTDi-USB chip of the crius and upload the sketch.
Is there any workaround to upload the sketch to the Arduino via the UART from the Minnowboard ?

Have you tried the RTS pin? The FTDI header usually asserts RTS to reset the Arduino.

You can use any GPIO you like on the Minnow to trigger a reset of the Mega to initiate the bootloader.  The Yún does just that to program the on-board ATMega chip through a script they have chosen to call "run-avrdude":
#!/bin/sh

echo 1 > /sys/class/gpio/gpio21/value
avrdude  -q -q -c linuxgpio -C /etc/avrdude.conf -p m32u4 -U efuse:r:/tmp/efuse:d
read EFUSE < /tmp/efuse
rm -f /tmp/efuse
if [ "x$EFUSE" = "x203" ] # 203 = 0xCB
then
    avrdude -c linuxgpio -C /etc/avrdude.conf -p m32u4 -U lfuse:w:0xFF:m -U hfuse:w:0xD8:m -U efuse:w:0xCB:m -Uflash:w:$1:i $2
else
    avrdude -c linuxgpio -C /etc/avrdude.conf -p m32u4 -U lfuse:w:0xFF:m -U hfuse:w:0xD8:m -U efuse:w:0xFB:m -Uflash:w:$1:i $2
fi
echo 0 > /sys/class/gpio/gpio21/value

You could do something similar to initiate the bootloader on the remote board - connect any GPIO pin to the RESET line of your Mega board, then perform the following logical actions:

Set the GPIO to OUTPUT
Set the GPIO to LOW
Delay a few ms
Set the GPIO to INPUT
Run avrdude.

By setting the GPIO to INPUT you are emulating an open-drain output.  If you were just to drive the GPIO HIGH it would hold the RESET pin HIGH and you wouldn't be able to use the USB interface, nor the RESET button.  By setting it to INPUT it is then effectively disconnected from the RESET pin so won't interfere.
The Yún again has a script that works in that way, "reset-mcu":
#!/bin/sh

echo 18 > /sys/class/gpio/export
echo "high" > /sys/class/gpio/gpio18/direction
echo 1 > /sys/class/gpio/gpio18/value
echo 0 > /sys/class/gpio/gpio18/value
echo 18 > /sys/class/gpio/unexport

I have a similar setup to you but using a BeagleBone Black and a PONTECH Quick240 PIC32 based controller.  In my IDE UECIDE I set up a special board definition with the following programmer added to it which performs the manual reset through GPIO and runs the upload program (pic32prog) all in one operation:
upload.local.name=Local upload
upload.local.using=script
upload.local.script.0=__builtin_bullet::Entering programming mode...
upload.local.script.1=__builtin_gpio::7::low
upload.local.script.2=__builtin_delay::100
upload.local.script.3=__builtin_gpio::20::low
upload.local.script.4=__builtin_delay::100
upload.local.script.5=__builtin_gpio::20::hiz
upload.local.script.6=__builtin_delay::100
upload.local.script.7=__builtin_gpio::7::hiz
upload.local.script.8=__builtin_delay::100
upload.local.script.9=__builtin_bullet::Uploading sketch...
upload.local.script.10=${core.root}/tools/linux_arm/pic32prog::-S::-d::${port}::-B::${upload.maxbaud}::-p::${build.path}/${filename}.hex
upload.local.script.11=__builtin_bullet::Resetting board...
upload.local.script.12=__builtin_delay::100
upload.local.script.13=__builtin_gpio::20::low
upload.local.script.14=__builtin_delay::100
upload.local.script.15=__builtin_gpio::20::hiz

sketch.upload=local

That one is a little different in that you have to hold a second GPIO LOW while you reset the board to initiate the bootloader, hence the two GPIOs in use there.


text:
Arduino IDE Board Manager: Unable to install Due on 1.6.5
I have an Arduino Due I'd like to start using. I've been using Unos, Megas etc no problem. The newer IDEs have removed the Due support. I've been trying to install Due support through the Board Manager, but when I open the Boards Manager, I get :
Error downloading http://downloads.arduino.cc/packages/package_index.json
and when I try to install Due support, I get :
Error downloading http://downloads.arduino.cc/cores/sam-1.6.4.tar.bz2
I understand I may be behind proxies, but in IDE version 1.6.5, that has been removed from the Preferences, so I can't change that. I have tried to allow the IDE past the Windows Firefall, but that has not changed anything.
I have manually downloaded sam-1.6.4.tar.bz2 and extracted the contents to C:\Arduino\arduino-1.6.5\hardware\arduino\sam (I had to manually create the sam folder). With this, I can see the options of Arduino Due Native USB Port and Arduino Due Programming Port when selecting the board, and when I look for it in the Ports, it can recognise the board at the port (eg "COM5 (Arduino Due (Programming Port))" ). When I try to compile anything, I get the error message :
Cannot run program "{runtime.tools.arm-none-eabi-gcc.path}\bin\arm-none-eabi-g++" (in directory "."): CreateProcess error=2, The system cannot find the file specified
Any other idea as to how I can install the Due? Is there an option for a manual installation? The same happens with Libraries Manager (I don't get a connection), so I guess, the same can be applied to that.


text:
Arduino Web Server and Relay Module
I am working on a web server project for work. I have a web server setup with an Arduino Meg2560 with Ethernet. I also have a 16 relay board connected to Ethernet with its own IP. I wanted to see if there is a way I can make calls to the relay board via IP from the Arduino Webserver. For example Relay 1 on the relay board can be turned on by typing 192.168.1.4/30000/00 but this opens the web GUI on the board. I need to do the same thing but without opening the webpage or web GUI.

    #include <SPI.h>
    #include <Ethernet.h>

    // MAC address from Ethernet shield sticker under board
    byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
    IPAddress ip(192, 168, 1, 177); // IP address
    EthernetServer server(80);  // Server Port 80

    void setup()
    {
      Ethernet.begin(mac, ip);
      server.begin();
    }

    void loop()
{
EthernetClient client = server.available();  // try to get client

if (client) {  // got client?
    boolean currentLineIsBlank = true;
    while (client.connected()) {
        if (client.available()) {   // client data available to read
            char c = client.read(); // read 1 byte (character) from client
            // last line of client request is blank and ends with \n
            // respond to client only after last line received
            if (c == '\n' && currentLineIsBlank) {
                // send a standard http response header
                client.println("HTTP/1.1 200 OK");
                client.println("Content-Type: text/html");
                client.println("Connection: close");
                client.println();
                // send web page
                client.println("<!DOCTYPE html>");
                client.println("");
                client.println("");
                client.println("<title>Arduino Web Page</title>");
                client.println("");
                client.println("");
                client.println("
Hello from Arduino!
");
                client.println("
A web page from the Arduino server
");
                client.println("");
                client.println("");
                break;
            }
            // every line of text received from the client ends with \r\n
            if (c == '\n') {
                // last character on line of received text
                // starting new line with next character read
                currentLineIsBlank = true;
            }
            else if (c != '\r') {
                // a text character was received from client
                currentLineIsBlank = false;
            }
        } // end if (client.available())
    } // end while (client.connected())
    delay(1);      // give the web browser time to receive the data
    client.stop(); // close the connection
} // end if (client)

}

I have my web server working and ready to go on my Arduino I just need help adding code to it for calling my relay board. Thank you

Which model of relay board is this? I don't see any need for server in arduino as you already have one in the relay module.

So what if it "opens a GUI" when you send a GET request to that URL.  That doesn't mean you have to DO anything with that GUI data - you can just ignore it completely.  Just send the GET request then close the connection.

Documentation on the controller you are using is pretty scant, but it looks like you just need to make a GET request to the URI corresponding to the action you need to take.

http://192.168.1.4/30000/00 : Relay-01 OFF
http://192.168.1.4/30000/01 : Relay-01 ON
http://192.168.1.4/30000/02 : Relay-02 OFF
http://192.168.1.4/30000/03 : Relay-02 ON
http://192.168.1.4/30000/04 : Relay-03 OFF
http://192.168.1.4/30000/05 : Relay-03 ON
…
http://192.168.1.4/30000/14 : Relay-8 OFF
http://192.168.1.4/30000/15 : Relay-8 ON
http://192.168.1.4/30000/41 : Enter
http://192.168.1.4/30000/40 : Exit
http://192.168.1.4/30000/42 : Next Page
http://192.168.1.4/30000/43 : Next Page

For example If I wanted to turn off relay 3, I would simple make a GET request to http://192.168.1.4/30000/04 and close the connection. Example code:
IPAddress server(192,168,1,4);
EthernetClient client;
client.connect(server, 80);
client.println("GET /30000/04 HTTP/1.1");
client.println("Connection: close");
client.println();
client.stop();

How do I add that to the Arduino web server I think that is exacly what I am needing to add I would like to just have a link for now say Relay 1 On and it do the Get /30000/01 to turn it on. I added my web server Sketch to the main question. Thank you

Thank you Jake I was able to get the GET code to work. I am new to the Arduino so it took me awhile to figure out what the code is doing.


text:
PWM timers, channels and pins
I've got this code from the MultiWii project, which is relevant to the hardware, ATmega32u4, I have. It is part of a function called initOutput().
In the comment it says "connect pin 6", which is the bit of that which specifies pin 6 as I would like to change it to another pin, specifically A0.
// Enhanced PWM mode
TCCR4E |= (1<<ENHC4);

// Prescaler to 16
TCCR4B &= ~(1<<CS41);
TCCR4B |= (1<<CS42) | (1<<CS40);

// Phase and frequency correct mode and top to 1023, but
// with enhanced PWM mode we have 2047.
TCCR4D |= (1<<WGM40);
TC4H = 0x3;
OCR4C = 0xFF;

// Connect pin 6 to timer 4 channel D
TCCR4C |= (1<<COM4D1) | (1<<PWM4D);

It's the (1<<COM4D1) that enables pin 6, or more specifically OC4D for timer output. You cannot use A0 instead, since there is no output compare capability on that pin; only pins 13, 5, 10, 9, 6, and 12 can be connected to timer 4. See the datasheet for details.

thanks for your answer, maybe you can help with my latest question: http://arduino.stackexchange.com/questions/13557/32u4-timer-4-help


text:
Can I connect TFT LCD screen to Arduino Leonardo same way as it's recommanded for Arduino Uno?
I want to connect the Arduino TFT LCD 1.77" screen to an Arduino Leonardo. Acording to this tutorial I should connect some pins on LCD screen to ICSP pins on Leonardo but I don't have equipment to do it. Can I just connect LCD screen to Leonardo in the way it't recommanded for an Arduino Uno (same tutorial above) using only digital and power pins. And then use sketches for Uno. Will it work?
Also, is it safe for LCD screen?

Datasheet where?

I think it could work, but not easily. I.e. you would need to tweak the code and anyway you will end up with really low performance.
This is the reason:

SPI: on the ICSP header. These pins support SPI communication using the SPI library. Note that the SPI pins are not connected to any of the digital I/O pins as they are on the Uno, They are only available on the ICSP connector. This means that if you have a shield that uses SPI, but does NOT have a 6-pin ICSP connector that connects to the Leonardo's 6-pin ICSP header, the shield will not work.

Source: https://www.arduino.cc/en/Main/ArduinoBoardLeonardo

The screen can be configured for use in two ways. One is to use an Arduino's hardware SPI interface. The other is to declare all the pins manually. There is no difference in the functionality of the screen between the two methods, but using hardware SPI is significantly faster when drawing.
  If you plan on using the SD card on the TFT module, you must use hardware SPI.
  All the examples are written for hardware SPI use.

Source: https://www.arduino.cc/en/Guide/TFT#toc4
In the end I think it would be better to get the equipment needed...
Edit: You can try with this constructor:

When not using hardware SPI, you can use any available pins, but you must declare the MOSI and SCLK pins in addition to CD, DC, and RESET.

#define SCLK 4
#define MOSI 5
#define CS   6
#define DC   7
#define RESET 8

TFT myScreen = TFT(CS, DC, MOSI, SCLK, RESET);

Source: https://www.arduino.cc/en/Reference/TFTLibrary

You can hook up the "Adafruit_ST7735" or from what i later learned after getting my Esplora. Thats when i had my adruino-epiphany. Okay so IF your wondering why im including this super rad Controller shaped arduino, the answer is, its a leonardo. well its just a different flavor of the Atmega32u4 whis is the chip that made ext serial programmers kinda obsolete and makes the uno and megas so unique as well. so with that being said the Esplora has a native language when refering back the tft libraries, but its not too far from a simple (ctrl+F) and replace Esplora references with actual defines and references. and in this case the Leonardo would need to have the icsp header used by the corresponding pins on the display (for this instance of using an SPI connection with the serial display we will not swap the Miso and Mosi  like we would a nother instance.just connect miso to miso and mosi to mosi i usually plug up the whole icsp header and then that wwill leave you with the two pins you MUST DEFINE to make it work which would be :
// Pins SCLK and MOSI are fixed in hardware, and pin 10 (or 53)

// must be an output
//#define sclk 13    // for MEGAs use pin 52
//#define mosi 11    // for MEGAs use pin 51
define cs 10   // for MEGAs you probably want this to be pin 53
define dc 9
define rst 8  // you can also connect this to the Arduino reset
// Pins SCLK and MOSI are fixed in hardware, and pin 10 (or 53)

// must be an output
//#define sclk 13    // for MEGAs use pin 52
//#define mosi 11    // for MEGAs use pin 51
define cs 10   // for MEGAs you probably want this to be pin 53
define dc 9
define rst 8  // you can also connect this to the Arduino reset
// Color definitions
define BLACK           0x0000
define BLUE            0x001F
define RED             0xF800
define GREEN           0x07E0
define CYAN            0x07FF
define MAGENTA         0xF81F
define YELLOW          0xFFE0
define WHITE           0xFFFF
include
include
// Option 1: use any pins but a little slower
//ST7735 tft = ST7735(cs, dc, mosi, sclk, rst);
// Option 2: must use the hardware SPI pins
// (for UNO thats sclk = 13 and sid = 11) and pin 10 must be
// an output. This is much faster - also required if you want
// to use the microSD card (see the image drawing example)
ST7735 tft = ST7735(cs, dc, rst);
float p = 3.141592; // value for pi
int tft_width = 128;
int tft_height = 160;
int x1 = 60;
int y1 = 60;
int x2 = 20;
int y2 = 80;
int ballx = 60;
int bally = 60;
int deltay = 1;
int deltax = 1;
int ball_speed = 24;
int left_score = 4;
int right_score = 4;
int background_color = 0x00;
void setup(void) {
  tft.initR();               // initialize a ST7735R chip
tft.writecommand(ST7735_DISPON);
  tft.fillScreen(background_color);
  delay(700);
  for(int i = 0; i < 9; i++){
    pinMode(i,OUTPUT);
  }
  for(int i = 0; i < 9; i++){
    digitalWrite(i,HIGH);
  }
  delay(500);
}
void loop() {
  for(int i = 0; i < left_score; i++){
    digitalWrite(i,HIGH);
  }
  for(int i = 0; i < right_score; i++){
    digitalWrite(i+4,HIGH);
  }
  int cur_r = random(20,32);
  int cur_g = random(55,64);
  int cur_b = random(10,32);
  int color = cur_r  | (cur_g << 5) | (cur_b << 11);
  int radius = 4;
  draw_paddles();
  draw_ball(color);
  delay(ball_speed);
}
void draw_input_text(){
  int cur_x2 =  analogRead(2);
  int cur_y2 =  analogRead(3);
  String xs = String(cur_x2);
  String ys = String(cur_y2);
  char cx[4];
  cx[0] = xs.charAt(0);
  cx[1] = xs.charAt(1);
  cx[2] = xs.charAt(2);
  cx[3] =0;
  char cy[4];
  cy[0] = ys.charAt(0);
  cy[1] = ys.charAt(1);
  cy[2] = ys.charAt(2);
  cy[3] =0;
  tft.fillRect(10,20,40,40,background_color);
  tft.drawString(12,22,cx ,YELLOW);
  tft.drawString(12,40,cy ,YELLOW);
}
void draw_paddles(){
  int cur_x =  analogRead(0);
  int cur_y =  analogRead(1);
  int hval = 620;
  int lval = 350;
if ( y1 < tft_height - 20  && cur_y > hval) y1++;
  else if ( y1 > 0 && cur_y < lval ) y1--;
int cur_x2 =  analogRead(2);
  int cur_y2 =  analogRead(3);
if ( y2 < tft_height - 20 && cur_y2 > hval ) y2++;
  else if (y2 > 0 && cur_y2 < lval ) y2--;
  tft.fillRect(2, y1-3, 5, 27, background_color);
  tft.fillRect(3, y1, 3, 20, YELLOW);
  tft.fillRect(tft_width-3, y2-3, 5, 27,background_color);
  tft.fillRect(tft_width-3, y2, 3, 20, YELLOW);
}
void draw_ball(int color){
   int bradius = 6;
    tft.fillCircle(ballx, bally, bradius , color);
    ballx += deltax;
    bally += deltay;
    if ( ballx < 7 && bally > y1 && bally < y1+20) deltax *= -1;
    else if ( ballx > tft_width-7 && bally > y2 && bally < y2+20) deltax *= -1;
    else if ( bally <= bradius || bally >= tft_height - bradius ) deltay *= -1;
    if (ballx <=  0 ) {
      left_score--;
      tft.drawString(2,42, "Right Won!" ,~background_color,2);
      tft.drawString(2,62, "Get Ready!" ,CYAN,2);
      for (int i = 0; i <250; i++){
        delay(10);
        draw_paddles();
      }
      int cur_r = random(0,26);
      int cur_g = random(0,30);
      int cur_b = random(0,18);
      background_color = cur_r  | (cur_g << 5) | (cur_b << 11);
      tft.fillScreen(background_color);
      ballx = 64;
      bally = 80;
      if (ball_speed > 1) ball_speed--;
      digitalWrite(left_score,LOW);
    } else if (ballx >= tft_width  ) {
      right_score --;
      tft.drawString(2,42, "Left Won!" ,YELLOW,2);
      tft.drawString(2,62, "Get Ready!" ,GREEN,2);
      for (int i = 0; i <250; i++){
        delay(10);
        draw_paddles();
      }
      int cur_r = random(0,26);
      int cur_g = random(0,30);
      int cur_b = random(0,18);
      background_color = cur_r  | (cur_g << 5) | (cur_b << 11);
      tft.fillScreen(background_color);
      ballx = 64;
      bally = 80;
      if (ball_speed > 1) ball_speed--;
  digitalWrite(4+right_score,LOW);

}

}
enjoy getting that code to fudge around with  i  stole it right form  here http://lucidtronix.com/tutorials/7
 but the point i had to bring up is that i believe the guy before mentioned that it is a muchslower connectionor process than if it were.....were you saying softwareserial was the option then?
 because im not an explert or novice or maker by any means. but i have picked up along the lines that hardware serial will always trump software serial compilation any day once you get your head wrapped around the brevity of what ports and pins are actually what are used or have the data displayed on the serial ports. and like software is a necessity im afraid, but its as simple as reasigning pins and when that gets too hard going out and just bbuying a mega, haahah hope i sorta helped. id say go out and snag an esplora whilst their like toing a fire clearance sale on the originallt 50$+ boards. but their reference and prebuilt array of sensors is a bit underwhelming for the newbies in what it alll does, but kinda overwhelmine and difficult to transistion onece having looked at some code as it is, but the language is more forg9ving, but i believe their also officially retiring the leonardo espolora and micro series so good luck this tft display kicks bum man and is the only one that hsnt broke


text:
Sending data from Processing and receiving as uint32_t
I need to send data from a processing sketch to an Arduino to pass to a function that takes a uint32_t.  How to I send the data in Processing to be run on the Arduino

One byte at a time.

I recommend studying up on bitwise shifts (<< and >>), along with the bitwise OR and AND. They're what you're going to need, especially since atoi() would only give you a 16 bit, signed integer.
Let's say that your variable's binary is this (split up into 4 segments):
10010010 10110101 01010010 10010100

Sending
uint32_t myVarCopy = myVar;
for(int i = 0; i < 4; i++) {
    Serial.write(myVarCopy & 255);
    myVarCopy = myVarCopy >> 8;
}

The first line in the loop modifies the variable by bitshifting right eight to allow us to read the data eight bits at a time. We have to, whenever sending data through the serial port, "trim" any data that is in the 9th digit or above using the & 255 part. This allows us to split this int up into four bytes.
How the myVarCopy variable would look over the four iterations:
After 1: 00000000 10010010 10110101 01010010 (sent 10010100)
After 2: 00000000 00000000 10010010 10110101 (sent 01010010)
After 3: 00000000 00000000 00000000 10010010 (sent 10110101)
After 4: 00000000 00000000 00000000 00000000 (sent 10010010)

Reading
uint32_t buffer = 0;
for(int i = 0; i < 4; i++) {
    buffer = (buffer >> 8) | (Serial.read() << 24);
}

This code works by adding the newest data onto the digits 25-32 after it moves everything else over eight bits.
This is how the buffer variable would look over the four iterations:
After 1: 10010100 00000000 00000000 00000000
After 2: 01010010 10010100 00000000 00000000
After 3: 10110101 01010010 10010100 00000000
After 4: 10010010 10110101 01010010 10010100

Depending on how Processing works, you might have to worry about little/big endian encoding to ensure that your data is in the right order. Warning: I haven't tested these yet as an IDE isn't installed on the computer I'm typing this on. Also, I don't know the exact function calls for Processing, so it might not compile.


text:
Using PROGMEM to store array of structs
I am hitting the limits of my arduino's SRAM and found that SRAM usage can be reduced by storing static stuff in flash memory instead of SRAM.
My project can (optionally) be built with an included SimulatorClass. I use this to 'playback' data at home which I gathered during real-life testing of my project. My project is based on photoelectric sensors, and it's timing-critical, so all timekeeping is done using micros(), which returns unsigned long datatype.
To simulate these photoelectric sensor triggers, I need an array containing a struct of 3 variables each:
unsigned int _iDataPos;
   struct SimulatorRecord
   {
      uint8_t iSensorNumber;
      unsigned long lTriggerTime;
      uint8_t iState;
   };

So one these structs is 6 bytes long in my counting (2x uint8_t = 2 bytes, unsigned long = 4 bytes).
A typical set of simulator records I need to use is about 25-30 records long, so worst case scenario the simulator array is 180 bytes in size.
I initialize these arrays like so:
SimulatorRecord SimulatorQueue[28] = {
      { 1, 41708, 1 }
      , { 2, 60692, 1 }
      , { 1, 176848, 0 }
      , { 2, 197732, 0 }
      , { 1, 4675580, 1 }
      , { 2, 4692252, 1 }
      , { 2, 4830180, 0 }
      , { 1, 4849032, 0 }
      , { 2, 9058416, 1 }
      , { 1, 9074780, 1 }
      , { 1, 9215868, 0 }
      , { 2, 9234968, 0 }
      , { 2, 13497276, 1 }
      , { 2, 13500924, 0 }
      , { 2, 13502728, 1 }
      , { 1, 13514992, 1 }
      , { 1, 13668000, 0 }
      , { 1, 13669344, 1 }
      , { 1, 13681828, 0 }
      , { 2, 13701464, 0 }
      , { 2, 18028788, 1 }
      , { 2, 18034252, 0 }
      , { 2, 18036540, 1 }
      , { 1, 18046892, 1 }
      , { 2, 18160312, 0 }
      , { 1, 18178224, 0 }
      , { 1, 20454580, 1 }
      , { 1, 20456368, 0 }
   };

In my simulator code I then loop through these arrays like so:
   unsigned int _iDataPos = 0;
   SimulatorRecord PendingRecord = SimulatorQueue[_iDataPos];

   //main simulator loop
   if (PendingRecord.lTriggerTime <= lRaceElapsedTime)
   {
      //simulate signal
      digitalWrite(PendingRecord.iSensorNumber, PendingRecord.iState);

      //And increase pending record
      _iDataPos++;
      PendingRecord = SimulatorQueue[_iDataPos];
   }

Now I've been reading various PROGMEM tutorials, and storing the SimulatorQueue array in flash seems to be piece of cake, just change
SimulatorRecord SimulatorQueue[28]

to
const PROGMEM SimulatorRecord SimulatorQueue[28]

But for the life of me I can't find out how I should change the copying of each array item to the PendingRecord variable, as my iDataPos counter increases.
Edit: I should have mentioned that this simulator class and all it's member functions & variables reside in a seperate *.cpp and *.h file.
I alreadt found out that since i'm initializing the SimulatorQueue array in the class itself, and not in the main *.ino file, I should do it like so:
constexpr static SimulatorRecord SimulatorQueue[28] PROGMEM = {<structs go in here>};

Edit2: Sample code which reproduces the problem when the simulator array is available here:
http://1drv.ms/1TRwiIB

I don't know why this only has one upvote, it's a very good question. (Ftr, I am that one upvoter).

An easy way of accessing any type of data in PROGMEM is to use this small library:
PROGMEM_readAnything.h
#include <Arduino.h>  // for type definitions

template <typename T> void PROGMEM_readAnything (const T * sce, T& dest)
  {
  memcpy_P (&dest, sce, sizeof (T));
  }

template <typename T> T PROGMEM_getAnything (const T * sce)
  {
  static T temp;
  memcpy_P (&temp, sce, sizeof (T));
  return temp;
  }

You can put that file into a new tab in your IDE, or make a library by putting it inside a folder called PROGMEM_readAnything and put that folder inside the libraries folder, which is inside your sketchbook folder.
That lets you copy from the memory in PROGMEM (using memcpy_P) into RAM. The template is used to work out how many bytes to copy.

Example, using your structure:
#include <PROGMEM_readAnything.h>

struct SimulatorRecord
{
  uint8_t iSensorNumber;
  unsigned long lTriggerTime;
  uint8_t iState;
};

const SimulatorRecord SimulatorQueue[28] PROGMEM = {
      { 1, 41708, 1 }
      , { 2, 60692, 1 }
      , { 1, 176848, 0 }
 //    ...   omitted for brevity
      , { 1, 18178224, 0 }
      , { 1, 20454580, 1 }
      , { 1, 20456368, 0 }
   };

// number of items in an array
template< typename T, size_t N > size_t ArraySize (T (&) [N]){ return N; }

void setup ()
{
  Serial.begin (115200);
  Serial.println ();

  for (int i = 0; i < ArraySize (SimulatorQueue); i++)
    {
    SimulatorRecord thisItem;
    PROGMEM_readAnything (&SimulatorQueue [i], thisItem);
    Serial.print (i);
    Serial.print (F(" = "));
    Serial.print (thisItem.iSensorNumber);
    Serial.print (F(" / "));
    Serial.print (thisItem.lTriggerTime);
    Serial.print (F(" / "));
    Serial.print (thisItem.iState);
    Serial.println ();
    }  // end of for loop
}  // end of setup

void loop ()
{
}  // end of loop

I found that it decreased RAM usage by 166 bytes, which is almost 28 * 6 (a couple of bytes must have been used by something).

Reference
Putting constant data into program memory (PROGMEM)

Putting PROGMEM into a class
In response to some comments below, this explains how to put the constants into a class.
Alex originally had:
class SimulatorClass
{

...

   typedef struct SimulatorRecord
   {
      uint8_t iSensorNumber;
      unsigned long lTriggerTime;
      uint8_t iState;
   } SimulatorRecord;

   constexpr static SimulatorRecord SimulatorQueue[28] PROGMEM = {
      { 1, 41708, 1 }
      , { 2, 60692, 1 }
   //    ...   omitted for brevity
      , { 1, 20454580, 1 }
      , { 1, 20456368, 0 }
   };

   SimulatorRecord PendingRecord;
};

Putting aside whatever "constexpr" is, you can't put constants inside a class like that. You need to make it static, and have the actual definition elsewhere. So, change the constants to:
class SimulatorClass
{

...

   typedef struct SimulatorRecord
   {
      uint8_t iSensorNumber;
      unsigned long lTriggerTime;
      uint8_t iState;
   } SimulatorRecord;

  static const SimulatorRecord SimulatorQueue[28] PROGMEM ;

  SimulatorRecord PendingRecord;
};

Now in your main class file (Simulator.cpp in your case):
 const SimulatorClass::SimulatorRecord SimulatorClass::SimulatorQueue[28] PROGMEM = {
    { 1, 41708, 1 }
    , { 2, 60692, 1 }
   //    ...   omitted for brevity
    , { 1, 20454580, 1 }
    , { 1, 20456368, 0 }
   };

That now compiles OK.

Thanks for your answer. Unfortunately it gives me the same compiler error as I commented on Ignaio's answer below.  I believe it has something to do with these being member functions and variables of a class, in a seperate cpp/h file. However I can't find how I should initialize PendingRecord correctly so it compiles...

Can you post the exact error message please? My code doesn't have SimulatorClass in it, so that cannot be in the error. I tested my code, I didn't just write it without trying. it gives me the same compiler error - I would like you to try my exact code. If it does not give a compiler error, then the problem is elsewhere.

Nick your code works fine off course, but due to the nature of my project  I have to adapt it into my existing codebase. I committed my attempt at integrating your solution to Github, you can find it here: https://github.com/vyruz1986/FlyballSensor/tree/develop. It would be great if you could modify your answer with information on how to use your solution inside a class.

Can you modify your question to add a minimal example of what you are doing? There's a lot of code on your Github site. A Minimal, Complete, and Verifiable example would be great.

OK sorry for that. Answer updated, check http://1drv.ms/1TRwiIB. Thanks!

See modified answer.

Works perfectly, not a byte more SRAM usage compared to when I leave the whole SimulatorClass out! Thanks a million!

"whatever "constexpr" is" constexpr is a very useful feature of C++11.

Using it with heterogeneous types is trickier, since it has to be copied by hand instead of using one of the pgm_read_*() macros.
SimulatorRecord PendingRecord;
memcpy_P(&PendingRecord, &SimulatorQueue[_iDataPos], sizeof(PendingRecord));

Thanks for answering! It is compiling but my SRAM usage isn't being affected at all. I also can't test if it works or not since my program is crashing due not enough SRAM... Any idea what could be wrong?

Never mind found it: was using const SimulatorRecord SimulatorQueue[28] PROGMEM, forgot to add the static keyword. I do get a compilation error on the memcpy_P() now however: undefined reference to SimulatorClass::SimulatorQueue

Could these undefined reference to errors be related to the fact the simulator class and its members reside in seperate cpp/h files? I edited my questions to clarify this.


text:
Function to send SMS in PDU format
I'm trying to send SMS using Arduino Uno v3 and Sony Ericsson K700i. I have a function that converts a text and a number to pdu format but I'm unable to deliver the message. I don't get any error after posting the serial data to phone. Could someone please quide me?
Here is the function that I use
void send_sms(String message, String phone_nr )
{
 byte original_byte;
byte newbyte;
int pdu_length;
int counter;
String newphone_nr;
int numlength;

 delay(1000);
  Serial.begin(9600);
  delay(1000);
  numlength=phone_nr.length()-1;
  if (numlength% 2 != 0 ) {
    phone_nr += "F";
  }
  for(int x = 0; x < numlength; x = x+2){
    newphone_nr.concat(phone_nr.charAt(x+2));
    newphone_nr.concat(phone_nr.charAt(x+1));
  }

  //start sending SMS
  Serial.println("AT");  //optional: say hello to the modem
  delay(3000);
  Serial.println("AT+CMGF=0"); //set pdu mode
  delay(3000);
  int textlength= message.length()*7/8;   // text message length: number of characters*7/8
  if (message.length()*7%8 != 0) {
    textlength++;
  }
  if (numlength%2 != 0) {   //if the length of phone number was uneven, it now increases by 1 because of the added "F"
    pdu_length = (8 + (numlength+1)/2 + textlength);
  }
  else { //8 bytes of parameters + (length of phonenumber)/2 + number of bytes in the text
    pdu_length = (8 + numlength/2 + textlength);
  }

  Serial.print("AT+CMGW="); //message will be stored in the mobile phone - AT+CMGS will send it off.
  //delay(3000);
  Serial.println(pdu_length);
  //delay(100);
  Serial.print("001100");  //these are some parameters which we don't need to bother about
  //delay(100);
  if (numlength<16){       //now we have to send the byte containing the length of the phone number in HEX format
    Serial.print(0);
  //delay(100);
  }        //the byte in HEX format needs to be 2 characters long; if needed we add a 0 in front, e.g. "C" will become "0C"
  Serial.print(numlength,HEX); //length telnr - this time any additional F is not to be considered
 // delay(100);
  Serial.print("91");     //international format of phone number //81 for national format
  //delay(100);
  Serial.print(newphone_nr); //now we send the rearranged phone number
  //delay(100);
  Serial.print("0000AA"); //some more parameters
  //delay(100);
  if (message.length()<16){
    Serial.print(0);
    //delay(100);
  }       //a byte in HEX format indicating the length of the text. Again the byte needs to be made of 2 characters
  Serial.print(message.length(),HEX);
  //delay(100);

  counter=0;
  newbyte=0;
  for (int j=0; j<message.length(); j++) {
    original_byte = message.charAt(j); //one by one we take each byte out of the original text

    for (int i=0; i<7; i++) {
      newbyte=newbyte|bitRead(original_byte, i)<<counter;  //take the bits 0 to 6 of the old byte, shift as required for the new byte and add to the new byte
      counter++;
      if (counter==8) {
        counter=0;          //if a new byte is complete, set the counter to 0
        if (newbyte<16){
          Serial.print(0);
         // delay(100);
        } //each byte in HEX format should consist of 2 characters, if necessary add 0 in front
        Serial.print (newbyte, HEX); //when the new byte is finished, send it to the mobile phone
        //delay(100);
        newbyte=0; // the next new byte will start again from 0
      }
    }
  }
  if (message.length()*7%8!=0) {    //if there were remaining bits (not enough to form a new byte), these are sent out as the last byte
    if (newbyte<16){
      Serial.print(0);
      //delay(100);
    } //each byte in HEX format should consist of 2 characters, if necessary add 0 in front
    Serial.println (newbyte, HEX);
    //delay(100);
  }
  delay (3000);
  Serial.write(26); //this is a command telling the mobile phone that the end of the transmission has been reached

}

Q1: Is there any way I can add service message center as a parameter?
Q2: How can I make this functionshow the phone response to the commands I give?
Thanks a lot!


text:
Arduino uint8_t to String or char- retrieve from usb device
My code returns uint8_t format when is cast to char and Display on LCD it works fine but I want to get that scanned code for further processing. not only to display on LCD 16x2 , but it returns some strange symbols. Any Idea?
#include <LiquidCrystal.h>
#include <avr/pgmspace.h>
#include <hid.h>
#include <hiduniversal.h>
#include <usbhub.h>
#include <Usb.h>
#include <usbhub.h>
#include <avr/pgmspace.h>
#include <hidboot.h>
#include <SPI.h>
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
USB     Usb;
USBHub     Hub(&Usb);
HIDUniversal Hid(&Usb);
HIDBoot<HID_PROTOCOL_KEYBOARD>    Keyboard(&Usb);

class KbdRptParser : public KeyboardReportParser
{
  void PrintKey(uint8_t mod, uint8_t key);
protected:
  virtual void OnKeyDown  (uint8_t mod, uint8_t key);
  virtual void OnKeyPressed(uint8_t key);
};

void KbdRptParser::OnKeyDown(uint8_t mod, uint8_t key)
{
    uint8_t c = OemToAscii(mod, key);

    if (c)
        OnKeyPressed(c);
}

/* what to do when symbol arrives */
void KbdRptParser::OnKeyPressed(uint8_t key)
{
static uint32_t next_time = 0;      //watchdog
static uint8_t current_cursor = 0;  //tracks current cursor position

    if( millis() > next_time ) {
      lcd.clear();
      current_cursor = 0;
      delay( 5 );  //LCD-specific
      lcd.setCursor( 0,0 );
    }//if( millis() > next_time ...

    next_time = millis() + 200;  //reset watchdog

    if( current_cursor++ == ( DISPLAY_WIDTH + 1 )) {  //switch to second line if cursor outside the screen
      lcd.setCursor( 0,1 );
    }
  char keys=(char) key;
    Serial.println(keys);
// char add =keys.indexOf(5)+keys.indexOf(6)+keys.indexOf(7)+keys.indexOf(8);
    Serial.println(keys);
    lcd.print(keys);
};

KbdRptParser Prs;

void setup()
{
    Serial.begin( 115200 );
    Serial.println("Start");

    if (Usb.Init() == -1) {
        Serial.println("OSC did not start.");
    }

    delay( 200 );

    Hid.SetReportParser(0, (HIDReportParser*)&Prs);
    // set up the LCD's number of columns and rows:
    lcd.begin(DISPLAY_WIDTH, 2);
    lcd.clear();
    lcd.noAutoscroll();
    lcd.print("Scan Your Code");
    delay( 200 );
}

void loop()
{
  Usb.Task();
}

I have some difficulties in following your code, and you include the same file twice. Maybe you can review the code and highlight where the problem lies?

Where in your code does it return 'strange symbols'?

@Bruce I have used this with scanning barcodes with my barcode reader, and it displays the barcode with numbers fine on LCD, but when I see the output of serial monitor, it show some stange symbols instead of numbers that display on LCD

A unit8_t is an 8 bit unsigned integer - it can have any value between 0 and 255, and can be compared to any numeric value in that range.
You can do "further processing" on the received uint8_t value whether it is a printable ASCII value or not.

Bennet I have used this with scanning barcodes with my barcode reader, and it displays the barcode with numbers fine on LCD, but when I see the output of serial monitor, it show some stange symbols instead of numbers that display on LCD

If the symbols look like Japanese, then probably bit 7 of your characters is set to 1. The upper 128 characters are reserved for Katakana in many LCDs. So, if you are sure the characters are correct, you may have to be AND them with 0x7F to assure they are in the right half of the character encoder.
Do check the requirements of your LCD, and the code in the library to control the display. In one occasion, you added a 5 ms delay, and in other clear(), you didn't. One of the annoyances of LCD displays is that you have to be careful with those delay, else you can land the controller in a strange mode,