text:
Sending 5 Led pixel values to arduino , is this a good way?
I wanted to install a 5 LED strip underneath my PC's front panel. I want to send color over PC so it can change when i open different apps, with temperature or etc!
So all I think the best way to do this is to just use Arduino to set the LED Values!
But I have had some troubles creating a good communication protocol for this, I've been just simply sending 45 digits (15 3 digit numbers) to my Arduino with serial. here's code:
Arduino :
#include "Adafruit_NeoPixel.h"
#include "WS2812_Definitions.h"

#define PIN 4
#define LED_COUNT 5

struct pixel {
  int R = 0;
  int B = 0;
  int G = 0;
};

Adafruit_NeoPixel leds = Adafruit_NeoPixel(LED_COUNT, PIN, NEO_GRB + NEO_KHZ800);

char count = 1;
int pixelNumber = 0;
struct pixel tempPixel;
//struct pixel Pixels[LED_COUNT];

void setup()
{
  Serial.begin(9600);
  Serial.println("Init");
  leds.begin();  // Call this to start up the LED strip.
  clearLEDs();   // This function, defined below, turns all LEDs off...
  leds.show();   // ...but the LEDs don't actually update until you call this.
}

void loop() {
  if(Serial.available() > 0) {
    if(count == 1) {
      tempPixel.R = PC_Receive();
    } else if (count == 2) {
      tempPixel.G = PC_Receive();
    } else if (count == 3) {
      tempPixel.B = PC_Receive();
      count = 0;

      setPixelColor(pixelNumber, tempPixel);
      Serial.println(pixelNumber);
      leds.show();
//      Pixels[pixelNumber] = tempPixel;
      if(++pixelNumber >= LED_COUNT) {
        pixelNumber = 0;
      }
    }
    count++;
  }

//  if(pixelNumber == 0) {
//    for(int i = 0; i < LED_COUNT; i++ ) {
//       setPixelColor(i, Pixels[i]);
//    }
//
//    leds.show();
//  }
}

void setPixelColor(int a, struct pixel P)
{
  leds.setPixelColor(a, P.R, P.G, P.B);
}

char PC_Receive() {
  int result = 0;

  while(Serial.available() == 0);
  result += ((int)Serial.read() - '0') * 100;

  while(Serial.available() == 0);
  result += ((int)Serial.read() - '0') * 10;

  while(Serial.available() == 0);
  result += ((int)Serial.read() - '0');

  Serial.println(result);
  return result;
}

void setColourRgb(unsigned int red, unsigned int green, unsigned int blue) {
  for(int i = 0; i < LED_COUNT; i++) {
    leds.setPixelColor(i, red, green, blue);
  }
  leds.show();
 }

And here's PC's dirty code in python:
import serial
import time
import random

class Pixel:

    def __init__(self, R, G, B):
        self.R = R
        self.G = G
        self.B = B

def clearAll():
    for i in range(0,5):
        ser.write("000000000")

def sendPixel(pixels):
    for i in range(0,5):
        ser.write(str(pixels[i].R).zfill(3))
        ser.write(str(pixels[i].B).zfill(3))
        ser.write(str(pixels[i].G).zfill(3))

ser = serial.Serial('/dev/ttyACM2', 9600)

little = [0,0,0,0,0]

for i in range(0,5):
    little[i] = Pixel(0,255,50)
sendPixel(little)

time.sleep(0.5)
clearAll()

the problem is it isn't stable, i think i should just use an \n at end or send back OK or something to confirm it, but that would make it slow if i did it for each value! (and checking only once after all 5 leds are send would mean sending more values until i receive the ok and clearing and sending them again!)
Can you recommend me a better way?
Thanks!
EDIT: Just wanted to say! it's almost done! It does change color when i open chrome, and i think at 115200 baud rate it's fast enough to not notice a delay (although at 9600 i felt like it's slower then my (xxx/xxx/xxx....) protocol but it's better and works at 115200
i will add some basic functions to my python side and add a rainbow effect
I will also add GPU temperature and etc... it's not going to be really hard on linux but windows, im not sure :D

Please edit your question and include the Arduino's setup() function as well.  The code doesn't make sense when includes, variable declarations, and initialization code isn't shown.  That is not to say it will make sense when they are shown :), merely that without them it doesn't.

I don't think you need to worry about speed or data size from what you've described. Prioritise for ease of coding and reliability. Forget all the binary stuff. Send whole bytes. Start with a known sequence, and end with a known sequence of bytes and take advantage of the arduino's readBytesUntil function to find those start and end sequences. This avoids problems with the arduino getting out of sync and picking up the data stream partway through, causing lighting mayhem

I would recommend a similar solution as DaveX with a small modofication.
If you bitmask your LEDS, and leave room for a possible additional 3, you can mask any combination of them in the space of 00-FF. then you could send to the arduino a single string of 0xFFFFFFFF  FF(LED bitmask),FF(Red value), FF(Green Value), FF(Blue Value).
so
LED 1 {00000001 =01} all red {FF0000} would be 0x01FF0000
LED 2 and  4 {00001010 =0A} all green {00FF00} would be 0x0A00FF00
LED 5 and 1 {00010001 =11} all blue {0000FF} would be 0x110000FF
ALL LEDS off would be 0xFF000000
All LEDS onn full white would be 0xFFFFFFFF

my led's are barely going to be the same color, so is it still worth using this? I think sending them in a chunk (but still binarry to reduce the size) will be easier! but im not sure how to convert a hex string to integer in arduino side, also im not sure how i can turn a int into hex string in python but i guess that one will be easy!

AFAIK C++ treats all numeric values as binary to start with, so if you say that rgbRED=127 it's the same as saying rgbRED = 0x7F

Here is a file with some likely colors as well as an interactive RGB slider and LED picker so you can generate the values you would need.. https://marvinfrancois.com/19228.php

Thanks a lot! as I'm inexperienced with these kind of stuff it will take em a lot of time, and googling :) but i will try to do it :) thanks a lot!

btw, just wanted to say, it's underneath my pc pointed to gound, it's a 5 strip led which EACH led has 3 colors, so it can be 5 different colors

Not sure if you're using the neopixel library, but if it's a strip of addressable LEDs, that may make your coding easier. I updated the page I pointed you at with some example arduino code that will update with the values you set, both which led and what color.. you'll still need to write your own logic for when to actually update  and how you are getting your value in. I will work on it for a bit more to see if I can get it to decode the values the way I suggested, but I don't have an arduino with me so can't test the code..

I'd recommend adding digits to a digit register, setting the an R,B,G register with R,B,G and setting values of led a-e to the RBG registers when you get an a-e, ignoring whitespace, and clearing the register otherwise.  So:
 ser.write("xRBGabcde\n")  # clear all the LEDs
 ser.write("x127RBb")       # make led b half-purple, relying on prior state
 ser.write("x255Gc")        # make led c greenish-white


text:
Looking for a wireless soil moisture sensor
I am new to arduino and have a basic question. I want to build a sprinkler controller system for my lawn which would detect moisture in the lawn soil and automatically starts the sprinkler controller to water the lawn when moisture in the lawn soil reaches a certain level. I am looking for soil moisture sensors that would be installed in the lawn soil and wirelessly transmit the moisture level to my arduino in the house. Any ideas where I can find these sensors?

The project is very much possible but it will be easier if you attach the moisture sensor directly to the arduino and add a wifi shield or a bluetooth shield to the arduino itself and make it communicate with computer or phone. You could also program the arduino to directly water the plants if it finds that they dont have much moisture. You will rarely find a sensor that transmits data wirelessly and still be economically feasible. The Sparkfun SEN-13322 moisture sensor is good for the purpose but again connect it to arduino direclty.

so how do I read the moisture in the lawn soil?  I can't put the sensor and arduino in the lawn so not sure what you are suggesting?

@JStorage I cant figure out why you cant put the arduino and the sensor in the lawn. For all such projects that I have seen arduino is encased in a box that protects it from rain etc. and the its connected to the sensor  and kept in the lawn. But also if you want this project to be messy you can actually wire the sensor in the lawn to the arduino inside but that will be a little too messy. Simply keep the arduino in a plastic box and attatch the sensor and keep it in the lawn.

source: Stack Exchange

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

sort: votes


text:
Problem with a digital potentiometer application
I am a beginner when it comes to electronics, coding and things like that (this is practically the first time I have done anything like this), so when building an application that is supposed to vibrate a vibration motor with a strength based on the distance measurement made by the ultrasonic rangefinder, I bumped up with a problem.
The MCP 41010 digital potentiometer seems to let electricity through only when it is given a SPI.transfer(128). Any other number stops the flow of electricity completely.
I have tried some addresses such as 00, 0x00, 0x01 and 0x04 to replace the 0 and the result was the same. With addresses 0x11 and 0x08 the digital potentiometer didn't react at all.
In addition to the code I have here I have tried just copy-pasting some of the tutorials I found from the internet, for example this one Digital Potentiometer not fading LED without really understanding the commands formats thing all that well. With that code I got a vibration that didn't seem to fade in or fade out at all, so the problem remains (I lack a way to properly test that though).
So... what am I doing wrong and how to fix it?
Thank you!

Many tutorials were used when making the code.

#include <SPI.h>

int vcc = 2; // attach pin 2 to vcc
int trig = 3; // attach pin 3 to Trig
int echo = 4; // attach pin 4 to Echo
int gnd = 5; // attach pin 5 to GND

int shortest = 250;
int longest = 12000;

int CS = 10; // for digi pot

void setup() {

  SPI.begin ();
  pinMode (vcc,OUTPUT);
  pinMode (gnd,OUTPUT);
  pinMode (CS, OUTPUT); // for digi pot
  // initialize serial communication:
  Serial.begin(9600);

}

void loop()
{
  digitalWrite(vcc, HIGH);
  // establish variables for duration of the ping,
  // and the distance result in inches and centimeters:
  long duration;

  // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  pinMode(trig, OUTPUT);
  digitalWrite(trig, LOW);
  delayMicroseconds(2);
  digitalWrite(trig, HIGH);
  delayMicroseconds(5);
  digitalWrite(trig, LOW);

  // The same pin is used to read the signal from the PING))): a HIGH
  // pulse whose duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  pinMode(echo,INPUT);
  duration = pulseIn(echo, HIGH);

  if (duration > 200 && duration < 220)
  // Limiting out an unwanted, randomly appearing distance measurement
  // made useless by later code though
    {
     Serial.print("Error ");
     Serial.print(duration);
     Serial.print("\n");

     return;
    }

   // Compressing the result of the distance measurement into the scale of 0 - 128
  if (duration < shortest) duration = shortest;
  if (duration > longest) duration = longest;
  duration = (1.0f-((float)(duration - shortest) / (float)(longest - shortest))) * 128;

  digitalWrite(CS, LOW);
  SPI.transfer(0); // 0x01 and 0x04 seem to "work" too. With 0x11 and 0x08 no voltage goes through
  SPI.transfer(duration); // sending a number from 0 to 128 to the digital potentiometer
  digitalWrite(CS, HIGH);

  Serial.print(duration); // printing the result of the measurement and calculations
  Serial.print("\n");

  delay(100);
}

Digital potentiometers are not a good choice for controlling the speed of a motor. They are designed only for very low current applications - things like setting offset points for op-amps and things like that - things where you would use a small trimmer pot rather than a large power rheostat.
Instead you should be controlling the motor using PWM and a transistor (here is a good tutorial).
But to help you understand the digital potentiometer and so you can work with it better:
Step one is always to read the datasheet.  That details the SPI communication protocol for you so you can know what numbers mean what.
In this case the protocol is made up of two bytes - a command byte and a data byte.
The command byte is made up like this:

As you can see it's in two parts - a command and a potentiometer selector.  So to set the resistance of potentiometer 0 you would need to craft a command byte that had the write command and the code for potentiometer 0.  That would be 0b00010001 or 0x11 in hex.  So your transaction would look like:
digitalWrite(CS, LOW);
SPI.transfer(0x11);
SPI.transfer(duration);
digitalWrite(CS, HIGH);

Another important part of the datasheet is the electrical characteristics.  That is a table that tells you the minimum, typical and/or maximum values for different parameters.  One important one here is the wiper current which it states as being allowed between -1mA and +1mA.  That is the maximum current you are allowed to draw through the digital potentiometer before you risk damaging it.  That is why it's not good for powering things like motors, no matter how small.

I agree with Majenko. What you probably need to control your vibrating motor is a MOSFET to handle the current, and possibly PWM output to manage whether you want weak or strong vibration.

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


text:
Can't make Wee serial WiFi work with Arduino Uno
I'm trying to plug a Wee serial WiFi module on my Arduino Uno, through an XBee shield .

I'm simply trying to make work the example from the library.
All I get is
setup begin
FW Version:
to station err
Join AP failure
setup end

The code i'm using :
#include <SoftwareSerial.h>
#include <doxygen.h>
#include <ESP8266.h>

SoftwareSerial mySerial(3, 2); /* RX:D3, TX:D2 */
ESP8266 wifi(mySerial);

#define SSID "yuflowoffice"
#define PASSWORD "cashless"

void setup(void) {
  Serial.begin(9600);
  mySerial.begin(115200);
  Serial.print("setup begin\r\n");

  Serial.print("FW Version: ");
  Serial.println(wifi.getVersion().c_str());

  if (wifi.setOprToStation()) {
    Serial.print("to station ok\r\n");
  } else {
    Serial.print("to station err\r\n");
  }
  delay(1500);

  if (wifi.joinAP(SSID, PASSWORD)) {
    Serial.print("Join AP success\r\n");
    Serial.print("IP: ");
    Serial.println(wifi.getLocalIP().c_str());
  } else {
    Serial.print("Join AP failure\r\n");
  }

  Serial.print("setup end\r\n");
}

void loop(void) {
}

What can I do?

Do any of the examples work? Although I guess none of them will work as the setup() is the same in each, and that is where the problems begin. It seems like no information is being picked up from the Serial port (Tx/Rx), as wifi.getVersion().c_str() results an empty string. Have you taken note of the issues/points listed on the main page, in particular increasing the size of the buffer?

Also, take a look at Need Help with WiFi Connection. As a sanity check, instead of using the XBee shield  and the sketch, try just using the Wee just plugged into an XBee Explorer/Breakout board, and then use a terminal to send it AT commands to see if it responds appropriately. I have recently ordered one of these devices, but it has not yet arrived, so I can't try any tests of my own unfortunately.

A look at https://github.com/itead/ITEADLIB_Arduino_WeeESP8266/blob/master/ESP8266.h shows that when you pass a SoftwareSerial object to the ESP8266 constructor, a default baud rate of 9600 is also passed to it. Also, the library source file shows that, in the constructor, the begin() method of the SoftwareSerial object you passed (myserial) is called with 9600 baud. Thus, this line in your code:
    mySerial.begin(115200);

is a duplicate, albeit one with a different baud rate, thus rendering the constructor's call of mySerial.begin() useless, since your call comes after the constructor's. If you are certain that 115200 is the right baud rate for the hardware, then you should get rid of the line above and instead pass the baud rate to the constructor like this:
    ESP8266 wifi(mySerial, 115200);

Replace 115200 with any baud rate you discover to be the right one for the AT commands. You also need to uncomment the line in ESP8266.h in your library:
    //#define ESP8266_USE_SOFTWARE_SERIAL

and then save, since you are using SoftwareSerial to communicate with the module.

Thank you for your reply. I tried your code, with every baud rate available, nothing changed for now.

Just to be clear, you got rid of the mySerial.begin() in your code, tried baud rates like i recommended, and uncommented the #define in ESP8266.h and saved it? And your pin connections are like this:               ESP8266_TX->Arduino pin 3
ESP8266_RX->Arduino pin 2
ESP8266_CH_PD->3.3V
ESP8266_VCC->3.3V
ESP8266_GND->GND....you should also get rid of the #include <doxygen.h>

I also recommend you connect the module directly to the Arduino with jumpers; only the pins indicated above should be connected at all, because other pins may be at a level that affect the module's working (e.g. the FW pin, which switches the module between firmware upload mode and normal mode). Also ensure that the slide switch on the module is set to 'work'. You're powering it using the Arduino 3.3V pin, which can't supply > 50mA, whereas the module can use up to 215mA. Try a different power source, maybe Arduino 5V pin connected to the module through LM1117T to bring it down to 3.3V.

Level-shifting the SoftwareSerial TX from 5V to 3.3V, using a voltage divider circuit, may also be needed, since its unclear if the module is 5V-tolerant.

Thank you brianrho. Actually, it was indeed the voltage that blew it up : I think the arduinoxbee shield doesn't make the right wiring for wee serial wifi. So i wired by myself :
3V3 on first pin
D3 on second pin
D2 on third pin
GND to last pin
and all worked fine. on 9600 bauds, i have to precise.


text:
Grab keys from an ordinary USB keyboard
Arduino USB
I want to write an Arduino Sketch (if there is no other possibility it can also be plain c) , to grab keyboard inputs from my ordinary USB keyboard. Preferably without expensive hardware, but as mentioned, if there is no other possibility, this will do it too.
Is this possible with V-USB? I looked a their website, but it seems like this only supports being slave and to imitate a keyboard.

The USB host shield is what you want.

PS2 is a whole lot easier. And most usb-keyboards  tend to also "speak" PS2, but you millage may vary. This way you don't need any USB host shield. See http://playground.arduino.cc/Main/PS2Keyboard and  http://pinouts.ru/InputCables/usb_ps2_mouse_pinout.shtml for the pinout.

@Majenko does it again.  That USB Shield is great.  https://www.arduino.cc/en/Main/ArduinoUSBHostShield

As suggested in the comments, you have two options:
As suggested by Majenko, you can use the Arduino USB Host Shield:

Alternatively you could use a PS2 keyboard instead (as suggested by Gerben). Arduino already has a library to handle PS2 keyboards, so the implementation of it would be easy. For reference (and example program)
playground.arduino.cc/Main/PS2Keyboard
If you do not have access to a PS2 keyboard or just want to use a USB keyboard, Gerben further suggests that most USB keyboards can be converted to PS2 keyboards with an adapter:

The keyboard must be able to support both formats (USB & PS2).
The following webpage shows the connections needed to go from USB to PS2:  USB to PS/2 adapter pinout

Gerben & Majenko, let me know if you would like to post your own answer and I will remove your content from my answer. Otherwise thank you for your suggestions in the comments and I hope I have done your suggestions justice.

I am able to use this library: https://github.com/techpaul/PS2KeyAdvanced and USB's data +/- connected to pins 2+3 of an arduino to read keys on standard keyboards.
keyboard.begin( 3, 2); // D3= data+, D2= data-

A standard keyboard is one which doesn't need a driver to work on any computer. I'd tried several libraries, serial keyboard adapters, and ps2/usb converters, and this method works best. Since the ps2-USB converter is just a physical pin change with no logic, standard USB keyboards just magically with with the PS2 libraries; even caps lock and what not...

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


text:
Could you tell me what is wrong with this Arduino code?
void fn( int pin, int pos)
{
    Servo temp;
    temp.attach(pin);
    temp.write(pos);
    delay(15);
    temp.detach();
}

void loop()
{
    int pos = 0 ;
    for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
        // in steps of 1 degree
        //tmp2.write(pos);
        //delay(15);
        fn(41,pos);
        fn(2,180 - pos);
    }
    for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
        fn(41,pos);
        fn(2,180 - pos);
    }
}

But when I run the code in mega , the servo does not move when attached to pin 2 or 41.
The reason I am creating a function fn , is so that the servo does not stay attached. I want the servo to rotate freely when I am not giving it a pwm signal.

Does it work if you extract the code from the function?

Arrange your code like this:
Servo servo1, servo2;

void setup() {
    servo1.attach(41);
    servo2.attach(2);
}

void loop()
{
    int pos;

    for (pos = 0; pos <= 180; pos++) {
        servo1.write(pos);
        delay(15);
        servo2.write(180 - pos);
        delay(15);
    }

    // 2nd loop here

}

It's rather inefficient to detach a servo after each write and then attach it again for the next write. Simply keep it up all the time.

It would be helpful to briefly describe what is significant about the difference in the arrangement.

I thought the code was short enough so that the difference is obvious. But I will update my answer next year.


text:
Arduino or Raspberry Pi for my project
A brief description of what I'm doing here. I wanna make a pet project, basically a device (be it Arduino or raspberry pi) that I can connect to via bluetooth / wifi (both preferably), that will be connected to a stereo system and allow me to play music. I essentially want to make a wireless sound system in my house.
My question is, is raspberry pi more adequate for my needs? Or would arduino get the job done? I know that raspberry pis are essentially mini computers, so I feel that the raspberry pi would be too much, since all I really need to do is design a bluetooth / wifi interface and send the signal to the aux cable connected to the stereo.
Any help would be really useful here. I've never worked with either/or, and this is my first project with Arduino / Raspberry pi (hello world). Thanks in advance.
EDIT: In response to comments below, a greater idea of what I want to do:
I want to design an item that will appear on local wifi as a sound device. i.e. on an imac / macbook I'd be able to right click on the speaker icon in the upper right and select it there). From there, I'm hoping to stream audio to the device, and have it play to a stereo that the arduino / raspberry pi would be connected to. I'd love to make this universal (i.e. possible to connect via your android phone / a windows machine), but I can imagine that part being a lot more difficult. I'd also like to add bluetooth functionality at some point, but that'd be in the future. Hopefully this gives everybody more of an idea of what I'd like to achieve here! I appreciate all the help so far.

Do you already know how to use wifi, Bluetooth, and audio streaming on Linux?

No I do not. I figure I can learn it. I've also heard, however, that programming in Linux can be somewhat dense, and that learning how to program an arduino is much simpler.
EDIT: I'd also like to point out I'm proficient in several programming languages, including Java, PHP, Swift, Ruby, Python, etc. etc. so I imagine I'd be able to pick up any programming knowledge necessary for either of these devices.

Hate to burst your bubble, but the sentence all I really need to do is design a bluetooth / wifi interface is a big task. Can you elaborate on what your other device is? Android Phone?

Revised my question above to further clarify. Sorry about that, hopefully my revisions give a better idea of what I intend to do with this arduino / raspberry pi.

Writing PulseAudio drivers for Windows and OS X might solve it with probably the least overall work.

Thanks, I'll definitely look into that. Would this be an easier job for arduino then?

AFAIK, there is no PulseAudio server for Arduino. At least, not for anything less than a Yún. So, no.

Well, I guess I'm getting a raspberry pi then. Thanks for the help!

This is definitely not an Arduino application.  There are a number of ways in which the actual implementation of the Raspberry Pi is a less than perfect fit, but it is based on the right general idea and not a bad place to start for a prototype.

Yea that's definitely the general idea I'm getting as well. I ended up ordering an arduino (I'm putting this project on hold for a bit) while I learn a little more about embedded computing, then I'll launch into it. For now I'm just starting with an arduino uno and working my way up :)

I'd definitely prefer the Pi for this project.

As mentioned in the comments, a Raspberry Pi would be superior here.
The standard AVR (not Due/Galileo/Yun) Arduino is superior to the Pi in only one area: IO. It has a 5V logic that's more compatible than the Pi's 3.3V (although you can use a logic level shifter). The Arduino also features more PWM pins and an ADC, along with interrupts. An Arduino also is a lot simpler to use for basic projects, but it becomes impractical when you need more computing power.
A Pi excels at the data-crunching side of things. It can handle a lot more data than the Arduino could ever dream of, and then some! Just to put things in perspective, the Pi has a clock speed of 700 MHz by default and the Arduino Uno has one of 16 MHz (with a less powerful architecture).
For your purpose, the Pi's audio jack and ethernet port are unmatched on the Arduino. Sure, you can get shields that replicate these behaviors, but the Pi's built in functionality doesn't cost extra and it's more powerful.

While it might be an interesting project, the overall quality of the sound generated by such do-it-yourself contraption, is likely to be highly disappointing, because of the not-stellar quality of the final analog stage in the audio output.

Can you explain your answer applies to the Arduino vs the R-PI?

I wanted to warn the OP that his expectation about the final result might be incorrect, because the question asked seems to make certain assumption (that the out come will be meeting his expectations in terms of sound quality).
So, if the desire is to make it produce some sound, yes, it will be successful. But in case the expectation is to produce good_quality sound, he will be probably disappointed and might want to spend his time on some other project.


text:
Will Arduino Pro Mini 3.3V run at half the speed of 5V version?
Provided a very simple sketch like this:
void loop() {
  digitalWrite(1, !digitalRead(1));
}

... should I expect 5V Arduino to run twice as fast as 3.3V, or are there some internal adjustments in place?
Specifically, I'm wondering about Pro Mini and/or Nano boards. The "speed" here is simply the frequency measured on pin 1.
edit:

To clarify, I'm wondering if there might be some behind-the-scenes frequency divider that makes sure Arduino code always run at the same physical speed, even if the actual MCUs run on different clocks.

Possibly the simplest way of forming this same question: Can the sketch above be used to identify 3.3V Pro Mini boards from 5V versions, with the help of a frequency meter?

In theory a 3.3v ATmega could run at 12 MHz in which case it would be 3/4 as fast.  In practice people sometimes run at 16 MHz, which is out of spec for that voltage but sometimes works.  But yes, 8 MHz or half speed is the simple, safe choice.

If the board is running at half the speed (8MHz instead of 16MHz) then everything that isn't based on real time (i.e., millis(), delay() etc) will run at half the speed. It will all take twice as long to do everything.


text:
Using / calibrating pH sensor module
I've bought this sensor module board to link to an Arduino nano: http://www.ebay.com/itm/For-Arduino-Liquid-PH-Value-Detection-detect-Sensor-Module-Monitoring-Controller/321764233326
I assumed the two screws were for calibration (low point + slope), but it seems the operation is different and I can't figure out how. I've got two reference liquids for pH of 4.0 and 7.0. When I put the probe in either one, I get readings. Turning one of the two screws seems to offset the reading so for instance I had pH 4 = 900 and pH 7 = 1000 (0 - 1023 range). Turning one of two screws would lower the value a bit, but it never gets below 500 or so.
So what I can do is measure two points (4.0 and 7.0) and their respective measurement values. That way I could calculate points in between, but as far as I know pH is not a linear scale, but logarithmic. If I get this wrong, the reading might seem right but only show 4.0 and 7.0 correct and not the rest of the values (I don't have 10.0 reference fluid at the moment).
Now onto the second screw, that one at first seemed to do nothing. But then I noticed that it sets some kind of threshold value, turning a LED on the board on and off. That LED seems to be linked to the value being read, but it's further purpose? Calibration? No idea.
Ok so best case someone has an equal module and wants to detail how it works. Otherwise maybe some of you have some bright ideas on what I could try in order to get this to work the way I want it to :)
Update 09-11-2015
Got feedback from the seller. She sent me the following ZIP: http://1drv.ms/1MSk1DX. It contains some files in Chinese but one had sourcecode in it. Tried it on my Arduino but unfortunately the values still don't make much sense. Depending on how I turn the knob on the print, I get values between 9 and 17 for a liquid that's in real life 7.0. I didn't try but doubt that doing a -7 offset is sensible.
The code itself is pretty straightforward, taking a 6-center average of ten consecutive measures. The interesting lines are these:
 avgValue = 0;
 for (int i=2;i<8;i++)       // take the average value of 6 center sample
   avgValue+=buf[i];

 float phValue = (float)avgValue*5.0/1024/6; // convert the analog into millivolt
 phValue=3.5*phValue+Offset;

Maybe someone can make sense of this, because I can't. I don't understand the 5.0 multiplication and the 3.5 after that one. Where do these come from?
Anyway, when I dip the probe into the storage liquid, my normal meter plummets to pH 0.5 whilst the software is giving me 17 (which is a higher value than the one I got from reading my 7.0 liquid). So either my board is broken or this sample code is useless.
Schematics can be found in the ZIP file by the way.
Update 11-11-2015
Did some more experimenting. First I found out that the readings from the module increased for more acidic liquid. So I reversed the value by using
buf[i]=1024 - analogRead(SensorPin);

Ok, now the values made more sense. Then I adjusted the pot to be in the middle of the available range. I dipped the probe in the 7.0 liquid, read the value and adjusted the offset. Then dipped in 4.0, adjusted the pot to match with 4.00, here are the results:
pH 7.0 reference --> 6.27
set offset to: 0.73
pH 4.0 reference --> 5.17
adjusted the pot so value read 4.0
pH 7.0 reference --> 5.86

So as I expected, adjusting the pot also messes up the 7.0 reference measurement. I then though it might be because of the slope of the pot (if there would be any), so I went to the lowest value first to have the least difference. Again the readings:
pH 7.0 reference --> 8.70
set offset to: -1.70
pH 4.0 reference --> 5.17
adjusted the pot so value read 4.0
pH 7.0 reference --> 5.70

The interesting thing here is that the 4.0 value reads 5.17 in both cases, even though the pot was in a different position. I cannot explain why though.
To make sure the probe is fine I re-calibrated my normal pH meter, operates as usual. This one also has two pots, one for 7.0 calibration and one for 4.0 slope. Calibration is done by setting 7.0, then measuring 4.0 and ajusting the slope pot. Measure 7.0 again, change 7.0 pot, measure 4.0 again, etc. until the values match their liquids. Usually takes me about 3 - 4 loops to get it right.
Another update
Took the two containers of reference fluids and started mixing. This gave me measurements in the range of pH 4 - 7.5. Also measured the storage liquid which has a pH of 1.00. Results are in an Excel sheet: http://1drv.ms/1lkAO6e. Next question is how to convert this into a suitable formula?
Update 18-11-2015
Working on @slash-dev's solution, here's what I did:
I first turned the pot all the way down to the lowest value. The readings (for pH 7.0) are as follows: low = 540 and high = 1017. Code as follows:
int rawValue = analogRead(SensorPin);
int buf[10];                //buffer for read analog

for(int i=0;i<10;i++)       //Get 10 sample value from the sensor for smooth the value
{
   buf[i] = rawValue;
   delay(10);
}

// sorting left out to reduce the sample length

int avgValue=0;
for(int i=2;i<8;i++)  // take the average value of 6 center samples
   avgValue += (buf[i] - CENTER);

In this stage I'm printing the raw value of course.
The shorting of the BNC connector I don't exactly understand, should I short the inside (where the pin goes) or the outside of the connector? And short it to the GND? I used the reference solution instead.
Now I added the formula to determine the voltage. For the low value that reads 0.10. I now put in the center value of 540 which brings the voltage reading to 0.0, seems good.
Now for step 2 I placed the probe into the 4.0 reference solution. The voltage now reads 0.48, raw value 637. I start adjusting the pot to where the voltage reads 2.25, takes quit some adjusting. Raw now reads 1000.
Now comes the part I don't exactly get. You say we can now calculate the pH/V, but with what variables? I mean, -3 / 2.25 will always result in -1.33 but shouldn't there be a variable here depending on how far I actually adjusted the pot?
When I now put in the formula to calculate the pH as expected it reads 4.0 for the 4.0 reference solution. But it now screws up the 7.0 solution as we adjusted the pot but didn't compensate for it as far as I see? I also tried the adjusted pH formulas but I guess those are meant for the first code we had and not this adjusted one.
So what am I missing between step 2 and 3 that messes up things here? Also, you state that the inverting by subtracting from 1024 is correct, but when I do that the voltage readings become minus.
Another thing I wonder about; if the pot has to be a slope, shouldn't it be a different one than the one next to it (where a linear one makes more sense)? Cause it isn't, they both read "W103 / 143C". In the meantime, the vendor is kindly sending over a replacement one to ensure it's not a hardware defect somewhere.
Next update: :)
So I now reverted to my original code to try the adjusted pH calculations. I used the 7.0 reference solution to calibrate again and then measured the 4.0 solution. It reads 4.1! Ok, not completely spot on but not bad either. It's a small difference which might as well come from the probe, not the most expensive one.
So I wonder whether we should still try to get the other approach working cause it sounds better (more scientific?) for some reason. Anyway, this is at least a whole lot better than nothing :)
USB power vs linked?
Another strange thing seems to happen when I disconnect the Nano from the USB port of my laptop and instead power it via a Raspberry. I want to use I2C to send the value from the Nano to the RPi. This works, but as soon as I power the nano from the RPi (5V connected to vIn), the calculated pH value drops?

I'm interested in this too, because I might use one of those sensors soon. See if the links on this page are helpful: https://www.tindie.com/products/rezahussain/dormant-labs-ph-module-v2/

There seems to be a remarkable lack of information about these modules, from the eBay vendors I skimmed. I am guessing none of them knows what they do. If you could find a datasheet, that might help. Maybe if you post what sort of chips are on the board it might help narrow down what the adjustments might do.

I've mailed the seller with a request for info, will update when I get it (and write a blog post). As for the chip types, will do but I'll have to check tonight when I'm home :)

@Jerry; thanks, but that's a different module which has software calibration instead of hardware knobs. Not the same and thus not much useful info there.

@Thomas I'm afraid that the "working" state only lasted a very short time. I'm back to having only weird values coming out, this board is just crap is my short conclusion. I'm switching to an Atlas board which should be much much better.

The schematic only shows one trim pot (R23), and it does, as you suspect, set a level for the LED to illuminate.  More of a GOOD/BAD indicator, and is available on pin DO.
The other trim pot is not on the schematic.  Is it marked on the board?  R6, R7, R8 or R9 maybe?  It probably controls the gain on p_AOUT.
t_AOUT is an analog temperature voltage, and appears to measure the temperature of the board.
Edit - official but totally bogus: According to my secret source, you are supposed to put the probe in the pH 7.0 reference solution and, with Offset defined to be 0.0, run the program and display the calculated pH value.  You may need to decrease the trim pot gain to get smaller (the smallest?) numbers.  Now take that displayed value and modify the Offset constant in the sketch to be 7.0 minus the displayed value.  If the displayed value is 8.1,
#define Offset (-1.1)

Build and upload the modified sketch.  This time, put the probe in your pH 4.0 reference solution and adjust the gain pot until the displayed value is as close to 4.0 as you can get.  This will calibrate it for mostly acidic solutions.

Edit 1: Iterate?
It's not clear, but I also wondered if this procedure is supposed to be iterated.  Go back to 7 and make sure that adjusting the gain didn't change Offset. Then test the pH 4 solution again; the gain pot may require a small(er) change. If it seems to be diverging, um, don't do that. ;)  I think it would diverge only if the probe had an inverted response, which would probably mean it's bad.
If you are measuring basic solutions, do the same procedure with reference solutions of pH 7.0 (of course) and a basic reference solution.
Voilà!
NB: For the 7.0 test, you could short the probe pins together. It really should look like a short circuit when pH == 7.0.  If switching to using the real probe in the pH 7.0 solution gives wildly different readings, the probe may be bad.  If you're able to calibrate it, it may be "good enough".

Edit 2: Fix the formulas in the provided sketch.
The schematic shows a non-inverting op amp with PH+ on the input, and p_AOUT on the output.  The (adjustable?) gain is
R9/R8 + 1 = 10k/10k + 1 = 2

The slope of an ideal probe response is -59mV/pH.  You were experimentally getting a negative slope, which agrees with the schematic.  I believe it was correct to "invert" the analogRead value by subtracting it from 1024.  There is no way that the provided code could have worked with a positive slope of 3.5.
The reference voltage provided to the the PH- pin is half the zener diode voltage... which is unidentified.  It could be the very-common 5.1V part, which is essentially forcing PH- to be at
5.1V/((R6+R7)/R6) = 5.1V/2 = 2.55V

I say probably, because you usually want the plus or minus probe voltage swing to have as much room as possible.  This would imply (an ideal) analogRead of pH 7.0 to be
2.55V/5.0V * 1024 = 522

This is the "center" of the probe swing about pH 7.0.
Step 1: Determine the reference voltage
At pH 7.0, print out the raw analogRead return value, before inverting it.  (The pot wiper should be at it's limit.  Which way, I don't know.  Changing the gain pot shouldn't change the analogRead very much at the low-gain end.  If it does change it, turn it to the other extreme.)
As stated before, you can run the pH 7.0 test by shorting the BNC connector pin to the shield or by using your reference solution.  I recommend shorting for now, to eliminate any possible interference from the probe.  It will absolutely determine the offset, but only if the gain is as small as possible.  You have to start here.  Once you know the center reading, you can change the code to display the voltage:
#define CENTER 522
int avgValue=0;
for(int i=2;i<8;i++)  // take the average value of 6 center samples
  avgValue += (buf[i] - CENTER);
float voltage = (((float)avgValue) / 6.0) * (5.0 / 1024.0);

Print this out.  You'd better get something close to 0.0... don't make me come over there.  :)
Step 2: Set the gain pot.
This is determining the slope, but you need to maximize the swing for the most extreme pH you want to read, say 4.0.  Using the 4.0 reference solution, adjust the gain pot so that the displayed voltage is close to +2.5V, say +2.25V to make sure it's not pegged at 1024.  (Let's see, slope is negative, 4.0 is < 7.0, so voltage should increase...)  With that reading, you can calculate the pH/V:
-3pH/2.25V  =  -1.33 pH/V

Step 3: Calculate and print pH
Modify the original computation to use the pH/V slope:
float phValue = voltage * (-1.33) + 7.0;

This is not even close to phValue = 3.5*voltage + Offset.  -_-    I have found several source now that echo my original answer.  Totally wrong, and wrong to the point of misleading.  I do think these steps will do it.  It sounds good in my head, anyway.  :D

Edit 3: "Next question is how to convert this into a suitable formula?"
Ok, if you don't want to fix the formula in the code, you can fit a linear or quadratic curve to your data.  Linear is actually recommended as "good enough", and that is effectively the change suggested in Edit 2.  If we just use your data points, though, this would be the linear approximation:
float adjustedPh = phValue * 1.627 - 2.499;

...and the quadratic approximation:
float adjustedPh = (-0.01796 * phValue + 1.8056) * phValue - 2.94;

A secret source heh? Sounds interesting :) Anyway, I will try this approach. My readings are far off from 7, so that means the offset will be something like 5 or 6, seemed a bit too far off. Also, when I adjust the gain pot for the 4.0 solution, won't that also mess up the 7.0 reading? Wil try tonight when I'm at home.

Yes, I also thought about iteration because that is the way it works for my normal meter. The problem is that this set-up now has two offsets; one as the pot on the board, one in the software. Changing either one for 4.0 messes up the 7.0 just as quickly. The only way this would work is when the software would apply a slope, or the pot would. Neither do as far as I can see. I tried your solution, see update.

@Jasper, you haven't posted in several days, although I see you have visited.  Have you tried "Edit 2" or "Edit 3"?

I'm sorry, you're right. I read your response but didn't get to testing it. Now I have, see update above.

Btw the bounty expired but I'm more than willing to grant it to you. Let me know whether you want to try to get the other solution working and otherwise I'll go and do a new one + answer it.

Sigh.  Edit 2 should have worked if the schematic was right.  It must not be right.  It looks like several manufacturers have simply copied it into their websites.  Your board has an extra transistor that is not on the schematic, so I don't think it's worth messing with the "correct" solution until you know the schematic. If Edit 3 is good enough, why bother reverse engineering this board?  As far as awarding the bounty, this seems like something a moderator would do to avoid a duplicate question and answer.  Could you flag this comment to get their attention?

Done (flag). And you're right. What I have is good enough for now, at least the values are somewhat credible. In due time I'm going to upgrade to an atlas module I think, those should be much better (https://www.atlas-scientific.com/product_pages/sensors/ph-sensor.html)

USB power vs linked

Just to add my 2 cents on your latest update about the USB or 5V from the PI.
You say you connect it to the VIN:

as soon as I power the nano from the RPi (5V connected to vIn), the calculated pH value drops?

If you look at the below image you see that Vin goes to a good old 7805, which needs a IN voltage > 7.5V, thus the output when its connected to the 5V of the PI is going to be very low and thus mess up readings.

I recommend you connect your power from the PI to the arduino's VCC as this is a regulated 5v and doesn't need to be regulated again.

I'm not entirely sure I understand. You state that it should need > 7.5V to work properly. But when I connect the power from the Pi to VCC of the Arduino; how many volts are we talking then? I thought that was 5V but maybe I'm wrong there? Which port from my cobbler should I use to connect to VCC?

From what I read on your edit you were say you connected the Pi 5V to the nanos Vin if that is so, you need to connect VCC - VCC

I don't know if this is a complete answer, but I can't comment yet.
The analogRead function in Arduino which is used by your sensor reads values from 0 - 5V. It divides the values between 0 and 5V in 1024 steps. So it returns a value between 0 and 1023. That is why it is multiplied by 5. It is easier to understand if the calculation is done in reverse order. Example:
analogRead returns 512, so that is on 1024 / 512 = 0,5th part of its range. Multiply that by 5.0 to get the actual voltage. 0.5 * 5.0 = 2.5. It is then divided by 6 to get the average.
I would also change the order of the calculation. The comments say that it calculates the average, but it doesn't it just adds the values. It does divide it by 6 eventually so that does not cause the error, but for readability it is generally good practice to let your code do what the comments say.

Thanks, as this doesn't solve the problem I won't mark is as an answer but it is valuable input anyway. The code comes from the sample, I'll improve it and redo the calculation, indeed seems to make more sense.

One other thing. Are you sure the connections are correct? Your results look a lot like when you are measuring a voltage divider at the wrong resistor. So try inverting your measurements, so: measuredValue = 1024 - analogWrite(pin);

Thank you, used the hint about inverting the measurements. Improved the reading but didn't solve the issue.

As a first approach, I'd collect a number of measurements from each of as many knowns as you can find or make, and plot them for a visual clue to the linearity or not (probably not) of the sensor's output vs. pH. You could try to eyeball-fit a curve to the data; interpolate linearly between sample points if you have enough of them; or run a least-squares approximation fit. The key is you'll need enough data - knowns - to make whatever approach you use give results accurate enough for your intended use. (Obviously this will be different if you just need to know if something is acidic or basic, or you're monitoring tropical fish tanks, etc.)
Update:
If your pH meter is good enough for the fish, and if your sensor is reliably repeatable and sensitive enough, why not check your meter against the two standards, then calibrate the sensor to your meter? Once you're happy with the result, lock down the screws with a dab of nail polish (it's not very tamper-proof but it will be tamper-evident). A pH 10.0 standard won't be very useful to you; at that extreme you'll already know the pH is out and you probably won't care about the exact value. You need your precision between the fish-tolerable limits, close to the pH goal.
In fact, if you trust your meter, you don't even need the standards. In that case you need only make up a few samples as you described, covering the pH range of interest, and use them to calibrate your sensor to the meter.

It's a fish tank indeed. I understand the approach, but I don't have many 'knowns', at the moment only 4.0 and 7.0 reference fluids. I could buy an additional 10.0 but wonder whether that will do it. Another thing I could try is to take tap water and a lemon (or some other acid) to increase the acidity step by step. I have a normal pH meter too which I could use to track the values. I guess the measurements would then tell me more. The issue I have with this is that this still doesn't tell me what the resistors are for and how it should work. Maybe it's just a faulty module, who knows.

I can't ask a question but make sure you're giving it enough power for the heating element, its not much but you never know try a separate power source if you are not.
Now you mentioned the nano, are you using a 3.3v nano or 5V nano?  (the regulator would have a 33 or 50 on it after a letter or two)  if 3.3V and assuming by example code they give the analog output is 5V you'll need a level shifter of sorts to map to 3.3V, then change the calculations to use 3.3 instead of 5 value.    if that's not the case and it's not power or connections then it may be broke or the probe etc.... there's a few variables.

Using a 5V nano. I've linked the module to both the 3.3V and 5V outputs, readings are the same.

USB power vs linked

Read it and use current Vcc instead of 5.0 in your code.
I have the same sensor and have the same problem. I'll be glad if you share full working code in this thread.

Please don't just post a link. The link might go down. If it has useful information in it, summarize it, or state it, here.


text:
Reading digital port with pullup via Firmata
I've got a weird issue, probably something I'm missing but have no clue what.
Got some simple float sensors connected to D2 - D5 on a Nano. Need internal pull-up to eliminate a floating value. Wrote this little sketch to test things:
pinMode(2, INPUT_PULLUP);
int sensorVal = digitalRead(2);
Serial.println(sensorVal);

pinMode(3, INPUT_PULLUP);
int sensorVal = digitalRead(3);
Serial.println(sensorVal);

There's one sensor connected reading HIGH and one reading LOW. This works as expected (displays 1010101010...).
Now I've got this connected to my Raspberry Pi via Bluetooth (BT shield connected to RX/TX) and using Firmata to communicate with the Nano. Code (C#):
_arduino.pinMode(2, PinMode.PULLUP);
PinState result2 = _arduino.digitalRead(2);

_arduino.pinMode(3, PinMode.PULLUP);
PinState result3 = _arduino.digitalRead(3);

Debug.WriteLine($"Result pin 2: {result2} and pin 3: {result3}");

This always gives me two pinstates of LOW, even though I'm absolutely sure it should be reading HIGH as my test sketch is outputting the correct value. This driving me nuts. The Firmata sketch I've got loaded on the Arduino is this one: https://github.com/jsiegmund/submerged/blob/master/src/Arduino%20Sketches/SubmergedCabinetModule/SubmergedCabinetModule.ino. Also tried the latest available version from the firmata repo, doesn't solve the issue. As I've got the BlueTooth shield connected to RX/TX (and wasn't able to change that) I cannot use the serial monitor to provide more debug info. Should anyone know how to change that, would also be appreciated.
Btw for other things, Firmata is working just fine. So the communication itself shouldn't be the issue I think.

Are you sure pinNumber is 2 when you are calling _arduino.digitalRead(pinNumber) ?  and you do have a semicolon at the end of that line right ?

Absolutely sure and yes it's there :) I'll see whether I can create a very simple test app which does the same to rule out interference of other code.

Never mind, I found out what the problem is. The Firmata SDK (Remote Wiring) for Windows just completely ignores the PULLUP pin mode. There are PR (https://github.com/ms-iot/remote-wiring/pull/102) which fixes this, now it's working just fine.


text:
Arduino based small LCD screen with camera video capturing
i have a idea to create a small screen which displays video recorded from arduino with camera. so camera will be back side of human and screen will be at near to eye. human can see the pictures from back side.
i have found https://electronics.stackexchange.com/questions/29139/processing-ntsc-video-feed-for-spi-display
but its not give me a clear idea. is there any one who can advice me for that kind project?

What exactly do you need advice on?

the devices or any projects already done with this idea???

An arduino (at least the classic ATMEGA-based ones) is nowhere near fast enough for this task, and also lacks the necessary memory to hold even a single frame of reasonable resolution video.  One of the ARM-based boards also offered from arduino.cc might barely work, but overall you'd be better with at least a raspberry pi or something even more capable likely based on a smartphone SoC.

@ChrisStratton: You should post that as an answer - it's dead on.

An Arduino doesn't have anywhere near the processing ability to transcode video from a camera unless you had an abysmal frame rate and very low quality. Even then, you would have to add extra storage because the Arduino would be over capacity in a heartbeat.
I recommend converting this project to a higher powered board like the Udoo. I have the Udoo Quad and it's beastly considering its form factor. You're going to need something a lot bigger than an Arduino!


text:
Exoskeleton Motor Control Code
Background:
I have been working on an exoskeleton project with a group of friends, and I need help.  I made another post on the robotics.stackexchange site for the drive system: https://robotics.stackexchange.com/questions/4323/exoskeleton-drive-system-help.  You can also check out our first prototype on youtube: https://www.youtube.com/watch?v=NL_aCwJSRiE&feature=youtu.be
The device is going to be controlled by an iPad that we created via bluetooth.  We are using the adafruit bluefruitLE
We are attempting to control 4 motors (2 knee motors and 2 hip motors) from an Arduino Mega.  We will be using 2 Roboclaw 2x60A motor controllers.  We are trying to get the motors to mimic the graph (see attached).

The graph is in degrees per percent cycle (a gait cycle).  We are using 50 gait cycles per minute for tests but we hope to make it adjustable.
We can change percent cycle to time in milliseconds using dimensional analysis (ie) 50 cycles/min = 8.333x10^-4 cycles/ms  —->  1/8.333x10^-4 cycles/ms is approx. 1200 ms/cycle.  So if you multiply the cycle times 1200 you get millisecond for a certain percent of the cycle (ie) 0.5cycles(50 percent of cycle) * 1200ms/cycle = 600 ms.
We will have a position feedback system incorporated in the drive system but because it is a prototype and I wanted to make the code as versatile as posible I created a function: getDegrees(int jointNum), so if I change the position feedback system I only have to change the getDegrees method.
In order to mimic the graph we broke the graph up into sections.  Each section represents a different velocity.  We are going to run a correction algorithm so far we have just done the P in PID, we have used a modifier of 1.5.  Then we saved the value that the section ended on so next gait cycle when it runs that section the algorithm will start off closer to the target value.
My question:
I need help developing a strategy in order to sync the movement of the 4 joints while running a correction algorithm on each joint individually.  While the device is running we need to be able to constantly check for a bluetooth message from the iPad.  The bluetooth messages come in via SPI from the adafruit bluefruitLE.
What I have done so far:
I have been able to run a single joint by using a while statement (ie)
int i = 0;
void loop(){
targetAngle = nextAngle[i]; //nextAngle is an array of points so nextAngle[0] through nextAngle[1] represents one section of the graph.
i++
if (getDegrees(1)< targetAngle){
double deg = getDegrees(1);
while (deg<targetAngle){
/*
*
*Execute drive code
*
*/
deg = getDegrees(1);
}else{
double deg = getDegrees(1);
while (deg>targetAngle){
/*
*
*Execute drive code
*
*/
deg = getDegrees(1);
}
}
}

The main problem with that code is its like using the delay() function instead of millis() is that it stops the program while its executing the code, and I cannot run multiple motors and check for bluetooth messages.
Major Challenges:
The drive commands must be based off of angle and not time.  It is ok if we tell it do 50 cycles per minute and it does 52 or 48 but its not okay if it only does 97% of the motion.
Possible solutions I have come up:
Using one arduino for each joint, and making them all slaves of a master arduino and the master arduino would act as the middle man sort of between the joints, making sure that they are synced up.  That way each arduino could use code similar to what I have already tried and confirmed to work.  But I would prefer to run it all from one arduino.
Conclusion:
I need help developing a strategy in order to sync the movement of the 4 joints while running a correction algorithm on each joint individually.
Is this the right forum for this question?  Or is it more of a Stack Overflow or Robotics question?
Any help will be greatly appreciated,
--
Joel

Writing an answer now and curious: Why do you prefer delay() over millis()?

I dont prefer delay() over millis().  I was using that as an analogy to show that while loops stop the void loop() function from continuing to loop like the delay() function does.  I prefer millis() over delay() because it doesn't stop the void loop() function.

As your question "to sync the movement of the 4 joints while running a correction algorithm on each joint individually."
Referring to the first part of your question, sync the movement, assume your are doing this at either commercial or university project level, popular practice is to use 'hard real time preemptive operating system".
RTOS, real time operating system, is a piece of system software that coordinates execution of your multi thread user software at precise and predictable time accuracy in order of millisecond.
RTOS involve money and learning time. You may want to continue using the simpler system that you already having now and work in just one joint, hence, no issue of syncing multiple joints. Once you reach some maturity on single joint, then, expand to syncing 4 joints.
RTOS can be commercial with full support or free of charge. Some are dual mode. Same software may either be free or if you choose, can buy commercial full support. There are simple and full-scale implementations where functionality, complexity, learning time and software cost (commercial  or free) varies by huge extend. You will then be more able to choose when you done the above single joint system.
Introduction http://en.wikipedia.org/wiki/RTOS
There are also real time 'executive' (smaller and less functions). For example, ucos II (older and simple version) is used by many people.
Hope it helps

Thanks for the response,  it got me to think more about how to order the processing.  What I am thinking now is to maybe stack the knee and hip graph and cut them up into equal sections.  Then have one angle as a reference and run a while loop based on that angle and run the drive commands for the other joints inside that while loop.  Theoretically when the reference joint gets to its target position the other joints should get there as well, however theoretically is not reality so inside the while loop I will add if statements to make sure the joints don't over rotate.

then after several cycles the algorithm will have hopefully honed in on the target velocity and the other joints will finish closer and closer to the target position.

Does that make any sense?  Do you think that would work?

Human and robot motion is a table of time and many independent TARGET angles at many joints.Example, at time 0,angle0 is 0,angle1 is 10; at time 0.01 second,angle0 is 10,angle1 is 30; at time 0.02sec,angle0 30,angle1 60 Then, feedback_error=actualangle-TAGET_ANGLE Use PID to control Motor based on error. Actual motion is a table of time and corresponding angles. 100 to 300 rows should be enough. One second 10 to 30 steps for smooth motion. Video human and play frame by frame to see, video is 25 to 30 frames per second.

These 'toys' robot comes with pc software for user to enter the 'time table' and the robot will move and dance. Typical has 10 to 20 joints. Comes with pc software for user to enter table and can selectively 'play back' from time point a to b. http://www.dx.com/p/32-ch-servo-motor-control-driver-board-for-arduino-works-w-official-arduino-board-blue-black-206987#.U9kvoECj7qY    http://robosavvy.com/store/images/khr3hvstore.jpg  https://www.youtube.com/watch?v=d3O2dQQTdYM

Here's what I came up with:

You have a certain percent of the gain cycle equal one "step" (step may be a bad term in this situation, but I'm using it because of stepper motors).
You have a blocking function that will move the motors and control all the P(ID) logic

Before this function is called, the main code will use a variable to store the desired time to do the next "step."
It will have a loop with "substeps." So it would look kinda like this:

void function nextStep(int var1, int var2) {
    //Read sensors and put into variables
    until(condition == true) { //Condition to see if the motors are at the right degree
        //Adjust motors not in the right place
        delayAndCheckBT(10); //Look at the bottom for this function
    }
}

You could also have it accept a few percent of variance as tolerance so it's not shakey, but that's more of the PID control than anything. You'll have to make sure that many 'steps' doesn't make the PID controller unstable.

When that code is done, the main function will check to see if the desired time for the next step has passed (or if it's now). If it's passed/now, then it will execute. Otherwise, it will not execute the next step and continue executing the main loop.

Great? No. The problem is you need to check for bluetooth! To do this, I've made two functions:
void checkBT() {
    //Checks BT. Make sure this is non blocking: if you need to, set a few global variables
    //Note this code will get called a LOT, so don't implement any delays or loops: inside here: use millis().
}
void delayAndCheckBT(int timeToWait) {
    unsigned long finishTime = millis() + timeToWait;
    while (millis()<finishTime) {
        checkBT();
    }
}


text:
programming attiny88 & attiny828 with arduino
I found some information that the attiny88 and attiny828 can be programed from an arduino, similar to the programing of the attiny85/45, simply connecting the right pins. https://electronics.stackexchange.com/questions/98970/how-to-program-atmel-attiny88-not-45-or-85
However, what I have not been able to find out are the arduino cores (drivers) for the attiny88 and attiny828.
I wonder if the cores (or drivers) to program the attiny88 and attiny828 from an arduino are available somewhere or would they have to be constructed?.

I have never come across cores for them (not that I've been specifically looking for them though).

88 support seems to exist. See http://arduino.stackexchange.com/questions/12977/attiny88-programming-with-arduino

I would suggest you look into getting a real programmer. As @Gerben says there seems to be support for it, but if you buy an Atmel Programmer or a 3rd party programmer, you will make your life easier. If you plan on doing AVR programming you will eventually graduate from Arduino. There are a number of programmers that can program the ATTiny 88. http://www.atmel.com/tools/STK500.aspx?tab=devices.


text:
Are there any constants for default SPI port pins defined?
I'm writing a library which controls a device using SPI bus. For the communication I need to manually toggle the chip select pin. On most Arduinos SS pin is on D10, but there are also other models where it's different like D53 on Mega. Is there a way to know where it is? Like a global #define? I would like to avoid any pin configuration parameters in my library. At least for default configuration...

As jantje answered (he beat me by a couple of seconds :P ) just use SS; in the files pins_arduino.h (folder \hardware\arduino\avr\variants\your variant) you can see them all. BUT I highly discourage you to use it in your code. You can use it as a default value, but give the user the possibility to change it (otherwise he won't be able to attach two different SPI devices, for instance)

Welcome to Arduino SE Gamadril! About your question, SS pin can be any pin as that pin just needs to be toggled, no high speed data transfer is done with that pin.

Yes there are. They are defined in pins_arduino.h Below the pins for the yun.
// Map SPI port to 'new' pins D14..D17
static const uint8_t SS   = 17;
static const uint8_t MOSI = 16;
static const uint8_t MISO = 14;
static const uint8_t SCK  = 15;

Use SS MOSI MISO and SCK in your code

you was some seconds faster, so get your point :)

This is defined in the platform variant specific file pins_arduino.h in the variants folder (\hardware\arduino\avr\variants). Each platform variant (standard, mega, leonardo etc) gets their pin definitions set here. For instance the mega:
static const uint8_t SS   = 53;
static const uint8_t MOSI = 51;
static const uint8_t MISO = 50;
static const uint8_t SCK  = 52;


text:
Difference between WiFiClient and HttpClient
Apologies if this question appears to be too vague but I would like to know the key differences between these two clients.
While WiFiClient comes pre-loaded with Arduino IDE, HttpClient doesn't. Also, to send HTTP commands to a server (XML/JSON), which one to go for?

WiFiClient provides a raw connection to the internet through a WiFi access point (such as your home router).
HttpClient provides a connection to a web server via an existing Client connection, such as a WiFiClient connection.
So the simplest answer to your question

to send HTTP commands to a server (XML/JSON), which one to go for?

is "Use both".
You use WiFiClient to connect to the internet, then you use HttpClient on your WiFiClient connection to communicate with a website.  As it states in the readme on HttpClient's github repository:

Because it expects an object of type Client, you can use it with any of the networking classes that derive from that. Which means it will work with EthernetClient, WiFiClient and GSMClient.

To understand the concept more fully you will first need to understand the OSI 7-Layer Model which is essential reading for anyone doing anything with networking software.

Can you tell me why aren't they using HttpClient on top of EthernetClient over here: https://gist.githubusercontent.com/jamesabruce/8bc9faf3c06e30c3f6fc/raw/11bbfe799a4122035963f8c6ee5cf3dac670ba7f/Control%20Philips%20Hue%20from%20Arduino%20Ethernet%20Shield

@Hyperbola Because you don't have to use HttpClient. You can do it all yourself manually if you like. HttpClient just saves you the hassle is all.

Thanks @Majenko. I have a question posted too regarding Philips Hue; if you could look at it once.

@Hyperbola I have no clue what a Philips Hue is nor how you communicate with it. I would recommend starting simpler and trying to send a GET request to somewhere like Google before dabbling into unknown boxes of tricks.

As Majenko Said,
WiFiClient is raw in the sense you have to deal with the HTTP protocol stuff yourself, a shot snippet of raw GET request is provided below
  WiFiClient wc;
  wc.print("GET ");
  wc.print(/xml/device_description.xml);
  wc.println(" HTTP/1.1");
  wc.print("Host: ");
  wc.println(selectedDevice->getIp());
  wc.println("Connection: close");  //automatically close Connection
  wc.println("");

each line is terminated with "\r\n", the request is terminated with an empty line
Where as the HttpClient is a library which handle all the low level HTTP protocol stuff and provide simple interface to sent HTTP GET/POST request to any device that support HTTP
HTTPClient http;
http.begin(serverName);
http.addHeader("Content-Type", "text/plain");
int httpResponseCode = http.POST("Hi Sending POST request");
Serial.println(httpResponseCode);
http.end();

To send JSON change the header with the below line
http.addHeader("Content-Type", "application/json");

So the answer is if you want to deal with the low level HTTP protocol use WiFiClient else use HTTPClient

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


text:
Cannot get Serial working
I've bought a module which should communicate via serial RX/TX. The module and code are described here: https://www.dfrobot.com/wiki/index.php/Weather_Station_with_Anemometer/Wind_vane/Rain_bucket_SKU:SEN0186.
I've hooked up everything as described (using an Arduino Nano instead of an Uno, but the rest is the same) and now trying to get things to work. I could not get any decent output. So I decided to switch to a bare-minimum program to read stuff from the serial port in order to see whats going on. I found the following sample: https://gist.github.com/Protoneer/96db95bfb87c3befe46e and implemented this code (only this).
Now what I see is the following:
- With RX/TX connected the wrong way, when I reset the nano, the serial monitor shows me one instance of the string I'm looking for (as described in the module documentation). When connected the right way, the text is not there but that's to be expected as the nano should receive it (and not the serial monitor). This does however prove that the module is actually sending data.
- Serial.available seems to evaluate to 0 all the time, indicating there is no data to be read from the serial line.
So why would Serial.available return 0 even though there seems to be data being sent to serial, as the monitor does show the string I'm looking for with the pins crossed. I have also tried disconnecting the RX line on the module to prevent statements being sent over serial to interfere with the module. The documentation does not state the need to send anything to the module in order to trigger the response. In fact, if you look at the sample code the first interaction with serial (after Serial.begin(9600)) is Serial.available().
Is there anything else I can do from a debug perspective? As you might notice I'm no expert in this stuff.

1st thought, Nano boards come in 3 and 5 volt versions.  The weather station clearly says it is a 5 volt device. Maybe you have the wrong Nano?

No voltage is correct, it's hooked to 5V on the nano.

If the serial terminal is showing you the data then it means you have the TX and RX pins connected the wrong way around.

@Majenko you're right, I was mixing up test results. With the cables connected the right way (RX-TX, TX-RX) I'm actually not getting the contents on the serial monitor. But the end result stays the same: Serial.available returns false and there's no data incoming, even though having the wires the other way around seems to indicate data is being sent.

available() returns count of available data.

Yeah the actual check is Serial.available() > 0 (which returns false).

so you copy data from Serial to Serial echoing them to the device in ascii form? what could be the reaction of the device?

See the gist, the sample code takes whats coming in and prints it, nothing more. But as there is no code coming in at all, there's no prints as well.
If I do Serial.println, is that being sent to the device as well? I have no clue how it would respond to that.

is the RX of the device connected to TX of Nano? then Serial output of Nano is send to the device

Its connected yes, I tried disconnecting the TX from nano (so only TX module => RX nano connected)  but that gives the same result, available return 0.

@Jasper, there is a saying that the RS232 protocol (never mind the physical bit) is the standard that is not a standard. I would recommend you discover this your self by abandoning the embedded world and connect your weather "thing" to a computer with a configurable application such as RealTerm.  Once you figured out the proper configuration you can work your self back to the embedded world.

sorry about that 2400 baud. it is in the other weater station question

So, you have the module connected to the Nano pins 1 and 2, and are also trying to communicate with the PC via the Serial object and serial monitor? There is a USB/serial converter chip on the Nano that is likely conflicting with your module. You can try SoftwareSerial to get a bit-banged serial port for communicating with the module on some other pins.

@josecanuc if you post that as an answer, I can give you the points you deserve :)

how did SoftwareSerial help if you need only RX to connect to the device and you are not sending anything over USB to Uno

@Juraj, pin 0 and 1 are connected to the usb-serial chip with a resistor. The signals can be overridden by something else, but we don't know how strong the tx signal from the module is.

@Jot, if it works in manufactures example, it should be strong enough

I'm also not sure what the issue is. Maybe it's my cheap Chinese nano that's causing the problems. Any way, I know for sure that now it's connected to other pins and using SoftwareSerial, it all works the way it should. I have a "real" uno lying around as well, will give it a go on that one too.

It seems you have the module connected to the Nano pins 0 and 1, and are also trying to communicate with the PC via the Serial object and serial monitor?
There is a USB/serial converter chip on the Nano that is likely conflicting with your module. You can try SoftwareSerial to get a bit-banged serial port for communicating with the module on some other pins.

you mean pins 0 and 1 - RX and TX?

Corrected answer to refer to RX/TX pins 0/1.

How is it conflicting? The device only sends data to RX of Nano. TX is not connected to the device so the Nano doesn't send data to the device, only to USB. Nothing is sent from computer to Nano and it would not stop the device.

@Juraj , well even if nothing is sent from the computer, the tx of the usb-serial chip is connected (with a resistor) to the rx of the atmega chip. josecanuc, for 9600 baud, I prefer the AltSoftSerial.

This indeed fixed it, SoftwareSerial on pins 10 and 11 works as expected.


text:
Timer interrupt won't work if the ISR is not set
I am using an Arduino Mega 2560.
I have a code in a c file, that looks like this:
    #include <avr/io.h>             /* for DDRB, PORTB, etc. */
#include <util/delay.h>         /* for _delay_ms () */
#include <arduino.h>

int main(void){
  DDRB    |= ((1 << DDB7)); // Define pin 13 as output

  noInterrupts();

//set timer1 interrupt at 1Hz
  TCCR1A = 0;// set entire TCCR1A register to 0
  TCCR1B = 0;// same for TCCR1B
  TCNT1  = 0;//initialize counter value to 0
  // set compare match register for 1hz increments
  OCR1A = 15624;// = (16*10^6) / (1*1024) - 1 (must be <65536)
  // turn on CTC mode
  TCCR1B |= (1 << WGM12);
  // Set CS12 and CS10 bits for 1024 prescaler
  TCCR1B |= (1 << CS12) | (1 << CS10);
  // enable timer compare interrupt
  TIMSK1 |= (1 << OCIE1A);
  interrupts();

  while(1){
        asm("nop");
  }
return 0;
}

  ISR(TIMER1_COMPA_vect)          // timer compare interrupt service routine
{
  PORTB ^= ((1 <<  PB7));   // toggle LED pin
  PINB |= _BV(7);
  PINB = PINB | _BV(7);
}

Which is called from an ino file, like this:
    extern "C"
 {
 void foo ();
 }

void setup ()
  {
  foo ();
  }  // end of setup

void loop ()
  {
  }  // end of loop

However, if I set up another timer interrupt (ex Timer Interrupt 0 or 2, the blink will stop happening, for some reason...
For example:
//set timer0 interrupt at 2kHz
  TCCR0A = 0;// set entire TCCR2A register to 0
  TCCR0B = 0;// same for TCCR2B
  TCNT0  = 0;//initialize counter value to 0
  // set compare match register for 2khz increments
  OCR0A = 124;// = (16*10^6) / (2000*64) - 1 (must be <256)
  // turn on CTC mode
  TCCR0A |= (1 << WGM01);
  // Set CS01 and CS00 bits for 64 prescaler
  TCCR0B |= (1 << CS01) | (1 << CS00);
  // enable timer compare interrupt
  TIMSK0 |= (1 << OCIE0A);

Now, the strangest part happens that if all the three (or just the same two) timer interrupts are set, and with everything defined in the INO file, it works fine...
//this code will enable all three arduino timer interrupts.
//timer0 will interrupt at 2kHz
//timer1 will interrupt at 1Hz
//timer2 will interrupt at 8kHz

//storage variables
boolean toggle0 = 0;
boolean toggle1 = 0;
boolean toggle2 = 0;

void setup(){

  //set pins as outputs
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(13, OUTPUT);

cli();//stop interrupts

//set timer0 interrupt at 2kHz
  TCCR0A = 0;// set entire TCCR2A register to 0
  TCCR0B = 0;// same for TCCR2B
  TCNT0  = 0;//initialize counter value to 0
  // set compare match register for 2khz increments
  OCR0A = 124;// = (16*10^6) / (2000*64) - 1 (must be <256)
  // turn on CTC mode
  TCCR0A |= (1 << WGM01);
  // Set CS01 and CS00 bits for 64 prescaler
  TCCR0B |= (1 << CS01) | (1 << CS00);
  // enable timer compare interrupt
  TIMSK0 |= (1 << OCIE0A);

//set timer1 interrupt at 1Hz
  TCCR1A = 0;// set entire TCCR1A register to 0
  TCCR1B = 0;// same for TCCR1B
  TCNT1  = 0;//initialize counter value to 0
  // set compare match register for 1hz increments
  OCR1A = 15624;// = (16*10^6) / (1*1024) - 1 (must be <65536)
  // turn on CTC mode
  TCCR1B |= (1 << WGM12);
  // Set CS12 and CS10 bits for 1024 prescaler
  TCCR1B |= (1 << CS12) | (1 << CS10);
  // enable timer compare interrupt
  TIMSK1 |= (1 << OCIE1A);

//set timer2 interrupt at 8kHz
  TCCR2A = 0;// set entire TCCR2A register to 0
  TCCR2B = 0;// same for TCCR2B
  TCNT2  = 0;//initialize counter value to 0
  // set compare match register for 8khz increments
  OCR2A = 249;// = (16*10^6) / (8000*8) - 1 (must be <256)
  // turn on CTC mode
  TCCR2A |= (1 << WGM21);
  // Set CS21 bit for 8 prescaler
  TCCR2B |= (1 << CS21);
  // enable timer compare interrupt
  TIMSK2 |= (1 << OCIE2A);

sei();//allow interrupts

}//end setup

ISR(TIMER0_COMPA_vect){//timer0 interrupt 2kHz toggles pin 8
//generates pulse wave of frequency 2kHz/2 = 1kHz (takes two cycles for full wave- toggle high then toggle low)
  if (toggle0){
    digitalWrite(8,HIGH);
    toggle0 = 0;
  }
  else{
    digitalWrite(8,LOW);
    toggle0 = 1;
  }
}

ISR(TIMER1_COMPA_vect){//timer1 interrupt 1Hz toggles pin 13 (LED)
//generates pulse wave of frequency 1Hz/2 = 0.5kHz (takes two cycles for full wave- toggle high then toggle low)
  if (toggle1){
    digitalWrite(13,HIGH);
    toggle1 = 0;
  }
  else{
    digitalWrite(13,LOW);
    toggle1 = 1;
  }
}

ISR(TIMER2_COMPA_vect){//timer1 interrupt 8kHz toggles pin 9
//generates pulse wave of frequency 8kHz/2 = 4kHz (takes two cycles for full wave- toggle high then toggle low)
  if (toggle2){
    digitalWrite(9,HIGH);
    toggle2 = 0;
  }
  else{
    digitalWrite(9,LOW);
    toggle2 = 1;
  }
}

void loop(){
  //do other things here
}

Is anybody able to explain why it works in the first case, doesn't work in the second, and in the third, it works as well?

I found out that it's not enough to just define the interrupts, there must also be an ISR method with the compare vector...
  ISR(TIMER0_COMPA_vect)          // timer compare interrupt service routine
{
  PORTB ^= ((1 <<  PB6));   // toggle LED pin
  PINB |= _BV(6);
  PINB = PINB | _BV(6);
}

There was no error at compile, though.

there must also be an ISR method with the compare vector - that's correct - you have told the processor to jump to an ISR vector, and the default vector jumps to the start of your program. There was no error at compile, though. - you have not made any syntactical errors.


text:
Arduino Memory Best Practice
So I have been diving deep into AVR programming and have seen several different ways of defining constants. I know that some of these methods are from "C" and others are from more modern "C++" methods. So my question here is what is the preferred method?
Method 1:
#define MAX_ARRAY_LEN 3

int my_array[MAX_ARRAY_LEN] = {1, 2, 3};

Method 2:
const int MAX_ARRAY_LEN = 3;

int my_array[MAX_ARRAY_LEN] = {1, 2, 3};

In my searches online I have ran across several pages that mention using PROGMEM in the declarations to load the variable into Flash memory instead of SRAM. The thing I am unclear about using PROGMEM is what should be loaded into Flash and what should be loaded into SRAM? Should I be loading all const into Flash? Are there any performance hits using Flash?
Edit
I guess I was not clear on what I was asking. I understand that #define and PROGMEM are not related. My question is there are a couple of methods that can be used to define constants. One is #define (Method 1) and the other is const (Method 2), with the const type comes the PROGMEM, when using Method 2 there are now 2 areas where you can store variables, Flash and SRAM so when do you want to use PROGMEM and when do you want to just leave it, when using method 2? Is there any performance hits when reading from Flash vs SRAM?
I understand that when using method 2 it is now scoped and typed, but are there any other advantages? Are the programs smaller using one vs the other? Are there times that you would want to use one over the other?

Well, as far as I know every compiler is smart enough to understand that the const int field should not be allocated into memory, so I THINK both are the same... You can try to compile both versions and see if the size and the memory is the same or not..

(Duplicate of this.)
In your example, neither definition of MAX_ARRAY_LEN will use program space nor RAM.  If you were to use the definition somewhere, it will certainly use program space in the instruction that uses that constant:
for (int i=0 i<MAX_ARRAY_LEN, i++)
  Serial.print( my_array[i] );

In this case, a CPU instruction will load the constant 3 into a register.  So you can say that the 3 "used" a byte in the CPU instruction, and is part of the program size.  Most people ignore that, because a loading a variable into i uses both RAM and program space.
The primary advantage of using const instead of #define is that the former allows additional compiler type-checking.
C++ has introduced another keyword, constexpr, which tells the compiler that an entire expression can be evaluated at compile time and reduced to a single constant value.  Read all about it here.
To answer your comment, #define's are not stored anywhere.  They are a simple string substituion that happens before the compiler processes the C++ code.
When you build your sketch, the source files are processed in several phases.  First, there's a preprocessor phase that consumes all the lines that start with '#'.  The results of the preprocessing are sent to the C++ compiler.  The compiler will see all the included files inline, and all #define's will be substituted.
UPDATE
For example, #define XXX 3 will cause the preprocessor to replace all occurrences of XXX in the C++ file with 3.  The C++ compiler will never see XXX, it only sees 3.  You could do a search and replace with your editor, and the C++ compiler would not know the difference.  (Well, there are a few more tricks the preprocessor can do for you, but you only asked about defining a numeric constant.)  The generated code would be identical.
There is no "global space" for #define symbols.  There is a "dictionary" in the preprocessor that is used to perform the substitution, but that is ephemeral.
PROGMEM is not related to #define or const at all.  It is an attribute of a variable that indicates it is to be stored in FLASH, not RAM.  I think the key is that #define is just string substitution, but const is a C++ attribute of a C++ variable.  All of these are equivalent:
#define MAX_ARRAY_SIZE 3
const uint8_t maxArraySize = MAX_ARRAY_SIZE;
int array[ maxArraySize ] = { 1,2,3 };

#define FOO 1,2,3
int array[] = { FOO };
const uint8_t MAX_ARRAY_SIZE = (uint8_t) sizeof(array)/sizeof(array[0]);

#define MAX_ARRAY_SIZE goofyNameThatMeansNothing
const uint8_t MAX_ARRAY_SIZE = 3;
int array[ MAX_ARRAY_SIZE ] = { 1,2,3 };

#define BAR = { 1,2,
int array[] BAR,3};
#define MAX_ARRAY_SIZE sizeof(array)/sizeof(array[0])

I hope that last 2 goofy examples help illustrate what a #define is... string substitution.
The PROGMEM attribute is a separate thing.  It can only be added to C++ variables, and it now requires the variable to also be const.  Extending the above, you could do this:
#define MAX_ARRAY_SIZE 3
const uint8_t maxArraySize = MAX_ARRAY_SIZE;
const int array[ maxArraySize ] PROGMEM = { 1,2,3 }; // a flash array, not RAM

#define FOO 1,2,3
const int array[] PROGMEM = { FOO };
const uint8_t MAX_ARRAY_SIZE = (uint8_t) sizeof(array)/sizeof(array[0]);

#define MAX_ARRAY_SIZE goofyNameThatMeansNothing
const uint8_t MAX_ARRAY_SIZE = 3;
int array[ MAX_ARRAY_SIZE ] PROGMEM = { 1,2,3 };

#define BAR PROGMEM = { 1,2,
const int array[] BAR,3};
#define MAX_ARRAY_SIZE 14

Again, in that last goofy example I used PROGMEM in the #define BAR, but it's just some characters as far as the #define is concerned.  And the last define is just plain wrong, but it will compile.
Because there is no validation of a string substitution, it is usually better to use a const type var = value; that can be validated by the compiler, both when it is defined and again when var is used in some context.
UPDATE 2
You say,

with the const type comes the PROGMEM

Not really.  const is the "read-only" attribute, and the compiler enforces that.
PROGMEM tells the AVR compiler that, if storage is required for this variable, put it in FLASH memory (a special address range) instead of RAM (a different address range).  Because of the AVR architecture, you must access FLASH differently, with special instructions.  The avr.pgmspace.h include file has some routines (macros and inline assembler) for reading from those address spaces.
I emphasized the "storage space required", because the compiler can optimize away the storage.  The literal 3 constant MAX_ARRAY_LEN does not need any storage space.  For this example program:
const int MAX_ARRAY_LEN PROGMEM = 3;

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

  Serial.println( MAX_ARRAY_LEN );
}

void loop() {}

This is the generated code:
  Serial.println( MAX_ARRAY_LEN );
156:    50 e0           ldi r21, 0x00   ; 0
158:    63 e0           ldi r22, 0x03   ; 3
15a:    70 e0           ldi r23, 0x00   ; 0
15c:    82 e2           ldi r24, 0x22   ; 34
15e:    92 e0           ldi r25, 0x02   ; 2
160:    f7 c2           rjmp    .+1518  ; 0x750 <_ZN5Print7printlnEii>

The compiler knows that storage is not required.  The value "3" is pushed directly onto the stack at program location 0x158.  It did not go to RAM nor FLASH (PROGMEM) to load a 3 into a register, and then push that register's value onto the stack.
The compiler knows the value, so it uses the "immediate" form of the instruction to push the 3.
However, for this program:
const int MAX_ARRAY_LEN PROGMEM = 3;

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

  Serial.println( (uint16_t) &MAX_ARRAY_LEN, 16 );
}

void loop() {}

The following code is generated:
  e4:   03 00           .word   0x0003  ; ????
     .
     .
     .
  Serial.println( (uint16_t) &MAX_ARRAY_LEN, 16 );
 158:   50 e0           ldi r21, 0x00   ; 0
 15a:   64 ee           ldi r22, 0xE4   ; 228
 15c:   70 e0           ldi r23, 0x00   ; 0
 15e:   82 e2           ldi r24, 0x22   ; 34
 160:   92 e0           ldi r25, 0x02   ; 2
 162:   b5 c2           rjmp    .+1386      ; 0x6ce <_ZN5Print7printlnEji>

Because I took the address of MAX_ARRAY_LEN, the compiler knew that it had to have storage... in order for it to have an address.  The compiler dutifully locates it in the program space, at 0xE4.  You can see that address being pushed onto the stack at 0x15A.
Without the PROGMEM attribute, the following code is generated:
  Serial.println( (uint16_t) &MAX_ARRAY_LEN, 16 );
 156:   50 e0           ldi r21, 0x00   ; 0
 158:   60 e0           ldi r22, 0x00   ; 0
 15a:   72 e0           ldi r23, 0x02   ; 2
 15c:   84 e2           ldi r24, 0x24   ; 36
 15e:   92 e0           ldi r25, 0x02   ; 2
 160:   b5 c2           rjmp    .+1386      ; 0x6cc <_ZN5Print7printlnEji>

This is a RAM address, 0x200.  Long before setup, a 3 is copied from the program space into RAM.  It is using both program space and RAM.
But this is only because I took the address of MAX_ARRAY_LEN.  In almost all cases, you will be using these as scalar values.  The compiler will not allocate any storage space for them, and the PROGMEM attribute is irrelevant.
You have another question:

Is there any performance hits when reading from Flash vs SRAM?

Yes.  Reading from flash takes twice as many CPU cycles.  It's always a juggling act.  If you need to squeeze every cycle out, make sure your constants do not even need storage space (i.e., don't take their address).  And if it's a PROGMEM array or structure, consider using a cached value (i.e., loaded into a RAM array or structure).  Sometimes you don't have a choice.  If you are out of RAM, you will have to load them from PROGMEM every time you need them, with a small penalty.  RAM, SPEED, SIZE... pick two.

Thanks, I saw the link that you posted but what that did not touch on was the usage of PROGMEM and what should be stored where to utilize memory as efficiently as possible. #define's are stored in global space but there is no way I know of to tell where to put that memory when "used"

@AndyBraham, the link did not touch on PROGMEM because it is not related to #define.  UPDATE section added above to explain the difference between preprocessing (string substitution) and compiling (variables, storage and PROGMEM).

Thanks a bunch for trying to help, I guess I was just not clear on what I was trying to get at. I updated my question hopefully you can shed a little light....

@AndyBraham, UPDATE 2 added.  Basically, constants rarely use storage space.  PROGMEM only applies to things that actually use storage.

Awesome, now you hit on what I was trying to get at. Now one more thing. While researching this topic there was some mention about LCD projects and storing the Strings that are displayed in a structure or array like you mentioned in your "Update 2". Do they suggest this because the String Arrays are large and when used they take up much more memory than other types? Or is this one of those things that "Work" but there are better ways? I am trying to find out what the best approach is. As you know the internet is full of obsolete information.

@AndyBraham, Be careful, when you use the capitalized String, it usually refers to the Arduino class, which you should never use. I will assume you are referring to "C strings", aka char arrays.  Here is a good example of strings in PROGMEM. As explained above, const vars, including char[], will be both in RAM and FLASH if storage is required.  Since most string ops use the starting address of the string, they require storage. PROGMEM saves RAM, but the same speed penalty applies. No Big Deal


text:
Manual Arduino Due Installation
Not sure if this is the right place to post this.
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 it just says there is an error downloading the files.
Is there a way to manually install the board support for the DUe, or must it be done automatically, connecting through the internet?

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

UPDATE 2
Question has been answered:
https://github.com/arduino/Arduino/issues/3358
Many thanks to Federico Fissore!

I just installed the Due fine using the board manager. What is the problem you are having?

If there is an error, you should report it to Arduino github https://github.com/arduino/Arduino/issues

@Majenko 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 change that.

@FedericoFissore I will try there as well, but if you have an answer, can't you just it here?

@Tom I don't have an answer, but if you are TheForeignMan on github, then we are already chatting :)

@FedericoFissore Haha yes! I'll update the question.

I have a repository that has the fix to the board issue with DUE.. here is the link...https://github.com/LadyLexi/arduino-platform-sam

I had the same problem described above.
Error downloading http://downloads.arduino.cc/packages/package_index.json
I solved the problem, just deleting the temporary file: "package_index.json.tmp"


text:
Interfacing accelerometer LSM303DLH with Arduino UNO using I2C
I am trying to connet a tri axis accelerometer LSM303DLH to arduino UNO using the libraries taken from the following links (https://github.com/adafruit/Adafruit_LSM303DLHC and/or https://github.com/ryantm/LSM303DLH) but none of them work.
Using the following connection:
SCL on A5,
SDA on A4,
Vin on 5V,
Gng on Gnd.
I should be able to see the values of the accelerometer but the serial monitor is empty.
I've tried inserting a few print in the libraries to understand where the execution stops, basically after a Wire.endTrasmission() the program doesn't go forward.
How can I connect the accelerometer using I2C?

Please post the code

Are you using one module bought from Adafruit?
Make sure the connection is correct between the sensor and Arduino, then make sure that the script doesn’t get stuck when the Wire is begun.
Another thing that you need to make sure, is to have the correct address, it depends from board and each one can have a different one or a selector.
This can be helpful to figure out what the wiring is


text:
Event driven programming
I have ran across a couple of different event libraries that are available on the AVR and Andruino but I am not sure which one is the best option. What I would like to do is design my program in a event driven style but not sure how to go about this.
I have a project that I need to keep lightweight but also in this program I have several actions that can be happening at any given time i.e. Digital Inputs being triggered and I need to run code whenever these events happen.
I found the QP Framework that looked promising but I wanted to get some feedback from some others that might of used this type of library before and might be able to provide some examples and maybe some experiences.
Another site I found here and lists all sorts of different libs

Cosa has to be the most fully featured of them all that I know of. Amazingly powerful and filled with drivers for everything you can imagine.  It's a completely different way of programming the Arduino - you'll have to unlearn everything you know ;)

@Majenko I had asked about OOP Programming (http://arduino.stackexchange.com/questions/17964/oop-vs-inline-with-arduino) does Cosa handle the problem with dynamically allocating memory?

It's pretty much all static objects.

@Andy Braham, if I may add to Majenko's statement, It's pretty much all static objects, which is a good thing.  As stated in the OOP thread, dynamic memory on small AVRs is not a good choice.  (It's something you have to un-learn.) Besides determinism, static binding also allows fantastic compile- and link-time optimizations.

Is the code that needs to be run interruptable?  How much latency can you tolerate?

You may want to take a look at LMX by David Anderson A Light-Weight Multi-Tasking Executive.
He has a very good set of videos on the code that he did for Dallas Personal Robotics Group (DPRG).
The specific videos for LMX are:

David Anderson on Robotics Software - part 1
David Anderson on Robotics Software - part 2