text:
Arduino time(milli) and pressure sensor
I've succeeded to get an Arduino to work with a pressure sensor.
What I want to do is

when I put pressure on the sensor, after 5 minutes the led lights on.
it starts over again if there's no pressure on the sensor.

Here's the program:
// FSR is verbonden met analoog 0
int fsrAnalogePin = 0;
// De LED is verbonden met pin 11 (pmw pin)
int LEDpin = 11;
// De analoge waarde van de fsr spanningdeler
int fsrWaarde;
// De helderheid van de led tussen 0 en 255
int LEDhelderheid;

void setup() {
    // start de serial monitor
    Serial.begin(9600);
    pinMode(LEDpin, OUTPUT);
}

void loop() {
    fsrWaarde = analogRead(fsrAnalogePin);
    // print ‘Analoge waarde’
    Serial.print(“Analoge waarde = “);
    // print de fsrwaarde op de monitor
    Serial.println(fsrWaarde);

    // maak van getallen tussen 0 en 1023 getallen tussen 0 en 255
    LEDhelderheid = map(fsrWaarde, 0, 50, 0, 255);
    analogWrite(LEDpin, LEDhelderheid);
    delay(100);
}

I've got this for the pressure sensor... now I need to combine it with 5 minutes and the led lights on when it's reached that 5 min of pressure.
i managed to do this but it aint enough...
unsigned long currentTime;
unsigned long startTime;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  currentTime = millis();
  startTime = currentTime;
}

    void loop() {
  currentTime = millis();
  // put your main code here, to run repeatedly:
  Serial.println(currentTime);
  delay(1000);

  if(currentTime-startTime > 6000) {
Serial.println("1 minuut voorbij");
startTime = currentTime;
  }
}

Try this:
unsigned long pressureOnTime; //millis() time when pressure switch is first turned on

const unsigned long ledOnAfterTimeThreshold = 300000; //5 minutes * 60 sec * 1000 mSec
int pressureThreshold = 1; //minimum analog reading from pressure sensor considered to be "on"

const int fsrAnalogePin = 0;
const int ledPin = 11;

int ledState = LOW;
int pressureState = LOW;

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

void loop() {
    checkPressureSwitch();

    //do other stuff here
}

void checkPressureSwitch() {
    if( analogRead(fsrAnalogePin) >=  pressureThreshold )
    {
        handlePressureOn();
    }
    else
    {
        handlePressureOff();
    }

    digitalWrite(ledPin, ledState);
}

void handlePressureOn() {
    if ( pressureState == LOW )
    {
        //pressure switch was off, but is now on
        pressureOnTime = millis();
        pressureState = HIGH;
    }

    else if ( millis() - pressureOnTime >= ledOnAfterTimeThreshold )
    {
        ledState = HIGH;
    }
}

void handlePressureOff() {
    ledState = LOW;
    pressureState = LOW;
}

thanks but im getting a void error(void handlePressureOn) on the line; else if ( millis() - pressureOnTime >= ledOnAfterTimeTheshold ) and it says that (ledOnAfterTimeTheshold) was not declared

There was a typo: change ledOnAfterTimeTheshold to ledOnAfterTimeThreshold. I edited the answer as well.

thank you again but when i do the SerialMonitor i dont see anything doing...maybe its how i put my board check this link is how i put my board; http://www.thuisexperimenteren.nl/science/Arduino/Arduino_FSR/FSRsensor_bb2.jpg

Hi, please read and try to understand the code.  Notice that I didn't put any Serial.print() statements, so of course there is nothing happening in the serial monitor.  Your questions states that you want the LED to be the indicator and this code should do that.  If you want something output in the serial console, add some print statements.

sorry im a rookie...but im going to try to do it on my board see if it works and understand

The very simplest way - not necessarily the best way - is something like:

Keep re-reading the pressure sensor until it senses pressure;
Read millis(), add 300000 (# of msec in 5 min) to it's value, and store that;
Keep re-read millis() until it returns a number >= to that stored value;
Read the pressure sensor;
If it senses pressure,
  turn on the alarm;
  do nothing, forever;
Otherwise, start over again;

It isn't the best way, because the Arduino does nothing else for the 5 minutes until the final sensor check. But as you're learning, you probably don't need it to do anything else - for now. When that time comes, there are better ways than dedicating your processor to watching the clock. But this will get you started, and you may figure out some of those ways on your own, by then. Good luck!
Update: I realized my answer does not account for the possibility that pressure is released from the sensor and reapplied some time later, if both occur within the 5 minute wait. How you treat that situation will depend on the needs of your application (which I'm guessing is for you to learn to work with time and physical data). I'll leave that as a further exercise for you.


text:
Which shield to use for GPRS?
I'm planning to build a device that would read some sensor data and send it via GPRS, eg. once per day. (Not that original, yeah.) But my problem is choosing a GSM/GPRS shield.
The official shield has a nice interface for doing an HTTP POST/GET. OTOH, the shield seems to be sold out (and would be quite expensive anyway).
There seem to be other shields available, but their code examples tend to look quite hacky: the device waits for an arbitrary moment and then hopes that the server is done. That's IMO both inefficient or unreliable.
My question: which GSM/GPRS shield would you recommend, with these features:
a sane library w/ examples, such as the official onean external antennabonus: a competitive priceanother bonus: hopefully a "real" shield, so no soldering required and a few pins still easily usable for the sensors.

I ended up ordering an Elechouse board which uses the M10 chip. Found one on eBay for 59 USD. It appears to work fine with the official library.
As the manual says, it must be given external power - the USB cable isn't enough!

did you find the elechouse board reliable, does it send/receive gprs ok?

Is 2G supported in your country? At least in europe there are plans to switch off the 2G network and the module you chosen does not support 3G

That library should work with pretty much anything that has the M10 module on it.
I only have experience with the SIM900 modules. Found the cheapest one on EBay.
While interfacing with these things can be a challenge at first, you really just need to read the manual for all the AT commands and execute them. I've written a couple of functions that may help:
Note: you may safely replace all instances of DEBUG_PRINT and DEBUG_PRINTLN with Serial.print and Serial.println.
SoftwareSerial SIM900(7, 8);

/*
    Sends AT commands to SIM900 module.

    Parameter   Description
    command     String containing the AT command to send to the module
    timeout     A timeout, in milliseconds, to wait for the response

    Returns a string containing the response. Returns NULL on timeout.

*/
String SIMCommunication::sendCommand(String command, int timeout) {
    SIM900.listen();
    // Clear read buffer before sending new command
    while(SIM900.available()) { SIM900.read(); }

    SIM900.println(command);

    if (responseTimedOut(timeout)) {
        DEBUG_PRINT(F("sendCommand Timed Out: "));DEBUG_PRINTLN(command);
        return NULL;
    }

    String response = "";

    while(SIM900.available()) {
        response.concat((char)SIM900.read());
        delayMicroseconds(500);
    }

    return response;
}

/*
    Waits for a response from SIM900 for <ms> milliseconds

    Returns true if timed out without response. False otherwise.
*/
bool SIMCommunication::responseTimedOut(int ms) {
    SIM900.listen();

    int counter = 0;
    while(!SIM900.available() && counter < ms) {
        counter++;
        delay(1);
    }

    // Timed out, return null
    if (counter >= ms) {
        return true;
    }
    counter = 0;
    return false;
}

I would recommend the official Arduino GSM shield.

Which one do you recommend? Care to elaborate?

Arduino GSM shield. I am using this, Its working fine and its a official Arduino shield.

Sadly the official Arduino GSM shield is now discontinued.

LinkitOne - ok not a shield but rather a compatible Arduino controller board with built-in GSM/GPRS/GPS/Wifi. comms library doesn't have as many diagnostic methods as e.g. the Adafruit one, but it was easy to setup and reliable. Main downside of the LinkitOne was that it uses a different processor from Arduinos so many of the Arduino libraries aren't compatible e.g. for I2C devices.
Adafruit Fona SIM808 2G Shield version. shield layout but stackable headers have to be bought and soldered seperately. Default pinouts work with Uno, but mods required for Mega. Library has lots of handy diagnostic methods (battery voltage, signal strength, etc). worked with giffgaff prepaid SIM but not vodafone for some reason. SMS worked ok. I could connect to GPRS but getting html from a website didnt' work.
DFRobot SIM808 GPS/GPRS/GSM Shield - Pre wired wirth stackable shield connectors, instructions to upload code and run the device are convoluted and vague. I Wasn't even able to get a basic connection to the Arduino to work. Either the library is very buggy or my device was faulty.
SEEEDStudio 113030009 GPRS Shield with Antenna and External SIM Holder V3.0 I'll probably tets this next..
Official Arduino GSM board DISCONTINUED
Sparkfun GSM/GPRS Module - SM5100B DISCONTINUED

source: Stack Exchange

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

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

sort: votes


text:
strange behaviour of dtostrf()
I'm trying to program a little bit in Arduino, but I'm stuck with probably something trivial.
This is what I have:
char ang[3], lat[9];
dtostrf(GPS.angle, 3, 0, ang);
dtostrf(GPS.latitude, 9,5, lat);

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

I would expect the following in the serial monitor:
5111.60160
267
-------

But instead, I'm getting this:
5111.60160
2675111.60160
-------

So it looks like the ang holds both the angle and the latitude....
Why is this happening? And how can I solve this?
My goal is to make one big string, comma separated, from the data stored in GPS

You might need to null-terminate the string. The last byte should be \0

Euuh, ok. How do I do that???

Increase the size of the arrays by 1 and then do ang[3] = '\0';

Your arrays are both too short for the strings they're meant to hold. In particular, ang has three digits and only three bytes. The string-terminator, NUL, ends up in the 1st byte of lat. Since you generated the ang string first, lat over-wrote ang's NUL character, effectively getting appended to ang.
The lat string will need at least (10+1) bytes; ang will need (3+1) bytes, counting only the actual data in your question.
I make it a habit to declare string arrays just as I wrote the sums above, to make it clear that I've counted both the contents and the NUL byte, so:

char ang[3+1], lat[10+1];

I doubt that you need to specifically add the NUL terminator; it would quite unusual (counter-conventional) for a C/C++ function that generates a string to leave off the terminator (except in a few special cases).
Try increasing just your array sizes first; it'll probably work.

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


text:
GSM library getIPaddress returns local network address 10.X.X.X
I have a Mega board and a GSM shield. I'm using Arduino's example "TestWebServer". The serial monitor shows that the GSM is connected, and returns a IP.
However, the IP is always 10.X.X.X. Isn't that a internal network IP address? How should I get the SIM cards IP? Thanks!

The SIM card does not have an IP address. When the data connection is made to your GSM APN it is assigned an IP in a similar way to DHCP. Often the address is the same after the first connection as the service provider will link that to your SIM for audit purposes. If you setup a private APN then you can arrange to have specific range allocated to your SIM card(s). This is normally only done for security of volume reasons.

I end up using bot.whatismyipaddress.com API to query the external URL address..... Plus just found out that my SIM cannot not work as a web server....


text:
Arduino Mega's 4 Serial Ports?
I have been using only Arduino Uno. Now I am about to buy Mega. But a question rises. Are those 4 Serial Ports of Mega controlled still through one usb cable?

Don't overlook the ChipKIT uC32. It roughly compares to the Mega at a glance, but has 2x the RAM and 10x the clock speed. Plus tons of I/O.

No. If Arduino ATmega microcontroller supports more than a single UART, then only the first one is available through the standard USB connection. Other UARTs use their own pins that you have to connect to on the board. Mind you these pins are TTL logic serial and need a converter for RS232 or similar. It is possible to use a second (third, ...) TTL-serial to USB cable to access the port on your PC.


text:
How to disable Arduino Yun to work as Access Point and set it to work as needed?
I am using Arduino Yun and I would like to disable it to work as Access Point. That is, I don't want that it is displayed in the list of available networks.
Then I would like to set and use it (separately) in the following scenarios:
a) Arduino Yun connected just over a given Wi-Fi network (Ethernet connection disabled).
b) Arduino Yun connected just over Ethernet (Wi-Fi connection disabled).
How can I make it?
Note: In my previous attempts I tried to customize and/or disable someway the Wi-Fi connection (through the LuCI panel) in order to reach what I am looking for but in all of these cases I had to restore my Arduino Yun from scratch because it did not work anymore.

Yun expects wifi to be working and, if it's not, it will reboot itself after 60 seconds and return in access point mode.
In order to disable this check, edit file /etc/rc.local and turn wifi-live-or-reset into #wifi-live-or-reset (with a starting #).
Once done, use LuCI (the advanced configuration panel) to configure network interfaces.


text:
What are the main differences between the Arduino Tre and the Intel Galileo?
I'm looking to find a suitable board for a robot I'm developing (it'll involve computer vision, else I'd be using my Arduino Micro) and I've come across two possibilities: The Intel Galileo and the Arduino Tre.
Now as I understand it, the Intel Galileo has a 400MHz Quark processor, whilst the Arduino Tre has 2 processors, an onboard 16MHz standard ATmega32u4 with the Arduino bootloader and then another 1GHz TI processor with Linux installed on it.
However, I'm not sure of the differences between both products, as price estimates appear to place them at approximately the same price (around $70) and the Intel Galileo doesn't appear to have any real advantage over the Arduino Tre (except for a full x86 instruction set).
Does anyone have any information on comparison of the two boards so I can make a better informed decision?

Biggest difference IMHO: Tre hasn't been released yet!
Besides that, there are a few different things that you should compare. Not much is available about the Tre as of now, but I'll update this post when it's released.

Basic Specs: [First sub-bullet is TRE, second Galileo; better spec in bold]

Microcontroller:

Texas Instrument Sitara AM3359AZCZ100 (ARM Cortex-A8) (1 GHz, 32 bit), Atmel ATmega32u4 (16 MHz, Secondary, found on Leonardo)
Intel® Quark SoC X1000 (400 MHz, 32 bit)

RAM:

512 MB SRAM (2.5 KB ATmega32u4)
512 MB SRAM

Pins

14 Digital 5V, 7 of which are PWM, 6 analog 5V (additional 6 multiplexed) (32u4); 12 Digital 3.3V, 4 of those are PWM (Sitara)
14 5V digital, 6 of those are PWM, 6 analog 5V

Networking:

Ethernet 10/100
Ethernet 10/100

USB port:

1 USB as slave, 4 USB host ports
Up to 128 devices as host, 1 USB slave

Video

HDMI (1920x1080), LCD header
None that I can find

Audio

HDMI, stereo analog audio input and output
None that I can find

MicroSD card

Yes
Yes

PCIe Slot

No
Yes

Sources (I combined a bunch of data for this): Galileo & Tre

Conclusion: If you need a board before the Tre comes out, which seems to be soon (Spring 2014), Galileo is your only option. Other than that, the Tre seems to be better all around in most aspects, minus the PCIe slot. I can't comment on power, but it seems like the Tre will be able to supply 4x the power per pin than the Galileo. The Galileo is getting older, and it doesn't seem like the Galileo can provide full Linux support like the Tre will.
Personally, I'd wait for the Tre. The only thing I can think that the Galileo would be better for would be either a.) lower power usage or b.) the PCIe slot for a WiFi adapter that works decently. The second one could be solved by doing a common WiFi router hack.
If you need a lot of processing power without the need of low latency, you should conciser sending data to a computer to process.

Source

Source

+1. galileo has no video, and is supported on the INTEL form, not the arduino's official. Alsto tre as A LOT more pin :)

I was disappointed that the Galileo had no analogue audio output. The 3.5mm jack is for serial comms.


text:
Changing pins used in ArduinoISP example
I have built my own ATTiny programmer, but made a bit of a mistake along the way - I didn't align the headers properly, and now instead of them plugging into pins 10, 11, 12 and 13 as per the ArduinoISP example - they now plug into pins 8, 9, 10 and 11.
If I use some jumper cables to wire the pins to match the ArduinoISP example, it all works fine, meaning the wiring on the actual board is OK, however, I want to be able to just plug my board I have made straight in, and thus need to get the bootloader burning and the uploading to work via pins 8, 9, 10 and 11 instead.
I have tried modifying the example myself by replacing the references to RESET, MOSI, MISO and SCK with my own pin numbers, but this doesn't seem to suffice. When I try to burn the bootloader now, I get the following error:
avrdude: stk500_program_enable(): protocol error, expect=0x14, resp=0x50
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

avrdude: stk500_disable(): protocol error, expect=0x14, resp=0x51

If I try to upload a sketch using my version which has the custom pin numbers, I get this error:
avrdude: stk500_getsync(): not in sync: resp=0x00

The wiring of my programmer is the same as can be found here: http://highlowtech.org/?p=1706 except I want the programmer sketch to work with different pins.
Thanks

You can't change the pins.
ArduinoISP uses the SPI interface on pins 10-13 which is provided by the underlying AVR hardware.

As a practical matter, you're much better off correcting things so you're using the original pins, which correspond to hardware SPI.
However, it's not terribly hard to implement SPI in software (at a lower performance, of course):
static uint8_t
SPITransfer(uint8_t out)
{
    uint8_t in = 0;
    for (int i=0; i<8; ++i) {
        digitalWrite(MOSI, (out & 0x80) != 0);
        out <<= 1;
        digitalWrite(SCK, HIGH);
        in = (in << 1) | digitalRead(MISO);
        digitalWrite(SCK, LOW);
    }
    return in;
}

There are several SPI modes, but this implements the one used for ISP.


text:
How do I initialize a servo object in my own library?
I'm trying to make my first library for Arduino and want to use a servo object in my library. How can I do this?

Welcome to Arduino SE! First of all, getting frustrated isn't going to get you anywhere. I understand it can be painful coding sometimes with problems, but it's easier to get help with a calm tone. Secondly, do you mean like creating an object like Servo myservohere; within your library and using that object within your main code?

Yes! Is that possible?

Important point: do you intend to create a C++ library i.e. with one -or more- class, which would then encapsulate a servo object?

It would be good to post some code to your question, showing what you have already done so far, and more importantly what part of the current code you would want to put into your own library.

Considering the fact you are a young hobbyist, I will first ask the question "do you absolutely need to write a library?". Writing libraries for Arduino generally comes in a second stage after writing several sketches, and it requires a good understanding of the language used by Arduino (C++).

This should give you an idea of how to create a custom library which you can use in your project. I actually compiled it with Arduino IDE 1.0.5 on Mac OsX.
I did not run it on an Arduino board, but have similar code in a production project, that works just fine.
Start a new Arduino sketch, name it as you like.
Go to the folder where you saved that file.
Add a new file called MyServoLib.h parallel to your main project file.
In your main file, include the servo library from Arduino and your custom library like so:
#include <Servo.h>
#include "MyNewLib.h"

If you close and reopen your project, it the Arduino IDE will automatically load your custom library file as well.
Copy the following simple stub code into your custom library file:
#ifndef MY_SERVO_LIB_H__
#define  MY_SERVO_LIB_H__

#include <Servo.h>
#include <Arduino.h>

class MyServoLib
{
public:

  MyServoLib()
    : _servoPin(9)
    , _attached(false)
  {}

  void attach()
  {
    if (_attached)
      return;

    _attached = true;
    _servo.attach(_servoPin);
  }

  void detach()
  {
      if (! _attached)
          return;

      _attached = false;
      _servo.detach();
  }

  void setPin(int pin){
    _servoPin = pin;
  }

private:

  bool _attached;
  Servo _servo;
  int _servoPin;

};

#endif

Your main file should look like this:
#include <Servo.h>
#include "MyNewLib.h"

// use your custom lib here
MyServoLib myServo;
int MyServoPin = 5;

void setup(){

  pinMode(MyServoPin, OUTPUT);
  myServo.setPin(MyServoPin);
  myServo.attach();

  // your additional setup code here
}

void loop(){

  // your main code here

}

That's it!
Upload it to an Arduino board and give it a try. The servo won't move, but it should get powered on.

This is a simple solution. All you need to do is declare a global variable (i.e. make it accessible everywhere in your sketch), and then add some additional code to "share" the servo between the different parts of the code.
Code you need:
Your library:
Servo servoname;
void foo() {
  //Some code here!
}

void bar() {
  //More code here!
}

The methods foo() and bar() are irreverent to the code, you just need to declare it.
Your library header file (name.h):
extern Servo servoname;

All you need to do then is import your new library and use servoname. You will have to still call servoname.attach([pin]); before you can use the servo, but then you just need to use the servo.
Source

when I do that I get an error: "Servo does not name a type"

@Zack Have you imported the servo library into your library? I can't help you without any code...

If your question is about including library A inside library B and then including library B in your main program, then you need to be aware of a limitation of Arduino IDE (discussed in this answer to a similar question).
Arduino IDE (at least 1.0.x, I have not checked with 1.5) for an obscure reason will not include libraries included by other libraries.
The only way to work around this issue is to include ALL libraries (direct and indirect) in your main program file (.ino file):
// Needed by library "B"
#include "A.h"
// Needed by your program
#include "B.h"

void setup() {
    // You can use B stuff here
}

void loop() {
    // You can use B stuff here
}

Another workaround is to trash Arduino IDE and use a better (I mean a real) IDE: many good options have been discussed in this question.


text:
Arduino stopwatch, which board to use?
I am planning on making a simple stopwatch with:

A display
One or two additional buttons to start the stopwatch and stop the stopwatch and
maybe reset it.

The problem is that it has to be as small as possible.
With all those different Arduino boards out there, I don't know which one I should buy (mini, micro, nano, ...).
I am not sure how many pins I need for the LCD since I have read that in fact not all pins are mandatory for the LCD. I have done something earlier with an LCD and I found the pot meter for the LCD contrast level a bit of waste of space. Could I just replace it with a certain resistor or something?
How many pins in the end would I need and which board would be fitting for this little project?

http://www.atmel.com/devices/ATTINY26.aspx

What LCD are you planning to use?  What power supply?  If you can still get one, I think the Arduino framework has mostly been ported to the ATmega-based AVR Butterfly, which might have everything you need.

It should be a pretty basic LCD like this for example.
I guess a 9V battery would be the maximum I could use as size.

That's not really a basic LCD. Common, sure, but not basic. And I'd use two Lithium cells instead of a 9V.

Ok thanks for the comment. I will look into a more basic LCD. Which arduino board would you recommend?

If you need it to be as small as possible then you should look at using bare AVRs instead, such as the ATtiny26. It has more than enough pins to interface with both a HD44780-based LCD and all the buttons you need.

How small is "as small as possible" This is possible but perhaps not what you meant.

By that photo you posted, you pretty much answered a decent part of your question. You'll need six pins for the LCD, and one or two for the button. That means that you need a total of 8 pins. That Uno pictured has 20 (analog can act as digital, too).
As far as the boards, if you feel comfortable with some extra work, I'd recommend an ATtiny. From what I can find, it seems like you can drive a LCD with a 44 or an 84 (similar, but the 84 is more powerful).

Source for image and how to program chip. I'm not going to go into the details for this method, as the link has the necessary files...

That's the smallest way to do this*, however, if you want to use a real Arduino board, then I'd recommend the Micro for a few reasons.
First of all, it has the newer ATMEGA32u4 chip, found on the Leonardo. I do not recommend the Mini because, although it's the smallest of the three, it doesn't feature on board USB. You would have to buy another adapter to program it. If you're already using a breadboard, the extra 2cm (or so) is worth not having to spend more to buy both of those components. The Nano is the equivalent of the Mini, only with USB. Also, the Nano and the Micro are roughly the same size, one a little bit longer and one a little bit wider.
However, the Nano and Micro are roughly the same as far as processing power, so I'd recommend that, if you can get one significantly cheaper, to go with that. It doesn't really matter that much.
*If you're building this on a breadboard, it won't be smaller. If you're transferring to a PCB, then you should use an ATtiny.

As far as the pot goes, I'd recommend getting a trimmer with an equivalent value. Some of them are very small, as I have one that fits on the USB connector part of my thumb drive. They need a screwdriver to adjust, but I would recommend it. I've had issues moving it from a dark room to in the sun and not being able to see it clearly. Spend the two cents and the 2 cm2 and have an opportunity to change it if needed.
For the battery, I would recommend any rechargeable battery (under ~3.5V) if and only if you add a proper chip to not waste energy in the conversion. I talked about this in this post.

Looks like I'm going with a cheap copy of the Arduino Micro or Nano, depending which one is the cheapest. I don't have a lot of knowledge in electricity so the ATTiny 44 looks a bit too complex for me.


text:
Turning a DC motor a set number of Rotations using an encoder
I'm using an arduino UNO, and i want to turn a motor a set number of revolutions, i'm trying to read the clicks of the encoder which has a resolution of 360 clicks/ revolution, my logic is that i count the number of clicks until i get to the desired number which represents the the number of revolutions * the resolution of the encoder:
1 revolution ==> 360 clicks
5 revolutions ==> 360*5 (desired number)
i'm a beginner with arduino so here is my code:
volatile int counter=0;
int motor=5;  // motor is connected to pin 5

void setup(){
  pinMode(motor,OUTPUT);
  attachInterrupt(0, count,RISING); // attaching encoder on interrupt 0
}

void loop(){
  while(counter< 360*5){
    analogWrite(motor,255);
  }
}

void count(){
  counter++;
}

This code is not working at all, how can i fix it?

You need to tell us what "not working" means. If it doesn't do what you want, What does it do?

There are so many potential issues here: oscillating across encoder ticks even when the motor is "not moving" (most designs of that resolution interpret a quadrature encoder to give a reversible count and ignore stationary vibration), integer overflow in a relatively small number of revolutions, lack of allowance for acceleration and deceleration.  What type of motor/reduction?  Is the encoder directly on the motor or after the reduction?

Thanks for the response, i'm actually simulating this on Proteus, and since it is an ideal model i don't think it has these issues, i'm really skeptical about the code itself, i think there is something wrong about how i'm reading the encoder.

How do you drive the motor? Directly attached to Arduino or using a motor driver (shield)?

I'm simulating this on ISIS, i'm using a mosfet to drive the motor.

You never tell the motor to stop.
void loop(){
   while(counter< 360*5){
     analogWrite(motor,255);
   }
   analogWrite(motor, 0); //add something like this or whatever could stop it
   //you may want to disable the counter now too
}

However, even with that change you are likely a long way from having a working, or at least reliable system - see other issues in my comment on the question.

But i'm telling it to run only if the condition is right, nevertheless i tried it and it isn't working.

The output statement you are using continues to generate the requested output until countermanded.  So if you want to stop doing that, you must tell it to do something else instead.  But there are doubtless other problems as well.

Since the Encoder resolution is high, the Arduino Uno misses some pulses hence you could not get the accurate reading from it. You could use the hardware quadrature decoder in Arduine Due board which can easily read the encoder values.
Here is a code which can only be executed in arduino Due to Read one quadrature encoder.
How to configure 2nd Quadrature Decoder IO pins in Arduino IDE


text:
Analog average sample wind speed sensor
I have wind speed sensor that can measure max speed upto 30 m/s with analog out put 0-5v. I have simple code calling from the loop. When I put the wind speed average code, the web server is not working and it just hangs. If I comment out web server it's working fine. Let me know What makes my web server hang or not get connected. Is there any way I can change average taking code?
Working code should like below:
if wind speed exceed 30 m/s
   mode =stow
else
   mode =track

My code. And how can write average of windload of day to SDcard
#include"wind.h"
#include"mode.h"

float sampleAverage(void)
{
  float accumulator = 0;
  for (int i = 0; i < SAMPLE_COUNT; i++)
  {
    accumulator += sample[i];
  }
  return accumulator / SAMPLE_COUNT;
}

void Wind_calc()
{

  static unsigned long lastSampleTime = 0;
  unsigned long currentTime = millis();

  // check if time for new reading
  if (currentTime - lastSampleTime >= SAMPLE_RATE)
  {
    lastSampleTime = currentTime;
    int sensorValue = analogRead(SENSOR_PIN);
    float voltage = sensorValue * (5.0 / 1023.0);
    /* Serial.print("voltage: ");
     Serial.println(voltage);*/
    // add the newest reading at the oldest pointer
    sample[sampleIndex] = voltage;
    // advance to next index which is now oldest
    sampleIndex++;
    // check for and handle rollover
    if (sampleIndex == SAMPLE_COUNT)
    {
      sampleIndex = 0;
    }
    // the sample array now contains the last ten readings
    // sampleIndex now points to the oldest reading
    // it will be replaced with the newest next time

    float average = sampleAverage();
    /*Serial.print("average:");
     Serial.println(average);*/
    Wind_Speed = (6 * average);
    Wind_Kmph = 3.6 * Wind_Speed;
    /*    Serial.print("Wind_Speed:");
     Serial.print(Wind_Speed);
     Serial.println("m/s");

     Serial.print("Wind_Exceed_count:");Serial.println(Wind_Exceed_count);Serial.println(".................");
     Serial.print("Wind_Kmph:");
     Serial.print(Wind_Kmph);
     Serial.println("KMPH");
     */
    if((Wind_Speed>4.0)&&(Stow_flag==0))
    {
      Wind_Exceed_count=Wind_Exceed_count+1;

      //Serial.println("Wind_Exceed_count");Serial.print(Wind_Exceed_count);
      if(Wind_Exceed_count<5)
      {
        Stow_flag=0;
      }
      else
      {
        Stow_flag=1;
        MODE=STOW;
      }

    }
    else
    {
      Redo_Wind_calc();
    }

  }

}

void Redo_Wind_calc()
{
  //  Serial.println("Wind_Exceed_count");Serial.print(Wind_Exceed_count);
  if(Wind_Speed>4.0 &&Stow_flag==1)
  {
    Wind_Exceed_count=Wind_Exceed_count+1;
    if(Wind_Exceed_count<=10)
    {
      MODE=STOW;
    }
    else
    {
      MODE=TRACK;
      Wind_Exceed_count=0;
      Stow_flag=0;
    }

  }
}

void loop()
{
 Wind_calc();
webcontrol();
}

void webcontrol()
{

//Web control function are defined here

}

Where is the sample[] array declared?

also thisseems to be the working code. Add the bad code!

And where's your setup() method? You seem to be missing a lot of code: can you add more please?

How much is SAMPLE_COUNT?

What arduino board is being used? I find that some webserver code takes up a lot of the SRAM and in an UNO this leaves very little space for other code.
To save SRAM use the F macro on all the Serial.print statements that have quoted text. i.e:
Serial.print("Some text you want output");

This takes up SRAM when running. 1 byte per letter and space.
Serial.print(F("Some text you want output"));

This takes up no SRAM as it is stored in program space and is makes a big difference.
Search for a freeRam() and use that in debugging your sketch to see how much free space you have.
Relevant question: What can I do if I run out of Flash memory or SRAM?

Is there way to checkSRAM memory occupied. I am using arduino UNO board .I have removed all Serial.println statement from my code

@AMPS this question has already been asked (and answered): http://arduino.stackexchange.com/questions/763/im-using-too-much-ram-how-can-this-be-measured

this is a really useful tip, though I think there are limitations with what can go in the argument of F(), for example this
Serial.print(F((int)lsm.magData.x*100));  seems to cause a compile error. I suppose I could do the maths in a seperate line and then offer its result to F as a variable, but I guess that would probably defeat the obejective of using less memory?


text:
Can the official arduino GSM shield library be changed to work with hardware serial on mega
I have a complex requirement that uses a number of libraries that depend on timing I.e. OneWire. When using the official GSM shield on a mega, it loads a version of software serial to talk to the GSM. I want to make it use a spare hardware serial port on the MEGA for more timing stability. How should I modify the GSM library to (optionally) auto detect a MEGA and then use a nominated serial port. I am happy to jumper the correct pins from the mega serial hardware port to the bent outwards pins 2 and 3 of the GSM shield ( pin 2 is already bent out if you use a MEGA anyway).

#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) ........

Thanks this will work but I need the help to change the libraries from using the customized soft serial code and allow me to select a hardware serial pin...this is the real issue.

AltSoftSerial might help you in this case...

Do you absolutely need to use serial0?

I don't think AltSoftSerial is going to help as the goal seems to be to use one of the additional available hardware serial ports.  Presumably going through the library and changing the soft serial references to the alternate hardware serial object would do it (or putting the selection inside ifdef's as jippie proposed).

Did somebody managed to do this?

Before we start, note that it might not be the right pinout for the GSM shield to use a hardware serial port on the Mega. Beware of some nasty wiring.
Poking around on Github, I found this is the directory for the GSM library. Ladies and gentlemen, it's time to break something important get our hands dirty! Draw your  chairs close for a tale of touching code you shouldn't touch!
Click on the src folder to open it up. When I first opened this up, I was somewhat scared by the number of files. However, I had a plan:

Find the name of the SoftwareSerial instance. I'm guessing that they would use only one object to do this to prevent redundancy. In addition, I'm going to guess that most serial data is handles though a single file, but I'll have to confirm this.
Remove instances of the SoftwareSerial Object.
Clean up any remaining issues with the "port"

After more poking around, I noticed that the library actually uses a unique version of the SoftwareSerial library, so it will be even harder to do this. Yay us! On the upside, we know exactly what code to replace. Fasten your seatbelts, this is about to get pretty nasty.
Okay, take a step back here and figure out what we want to modify. First of all, it's a terrible idea to modify the libraries directly in the directory that the Arduino IDE uses.
So, if you were to make a copy from the src folder for the GSM library into the Arduino "libraries" folder, it wouldn't be enough. The Arduino IDE would get confused when there would be two identical header files to use. You will need to rename the main header file and use just that one instead to include into your projects. In addition, most of the files in the library probably reference that file, so make sure to rename any references within the library to that one file. A quick CTRL + SHIFT + F on the Atom text editor will search the entire project I'm working on. I'm not entirely sure if a folder name would mess up the Arduino IDE, but it'd be a good idea to rename the folder to whatever your library is called, at least for readability purposes.
Before we continue, let's make sure that the library still compiles without us playing with the code. Import the new library into a basic GSM example sketch and see if it compiles and works normally.
It compiles? Great. Let's go on!
The file that does serial is the GSM3SoftSerial.cpp file. Without actually porting it, I can't give you a ton of advice here. Look through and see when variables are created, used, and modified. If you're not sure, I'm in chat sometimes: feel free to ask there on minor questions and ping me with @AnnonomusPenguin or leave a comment on this post.
I'd also advise to leave everything in there that you're not sure of, make sure it works with hardware serial, and line by line start removing that variable and see if anything breaks. A great too for this would be to use a tool like Git/Github (or other version control software) to help you revert changes that broke something or to see, overall, what you've changed.
So, after replacing the code inside the functions (finalWrite, the ISRs, and the begin/clear seem like the ones you should touch), compile the code and see if it works!


text:
How to compile code for the Arduino Due?
I have set up Eclipse to compile for the Arduino Due using all the tools shipped with the Arduino IDE 1.5.6-r2. It compiles without errors, but when uploaded, the Arduino does nothing, and isn't recognized on the computer. It then has to be reset manually using the erase and reset buttons.
There is one static library (ArduinoDueCore) consisting of the Arduino library (core), and other code (Atmel found in lib). The other Eclipse project is the TestProject. It contains one file blinking an LED on pin 13. All the files from the Arduino library are there.
This is the output from Eclipse compiling the library itself: (excerpt of only one of each type of command)
18:31:36 **** Build of configuration Release for project ArduinoDueCore ****
make all
Building file: ../src/lib/variants/arduino_due_x/variant.cpp
Invoking: ARM Sourcery Linux GCC C++ Compiler
arm-none-eabi-g++ -DUSB_PRODUCT="Arduino Due" -DARDUINO=156 -DUSB_MANUFACTURER="Unknown" -DARDUINO_ARCH_SAM -DARDUINO_SAM_DUE -D__SAM3X8E__ -Dprintf=iprintf -DF_CPU=84000000L -DUSB_VID=0x2341 -DUSB_PID=0x003E -DUSBCON -I"/home/kim/workspace_juno/ArduinoDueCore/src/core" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/Device/ATMEL" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/CMSIS/Include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/libsam/include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/libsam" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/Device/ATMEL/sam3xa/include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/variants/arduino_due_x" -Os -ffunction-sections -fdata-sections -Wall -Wa,-adhlns="src/lib/variants/arduino_due_x/variant.o.lst" -fno-exceptions -fno-rtti -w -c -g -fmessage-length=0 --param max-inline-insns-single=500 -nostdlib -MMD -MP -MF"src/lib/variants/arduino_due_x/variant.d" -MT"src/lib/variants/arduino_due_x/variant.d" -mcpu=cortex-m3 -mthumb -o "src/lib/variants/arduino_due_x/variant.o" "../src/lib/variants/arduino_due_x/variant.cpp"
Finished building: ../src/lib/variants/arduino_due_x/variant.cpp

Building file: ../src/lib/libsam/source/adc.c
Invoking: ARM Sourcery Linux GCC C Compiler
arm-none-eabi-gcc -DARDUINO=156 -DARM_MATH_CM3 -DUSB_MANUFACTURER="Unknown" -DARDUINO_ARCH_SAM -DARDUINO_SAM_DUE -D__SAM3X8E__ -Dprintf=iprintf -DF_CPU=84000000L -DUSB_VID=0x2341 -DUSB_PRODUCT="Arduino Due" -DUSB_PID=0x003E -DUSBCON -I"/home/kim/workspace_juno/ArduinoDueCore/src/core" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/Device/ATMEL" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/CMSIS/Include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/libsam/include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/libsam" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/Device/ATMEL/sam3xa/include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/variants/arduino_due_x" -Os -ffunction-sections -fdata-sections -Wall -Wa,-adhlns="src/lib/libsam/source/adc.o.lst" -w -c -fmessage-length=0 --param max-inline-insns-single=500 -nostdlib -std=c99 -MMD -MP -MF"src/lib/libsam/source/adc.d" -MT"src/lib/libsam/source/adc.d" -mcpu=cortex-m3 -mthumb -o "src/lib/libsam/source/adc.o" "../src/lib/libsam/source/adc.c"
Finished building: ../src/lib/libsam/source/adc.c

Building file: ../src/core/USB/HID.cpp
Invoking: ARM Sourcery Linux GCC C++ Compiler
arm-none-eabi-g++ -DUSB_PRODUCT="Arduino Due" -DARDUINO=156 -DUSB_MANUFACTURER="Unknown" -DARDUINO_ARCH_SAM -DARDUINO_SAM_DUE -D__SAM3X8E__ -Dprintf=iprintf -DF_CPU=84000000L -DUSB_VID=0x2341 -DUSB_PID=0x003E -DUSBCON -I"/home/kim/workspace_juno/ArduinoDueCore/src/core" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/Device/ATMEL" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/CMSIS/Include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/libsam/include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/libsam" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/Device/ATMEL/sam3xa/include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/variants/arduino_due_x" -Os -ffunction-sections -fdata-sections -Wall -Wa,-adhlns="src/core/USB/HID.o.lst" -fno-exceptions -fno-rtti -w -c -g -fmessage-length=0 --param max-inline-insns-single=500 -nostdlib -MMD -MP -MF"src/core/USB/HID.d" -MT"src/core/USB/HID.d" -mcpu=cortex-m3 -mthumb -o "src/core/USB/HID.o" "../src/core/USB/HID.cpp"
Finished building: ../src/core/USB/HID.cpp

Building file: ../src/core/cortex_handlers.c
Invoking: ARM Sourcery Linux GCC C Compiler
arm-none-eabi-gcc -DARDUINO=156 -DARM_MATH_CM3 -DUSB_MANUFACTURER="Unknown" -DARDUINO_ARCH_SAM -DARDUINO_SAM_DUE -D__SAM3X8E__ -Dprintf=iprintf -DF_CPU=84000000L -DUSB_VID=0x2341 -DUSB_PRODUCT="Arduino Due" -DUSB_PID=0x003E -DUSBCON -I"/home/kim/workspace_juno/ArduinoDueCore/src/core" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/Device/ATMEL" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/CMSIS/Include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/libsam/include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/libsam" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/Device/ATMEL/sam3xa/include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/variants/arduino_due_x" -Os -ffunction-sections -fdata-sections -Wall -Wa,-adhlns="src/core/cortex_handlers.o.lst" -w -c -fmessage-length=0 --param max-inline-insns-single=500 -nostdlib -std=c99 -MMD -MP -MF"src/core/cortex_handlers.d" -MT"src/core/cortex_handlers.d" -mcpu=cortex-m3 -mthumb -o "src/core/cortex_handlers.o" "../src/core/cortex_handlers.c"
Finished building: ../src/core/cortex_handlers.c

18:31:39 Build Finished (took 2s.811ms)

Here is the project itself:
18:33:42 **** Build of configuration Release for project TestProject ****
make all
Building file: ../src/TestProject.cpp
Invoking: ARM Sourcery Linux GCC C++ Compiler
arm-none-eabi-g++ -DARDUINO=156 -DUSB_PRODUCT="Arduino Due" -DARDUINO_SAM_DUE -D__SAM3X8E__ -DARDUINO_ARCH_SAM -Dprintf=iprintf -DF_CPU=84000000L -DUSB_MANUFACTURER="Unknown" -DUSB_VID=0x2341 -DUSB_PID=0x003E -DUSBCON -I"/home/kim/workspace_juno/ArduinoDueCore/src/core" -I"/home/kim/workspace_juno/TestProject/src" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/libsam" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/Device/ATMEL" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/variants/arduino_due_x" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/CMSIS/Include" -I"/home/kim/workspace_juno/ArduinoDueCore/src/lib/CMSIS/Device/ATMEL/sam3xa/include" -Os -ffunction-sections -fdata-sections -Wall -fno-exceptions -fno-rtti -c -fmessage-length=0 --param max-inline-insns-single=500 -nostdlib -g -w -MMD -MP -MF"src/TestProject.d" -MT"src/TestProject.d" -mcpu=cortex-m3 -mthumb -o "src/TestProject.o" "../src/TestProject.cpp"
Finished building: ../src/TestProject.cpp

Building target: TestProject.elf
Invoking: ARM Sourcery Linux GCC C++ Linker
arm-none-eabi-g++ -T"/home/kim/workspace_juno/ArduinoDueCore/src/lib/variants/arduino_due_x/linker_scripts/gcc/flash.ld" -L"/home/kim/workspace_juno/ArduinoDueCore/Release" -Wl,-Map,TestProject.map -lm -lgcc  -Wl,--cref -Wl,--check-sections -Wl,--gc-sections -Wl,--entry=Reset_Handler -Wl,--unresolved-symbols=report-all -Wl,--warn-common -Wl,--warn-section-align -Wl,--warn-unresolved-symbols -Wl,--gc-sections -mcpu=cortex-m3 -mthumb -o "TestProject.elf" -Wl,--start-group  ./src/TestProject.o   -lArduinoDueCore -Wl,--end-group
Finished building target: TestProject.elf

make --no-print-directory post-build
/home/kim/arduino-1.5.6-r2/hardware/tools/g++_arm_none_eabi/bin/arm-none-eabi-objcopy -O binary TestProject.elf TestProject.bin

Invoking: ARM Sourcery Linux GNU Create Listing
arm-none-eabi-objdump -h -S TestProject.elf > "TestProject.lst"
Finished building: TestProject.lst

Invoking: ARM Sourcery Linux GNU Print Size
arm-none-eabi-size  --format=berkeley TestProject.elf
   text    data     bss     dec     hex filename
  10396      24    1188   11608    2d58 TestProject.elf
Finished building: TestProject.siz

18:33:43 Build Finished (took 308ms)

Here is the upload command: (removed readWord, go, write and writeWord lines)
-i -d --port=ttyACM0 -U true -e -w -v -b ${project_loc}/Release/${project_name}.bin -R

Set binary mode
chipId=0x285e0a60
Connected at 921600 baud
Erase flash
Write 10420 bytes to flash

[                              ] 0% (0/41 pages)
[=======                       ] 24% (10/41 pages)
[==============                ] 48% (20/41 pages)
[=====================         ] 73% (30/41 pages)
[============================= ] 97% (40/41 pages)
[==============================] 100% (41/41 pages)
Verify 10420 bytes of flash

[                              ] 0% (0/41 pages)
[=======                       ] 24% (10/41 pages)
[==============                ] 48% (20/41 pages)
[=====================         ] 73% (30/41 pages)
[============================= ] 97% (40/41 pages)
[==============================] 100% (41/41 pages)
Verify successful
Set boot flash true
Device       : ATSAM3X8
Chip ID      : 285e0a60
version()=v1.1 Dec 15 2010 19:25:04
Version      : v1.1 Dec 15 2010 19:25:04
Address      : 524288
Pages        : 2048
Page Size    : 256 bytes
Total Size   : 512KB
Planes       : 2
Lock Regions : 32
Locked       : none
Security     : false
Boot Flash   : true
CPU reset.

TestProject.cpp:
#include "Arduino.h"

void setup() {
    pinMode(13, OUTPUT);
}

void loop() {
    digitalWrite(13, HIGH);
    delay(50);
    digitalWrite(13, LOW);
    delay(950);
}

Can you tell if it works when you build and upload the program from Arduino IDE instead of Eclipse?

@jfpoilpret It works from the Arduino IDE.

Only the #include "Arduino.h" line is unnecessary.

How did you setup eclipse for Arduino, do you use http://eclipse.baeyens.it/ plugin?

@jfpoilpret I'm using GNU ARM Eclipse plugin version 0.5.4 (http://sourceforge.net/projects/gnuarmeclipse/files/Current%20Releases/0.5.4/) It is set up with the Sourcery Lite toolchain. All the build settings are reflected in the terminal output.

I used this guide as a starting point, and added preprocessor variables to make it compile successfully.
http://forum.arduino.cc/index.php/topic,135403.0.html
By following the guide, it worked using Arduino 1.5.1, however it did not support all of the Arduino API...

Then the next important question is "where is main() defined?"

@jfpoilpret It is defined inside of the Arduino Library. It resides inside ArduinoDueCore->src->core->main.cpp.

OK; in your situation, I would try to compare the output (console and files) of Arduino IDE 1.5 and Eclipse, in order to spot any difference; each found difference is a potential reason of failure. Then analysing each difference can help you find the root cause for it. Sorry, I can't help more, I don't have a DUE available.

@jfpoilpret That is what I've tried. All the differences I know how to "fix" are "fixed". The problem is that the Arduino IDE uses a precompiled library (I believe) for some operations. I know very little about C/C++, as I've mostly interpreted languages. I'll try and see if I can make the Arduino IDE compile everything itself by deleting the compiled library (l*\.a?)

If I were you, I would rather try http://eclipse.baeyens.it/ (I already use it for UNO boards). It works well, and there is a version for Arduino IDE 1.5 also; that may be your best option?

@jfpoilpret Does it work for Arduino 1.5.6-r2? The problem with 1.5.1 was that the API wasn't fully developed for the ARM series.

It is not mentioned; the latest mentioned supported IDE is 1.5.5; I guess that does not mean it won't work with 1.5.6, but you'll have to check it by yourself I think.

@jfpoilpret The reason why I wanted to do it "myself" is because I want to learn how to use the Atmel ARM series step by step. But I suppose Arduino have modified everything so much that it's not like communicating with the real chip anymore. The master branch BOSSA doesn't work on the native port, which I thought was connected directly to the chip... I'll learn how to program it using a book instead.

@jfpoilpret Now I've set up Baeyens.it. It only works half way. Yes, it uploads the code, but it only starts running after pressing the RESET button manually. Additionally it needs to be erased and reset to listen for new code. The RXTX-library doesn't work, and even triggers a Linux system error. I'll just stick to the Arduino IDE!

Using 1.5.6-r2 with Eclipse cause the Due to hung in Default_Handler function after entering main and polling a few times for the next SysTick gettin passed.
Some weak symbol declarations are done twice (i.e. the SysTick_Handler function definitions). They appear to overwrite each others weak alias depending on the link time usage of the objects. All declarations (not only the failing SysTick_Hanlder) from cortex_handler.c are getting overwritten by weak symbol redeclaration inside startup_sam3xa.c.
This commit seems to already address a weak symbol definition problem.
https://github.com/arduino/Arduino/commit/65f00a69c74ca0def8d7f1d7597327945a04a33f
For now, to fix it. Just comment out the part in startup_sam3xa.c with the weak symbol declaration regarding the vectors. Lines 53 to 129.
It should also work to just remove the file completely.
The startup handler code and vector map should be provided by gcc arm built-in libraries instead.


text:
CO2 sensor for arduino
I want to add CO2 measuring feature to my room weather station. Can someone please recommend a CO2 sensor easy to integrate with Arduino?

you can try this co2 sensor ...

You could try the K30 CO2 sensor. There is also a guide using it to make an arduino CO2 detector here.
I've also seen people use the MG-811 module, you can buy them from dfrobot.com . There is also good documentation for how to use the MG-811 with arduino here.

Are these sensors good for external environment, not only to inside building?

Based on hands-on time with CCS811 CO2 sensors, I would recommend against them. They tend to drift high, sometimes way high, and then come back to their senses and provide reasonable readings when reset.
I've tried two batches of CJMCU-811 sensors, purchased months apart (hoping to get a different manufacturing lot), and they were all rubbish.

This worked well for me on a colour screen. A small delay for the sensor and a long burn (24hrs) required. But easy KIWI
#include <XTronical_ST7735.h> // Hardware-specific library
#include <SPI.h>
#include <Adafruit_GFX.h>    // Core graphics library
#include <sSense-CCS811.h>
#include <dht.h>

#define SERIAL_SPEED  9600

#define TFT_SCLK 13         // SPI clock
#define TFT_MOSI 11         // SPI Data
#define TFT_CS   10         // Display enable (Chip select), if not enabled will not talk on SPI bus
#define TFT_RST   9         // Display reset pin, you can also connect this to the Arduino reset
                            // in which case, set this #define pin to -1!
#define TFT_DC     8
CCS811 ssenseCCS811;
Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS,  TFT_DC, TFT_RST);
dht DHT;

#define DHT11_PIN 7

void setup()
{
  DebugPort.begin(SERIAL_SPEED);
  delay(5000);
  Serial.println("s-Sense CCS811 I2C sensor.");
  if(!ssenseCCS811.begin(uint8_t(I2C_CCS811_ADDRESS), uint8_t(CCS811_WAKE_PIN), driveMode_1sec))
    DebugPort.println("Initialization failed.");
  tft.init();   // initialize a ST7735S chip,
  tft.setRotation(0);
  tft.fillScreen(ST7735_GREEN);
  tft.setTextColor(ST7735_RED);
  tft.setCursor(0, 30);
  tft.setTextSize(1);
}

void loop()
{
  ssenseCCS811.setEnvironmentalData((float)(21.102), (float)(57.73));  // replace with temperature and humidity values from HDC2010 sensor
  int chk = DHT.read11(DHT11_PIN);
  if (ssenseCCS811.checkDataAndUpdate())
  {

    tft.fillScreen(ST7735_GREEN);
    tft.setCursor(10,10);
    tft.print("CO2 ppm  ");
    tft.print(ssenseCCS811.getCO2());
    tft.setCursor(10,40);
    tft.print("tVOC ppb ");
    tft.print(ssenseCCS811.gettVOC());
    tft.setCursor(10,70);
    tft.print("Temp C   ");
    tft.print(DHT.temperature);
    tft.setCursor(10,100);
    tft.print("Humid %  ");
    tft.print(DHT.humidity);

  }
  else if (ssenseCCS811.checkForError())
  {
    ssenseCCS811.printError();
  }

  delay(2000);
}

How about this one? http://cgi.ebay.de/ws/eBayISAPI.dll?ViewItem&item=380915024016&ssPageName=STRK:MESE:IT
The MG-811 is highly sensitive to CO2 and less sensitive to alcohol and CO.

This one:
http://sandboxelectronics.com/?product=mg-811-co2-gas-sensor-module
They also got a nice demo code there.
Here is a wiring scheme if you use the demo without modification:

Red - 5V
Black - GND
Yellow - Analog input 0
Green - Digital I/O 2

The easeir integration ever


text:
XBEE WiFi S6B RSSI for Smartphone localization
I am building an early prototype, proof of concept, network monitoring tool.  A big part of it uses localization of a Smartphone.  It seems that the best way to do this is using RSSI from multiple points.  I plan to do this using several Arduino Fios with Xbee WiFi (S6B) cards.
My current setup has a network running from my smartphone (it is running DHCP) with a laptop monitoring all the traffic on the network.
What I need is for my Fio Xbees to dump the RSSI of the "access point" (Smartphone) onto the network so my laptop can pull the data.
Thus, to/from is not important as far as the packet is concerned, I just need the data dropped on the "wire" for my laptop to later parse, which is good because Serial.print* sends out a broadcast to 255.255.255.255:fffff.
I can make my devices broadcast any integer, but when I go into AT mode nothing aside from the initial DHCP handshake gets put on the wire.  Any ideas?
void setup() {
  Serial.begin(9600);
  Serial.flush();
  delay(1000);//enter AT mode start
  Serial.print("+");//AT
  Serial.print("+");//AT
  Serial.print("+");//AT
  Serial.flush();
  delay(1000);//enter AT mode finish
  while(Serial.available()>0){
    Serial.write(Serial.read());
  }

}

void loop(){
  Serial.println("ATDB");

  while(Serial.available()>0){
    Serial.write(Serial.read());
  }
  delay(750);//3/4 a sec
}

Note, Serial.println("ATDB"); should cause the xbee to drop the RSSI on the wire; see
XBee_WiFi_AT_Commands.pdf
at digi.com.
The three "+"s at the start are how you move the device into AT mode; see
Digi_International_90002124_G.pdf at mouser.com.
Once again what I am trying to do is get the collected RSSI information dropped onto a wifi connection from multiple xbee WiFi S6B equipped Fios.

You are reading from the device then echoing back the characters, still in AT mode. You need to save the rssi response, exit AT mode, then send the response, otherwise the device will interpret it as another AT command.

Just incase anybody stumbles onto this page googling, I am posting my solution below (I think it will work for any xbee radio)
Basically for some reason the RSSI values are getting nulled out before I can read them, both in my API mode tests and AT commands.  I'm not convinced that there is not some way around this in API mode at least, but it is irrelevant for my current purpose.
What I did was wire pin 6 on the xbee to a digital pin on the Arduino (I used 7) then use a pulse detector to find the period of the wireless signal coming in.
int pin = 7;
unsigned long period;

void setup(){
  Serial.begin(9600);
  pinMode(pin, INPUT);
  Serial.println("Getting started");
}

void loop(){
  delay(100);
  period = pulseIn(pin, HIGH);
  Serial.println(period);

}

It is not perfect, but for now it works, might help someone else in the future.


text:
My Servo Won't Sweep Smoothly
So I've tried this a few times and I always get the same issue. When I try to run the sweep example the servo goes round 180 degrees but only in steps. Anyone know a way to fix this?
The servo I'm using is a Tower Pro Micro Servo 9G SG90
// Sweep
// by BARRAGAN <http://barraganstudio.com>
// This example code is in the public domain.

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
                // a maximum of eight servo objects can be created

int pos = 0;    // variable to store the servo position

void setup()
{
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop()
{
  for(pos = 0; pos < 180; pos += 1)  // goes from 0 degrees to 180 degrees
  {                                  // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for(pos = 180; pos>=1; pos-=1)     // goes from 180 degrees to 0 degrees
  {
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
}

Video: http://vidd.me/A40

does it hummmmm in between the "steps"?

no just the usual ticking on each step

You don't tell us anything about the set up (schematic?). My guess would be it doesn't have enough voltage.

I've set it up exactly as shown in the sweep example

My only advice is make sure the Arduino is getting enough power and check your connections. Consider external power if you're not on USB.

What's the maximum voltage input?

What power supply do you use? USB, power adapter, battery... Please indicate characteristics (voltage, max current...)

Currently USB from my MacBook so I would guess 5v

Have you checked that your Arduino is running at the right frequency? This can be easily done by just uploading the usual blink sketch and checking the LED on pin 13 blink period. If it's fine then try the same blink sketch but add the Servo library and myservo.attach(); (no call to myservo.read()) to see if the presence of the servo has an impact on frequency.

I've seen disappointingly step-y behavior from a similar cheap servo with an entirely different microcontroller.  Don't rule out low quality.  Generally you should not use USB (or anything coming through the Arduino) to power servos though.  http://www.thebackshed.com/Forum/forum_posts.asp?TID=5611&PN=9&TPN=3  Seems to suggest that different frame rates might yield better results.

@chris-stratton Would a 9v battery be a more suitable power source?

No.  9v batteries should not be used for high current applications.  And without a switching regulator, you'd waste nearly half of your (limited and relatively expensive) power as heat in the linear regulator.

Complete stab in the dark but nothing seems to be working as of now: change the delay to something slower (150 maybe)? Your servo might be getting low power and not wanting to move reliably.

To be fair, you'd better not "step" te servo?
Try to set it from 0 (1sec delay) to 180 (1sec delay) to 0 ... this should give a relatively smooth motion.

In electronics, as usual in situations where a cricuit is misbehaving and we don't understand why, a solution that generally works is to add a decoupling cap between +5V and GND.
In your case, I would put at least 220uF; that would ensure two things:

the voltage used to control the servo never drops
the voltage brought to Arduino by the USB does not drop either (which would have very bad impact on the Arduino, probably resetting it)

Electrolytic caps are a must-have for every electronics hobbyist (and professional as well, of course).
You can read more about decoupling capacitors on Wikipedia.
Edit:
According to @gwideman comment, it seems that using a decoupling capacitance above 10uF in a USB 2.0 device would violate USB specs and may damage the USB host controller on the computer.
I was not aware of this limitation but I have already used decoupling capacitance up to 100uF in my circuits and never got any issue with my USB computer port.
It might be due to extra electronics on the Arduino board that would "isolate" USB power from Arduino +5V anf d GND pins, I don't know (that should probably be the topic of a specific question); or maybe I have just been lucky all this time...

Would you happen to have a schematic for this?

You don't need a schematic just to add a decoupling cap! You just need the right cap and put it (on breadboard preferrably but you could also solder it directly to the servo) between +5V and the GND pins; just ensure you put the cap right as it is polarized (if you put it reverse it will explode)

Like this? http://imgur.com/thfEQtY

Yes exactly like that.

I've tried the following setup with no luck. Any more ideas? http://imgur.com/lprLvm4

What cap did you use? Didn't that change anything at all?

A 2.2uF as you suggested and everything acted exactly the same

I did not say 2.2uF but 220uF, which is a much bigger cap; if you don't have a 220uF or bigger, try to find a 100uF that may be enough.

USB requires that connected devices limit inrush current. This limits the size of bulk capacitor between VBUS and Ground to 10uF in USB 2.0. See USB 2.0 standard section 7.2.4.1 –  Inrush Current Limiting.  Using a larger capacitor, particularly one much larger than the source (computer) is required to supply on its end (120uF) would possibly lead to damage to the computer, or at least disruption of its operation.

More detail on the USB bypass capacitance limitation: http://www.edn.com/design/analog/4313897/Current-limiter-allows-large-USB-bypass-capacitance

Thanks @gwideman for this precision; however, to verify that this applies to an Arduino-based circuit, one has to check first what in Arduino diagram lies between USB power and 5V pin (I did not check it). For what it's worth, I have already used 100uF decoupling capacitor in one of my Arduino UNO based circuits and never got any USB issue at all; your mileage may vary.

What lies between USB power and the +5V net is a fuse and the Ron resistance of the FET that switches between USB and external power. Neither offers much resistance, and the fuse will not operate on a time scale to offer protection in this case. It is true that hosts (computers) are not required to break down when a USB device presents too much capacitance :-), and it obviously behooves computer makers to guard against such damage. Indeed, the Arduino UNO already presents 47uF x 2 bulk capacitance (and it looks like Duemilanove has 100uF x 2).

More likely issues are that hot-plugging will cause other USB-connected devices to experience glitches, especially if sharing a hub.

It's worth noting that USB is often quite tolerant of devices that are MASSIVELY out of spec. It depends on the host implementation, and lots of computers are willing to provide connected devices considerably more current then the specifications say the need to.

I've experienced same behavior with this type of servos. In my case it was easier to spot since Arduino frequently rebooted when servo was approaching the boundaries of the swing - so it was clear it was consuming too much power, and USB port was unable to deliver that.
Cheap dedicated 9V 1A AC/DC converter usually solves the problem. But if you can't wait for one to get delivered, get an iPad USB charger (nowadays everyone has it or has a neighbor/friend who has one). It is rated 10W, and it doesn't suffer from voltage drops even under high loads. Power your setup from it, and if you'd see it moves smoothly, you will have your answer.

It looks like your sketch runs in slow motion.
Check if you wrote delay(150) or have an additional delay in your loop.
Check twice and - just to make sure - upload the corrected sketch again.
Edit:
If possible, test with another servo and even test with another Arduino board.

I can assure you that's not the case. I've tried everything from 1 to 15 for the delay and even without the delay. I've also tried having just one for loop

Ok. Without delay, the servo should move at the actual processor speed.
Which board type do you use? And is the code above the original code that is running on the board?
did you try to set pin 9 as digital out?
Code in setup(){ ... pinMode(9, OUTPUT);   // sets the pin as output ... }

give a 9v supply +ve terminal to Vin and -ve ground.
since the arduino board cannot supply enough power to the servo, this will provide
this worked for me and workin just fine

I tested your code, nothing wrong with it.
Maybe it is power supply issue.
1. Don't use USB to power servo, it can make current spike when it move rapidly.
2. Use proper supply for servo. High current and use large capacitor to deal with current spike.

The program is faulty. 1) No servo can react to a command in 15 milliseconds. Delay should be more like 500 milliseconds (.5 seconds). 2) The for loops are not designed to work together. The 1st loop feeds a value of 181to the second loop which is designed to start with a value of 180. The 2nd loop feeds a value of -1 back to the first loop, which is designed to start with a value of 0.

Please tell me what is incorrect about my for loop analysis. Could use some help.

There are some pretty serious misunderstandings in this - the given delay is only between the finest increments, the actual time of the sweep is  2.7 seconds, well within the capability of a servo.  Using a 20ms delay (possibly with larger increments to compensate) would indeed be more in keeping with typical servo update rates, but that is not what you recommend.  Also your analysis of the for loops is incorrect.

The contents of the for loop only execute if the condition is true, so only conditions which satisfy it are written to the servo.  Both for loops initialize their variable.


text:
ArduinoUno+LcdKeypad+ArduinoWifi=Pins Problems
Is it possible to connect these two shields to my Arduino Uno? After a research on the internet, I discovered that they use some of the same pins. Even so, is it still possible for me to connect the LcdKeypad and the ArduinoWifi on my Arduino Uno? (the LCD would be on top)
Here are the pic of the shields, and some information:
LDC KEYPAD
Arduino WIFI
WiFi shield info:

The Arduino communicates with the processor WiFi shield with the microSD card by SPI
  (Eurotherm the ICSP bus) that is on pins 11, 12
  and 13 at Uno. The pin 10 is used to select the HDG104 and pin 4 to
  the microSD card(i dont need the pin 4 cause i wont use SD). These pins can not be used
  for input and output. The
  digital pin 7 is used for initialization of the communication protocol
  between the shield and Arduino WiFi and should not be used.

LCD info:

This shield we will have to use the following sequence to initialize
  the library LiquidCrystal:
  LiquidCrystal lcd (8,9,4,5,6,7);

As you guys have noticed, there is the pin 7 on both shields that I need to use. How would it work? Can I do this? If i can't, is there any solution that I can expand my pins that would not result buying a Mega?
I still have to connect two INFRA-RED sensors and a motor (using pins 0, 1, and 2). I don't know if i can connect on the pins TX and RX (they seem to work).

So here are your needs:

WiFi, which uses pins 4, 10, 11, 12, 13. I know you said that you don't need pin 4 since no SD, but because that pin switches on/off the SD card, if you use it at all. Note: As Connor Wolf points out, it's not really relevant when there's no SD card. If you're facing problems with the Ethernet shield using the LCD additionally, you might have to reroute pin 4.
LCD, which uses pins 4, 5, 6, 7, 8, 9. The standard Arduino LCD library can use any pins, but your shield is hard wired to use those. As mentioned before, you can reroute them if you want to. Below is the method for rerouting pins.

Rerouting pin 7 (you need to do this!):

Bend pin 7 on the LCD shield and the WiFi shield outward so it doesn't make contact with the header
Use LiquidCrystal lcd(8,9,3,5,6,2); if you're rerouting pin 4, or LiquidCrystal lcd (8,9,4,5,6,2); in your code if you're not rerouting
Attach a jumper between the pin 7 on the header of the WiFi shield and the pin 7 on the Arduino Uno
Attach a jumper between the pin 2 of the WiFi shield (or the Uno, if that's easier) and the pin 7 of the LCD using the free space of the pin bent above it.

This will isolate pin 7 on the LCD, still send the pin 4 signal to the WiFi shield, and reroute the signal from pin 2 on your Arduino to pin 7 on the LCD shield.

Rerouting pin 4 (optional):

Bend pin 4 on the LCD shield and the WiFi shield outward so it doesn't make contact with the header
Use LiquidCrystal lcd(8,9,3,5,6,2); in your code
Attach a jumper between the pin 4 on the header of the WiFi shield and the pin 4 on the Arduino Uno
Attach a jumper between the pin 3 of the WiFi shield (or the Uno, if that's easier) and the pin 4 of the LCD using the free space of the pin bent above it.

This will isolate pin 4 on the LCD, still send the pin 4 signal to the WiFi shield, and reroute the signal from pin 3 on your Arduino to pin 4 on the LCD shield.

For number of pins, you should be fine. You can use pins 0 and 1 (TX/RX) as long as you aren't connecting to the computer or any other UART device  (i.e. using the Serial() library). Don't forget you can use the analog pins as digital pins by referencing them as A0 to A5.

As long as you don't have a microSD card in the microSD slot, the fact that you have a wire going there that is energized is irrelevant. You don't need to bend any pins. Just don't put a SD card in the slot. You can't "enable" something that's not physically connected.

Note: there is a voltage translator in there too, but it doesn't matter if it's not connected to something at both ends, so you can ignore it. Also, it doesn't "switch the SD card on/off" anyways. It's a chip-select line, not a power line. It just controls the bus-arbitration electronics in a already powered on SD card.

@Connor I know that you probably don't have to do that, IMO it's more of a "best practice" thing. I'm editing to clarify my post. It also prevents accidental problems if you were to plug in a SD card forgetfully.

If you don't have to do it, and it involves damaging one of your devices somewhat, I'd qualify it as "worst practices", rather then "best" practices. It's not like you can damage anything anyways, the level translator has limited drive capability.

Thanks guys, the but what about pin 7? it's used in both shields, and unlike the pin 4, it's something that i'll use, because it's used for the "initialization of the communication protocol between the shield and Arduino WiFi"

@user3504192 Sorry, forgot to add that. I edited my post.

@Connor BTW you do have to "damage" your board either way with pin 7; I forgot to add that in my answer. The OP could also do this manually with a breadboard for the WiFi, but that would be a pain.


text:
Why doesn't the master branch BOSSA work on Arduino Due?
I have downloaded BOSSA for Linux, and have run bossash->scan. I have also tried erasing and resetting the board before scanning. It does not work. According to the Arduino website, the native USB port is connected directly to the chip.
Isn't the master branch BOSSA (Arduino IDE uses it's own modified version of BOSSA) working because of a problem with this specific board, or have Arduino modified something inside the chip which alters the behaviour of the native port?

No Arduino did not alter the chip, custom chips are massively expensive. If they are using their own modified version of BOSSA, then there must be a reason for it, probably the support of Arduino's hardware platform. To find out what the difference is, you have to find the code base used for Due and the original version when the code was forked. Often in such cases a project like Arduino can provide a patch to the BOSSA project, and that patch may or may not be applied to the master tree. Only way to find out is to check the BOSSA project repository / bug  reports and documentation.

I was thinking about the bootloader, but maybe it can't change the behavior of the native USB port? So what you are saying is that the native BOSSA should work if the native USB port is connected directly to the chip? Are you implying that they have added extra hardware in between that BOSSA needs to account for? Please bear with me, as I know very little about this subject. I'm trying to learn more about it.

@FriendofKim I am unfamiliar with BOSSA and Due. This is generally how open source projects work.


text:
A waterproof Chlorine Sensor
Does anyone know where I can find a Chlorine Sensor to use with the Arduino? It would need to be water proof. I've googled, but I couldn't find anything.
EDIT
Requirements: relatively inexpensive (under $100us), works with Arduino, waterproof and used to detect chlorine in water.

A quick Google search turns up tons of them. Do you need to sense Chlorine gas in air? Dissolved in water? Do you need to measure concentration or merely detect the presence? How have you tried to find one so far?

actually for water (swimming pool) - I have searched but could not find any that look suitable

Define "suitable".  What are your requirements?

suitable = relatively inexpensive (under $100us), works with Arduino

Your best bet would probably be to interface with a colorimeter.  There is a tutorial for an open source colorimeter here:
http://www.appropedia.org/Open-source_colorimeter
IORodeo also sells a shield:
http://www.iorodeo.com/colorimeter
Vernier sells a colorimeter that may be suitable for your project & Sparkfun sells a shield to interface with Vernier sensors.
If a colorimeter doesn't work you would have to use an electrode, which is pretty expensive and has a shelf life.

Maybe measure conductivity instead?  I think, in freshwater pools, one of the active parts of working chlorine is an OCL ion - which I guess is conductive.


text:
Seeed Studio motor shield
My goal is to have my Arduino fire two stepper motors.  They need not be simultaneous. I'm using an Arduino Uno with 2 motor shields - specifically, the Seeed Studio Motor Shield v1.0. I know this shield uses D8-13.
Question is, how can I get the Arduino to use both shields?  Is there a way to make one of the shields take D0-D7?  If I could do that that'd be great. As far as I can tell, there's no way. The motor shields cannot be physically mounted either.

What's wrong with breadboarding the motor shields and then running wires to the Arduino? Or see if a breakout for the shield exists?

Part of the problem is that you've picked a shield that uses the L298 and hence requires the Arduino to control the stepper in detail, and use much of the MCU time, and many signals, to do so. Other shields based on more sophisticated chips like A4988 or DRV8825, only require the Arduino to send Direction and Step signals, and one select line for each motor. See particularly the shields commonly used for 3D printer control, if you have an Arduino Mega, or smaller ones (eg: DF Robot DRI0023). (But note differing current capabilities.)

SoFly, thanks, but for some reason stepper #2 is not responding when i "connect" it to pins 2-7.  for code please see my comment to Karl B. below

Some shields let you use jumpers or something to change the pin assignments, but I don't believe the Seed motor shield does.  What you can use is a go-between shield between the two shields to remap the pins on the top shield.  Then in your code, you just initialize the second instance using different pins.  You just have to make sure the alternate pins have the features you need, like pwm.

Thanks! Tried effectively that by using breadboard. BUT, any motor shield thats connected to pins 2-7, which are PWM, output pins, won't work. Original Code below. I just subtracted 6 from each pin number to get pins 2-7. Why not working? Is the "~" sign next to pin 3,5,6,9,10 and 11 important?

#include <Stepper.h>
const int stepsPerRevolution = 340;
// initialize the stepper library on pins 8 through 11:
Stepper myStepper(stepsPerRevolution, 8,11,12,13);
void setup() {
// set the speed at 60 rpm:
myStepper.setSpeed(60);
Serial.begin(9600);
pinMode(9,OUTPUT);
pinMode(10,OUTPUT);
digitalWrite(9,HIGH);
digitalWrite(10,HIGH);
}
void loop() {
Serial.println("clockwise");
myStepper.step(stepsPerRevolution);
delay(500);
Serial.println("counterclockwise");
myStepper.step(-stepsPerRevolution);
delay(500);
}

Nevermind, I can't paste code into this window. Basically, it boils down to: Stepper myStepper(stepsPerRevolution, 8,11,12,13);      myStepper.setSpeed(60);      pinMode(9,OUTPUT);         pinMode(10,OUTPUT);         digitalWrite(9,HIGH);        digitalWrite(10,HIGH);


text:
How to catch the Enter key received by Bluetooth?
I got some code to receive characters from Bluetooth and code and print it back to the LCD display.
However, want to detect the Enter character to be the input signal, in other words, not to print nothing to the display until Enter is pressed.
An strange character is shown at display for Enter but I can't catch it.
This is my code:
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x20,16,2);

void setup()
{
  lcd.init();
  lcd.backlight();
  pinMode(13,OUTPUT);
  Serial.begin(9600);
  Serial1.begin(9600);

}

void loop()
{

  while (Serial1.available())
  {
    char dato= Serial1.read(); //Comprobamos el dato

     lcd.print(dato);

    switch(dato) {
    case '#':
      Serial.println("GATO...");
    break;
    case 'e':  digitalWrite(13,LOW);

    Serial1.println("Led apagado");
    break;
      case 'r':
      digitalWrite(13,HIGH); delay(200);
      digitalWrite(13,LOW); delay(200);

      Serial1.println("Led intermitente");
      break;
  } //fin switch

}//serial disponible

}//fin programa

How is this related to bluetooth?

It depends on what the enter key sends. It may be just CR (carriage return), LF (line feed), or both. You can check the ASCII table for the hex values for those characters.
LF is 0x0A and CR is 0x0D. Those are the characters you're looking for, you can add a if for these cases in order to guard the call to lcd.print(dato):
char dato= Serial1.read(); //Comprobamos el dato
if (dato != 0x0A && dato != 0x0F)
    lcd.print(dato);

I would use '\n' and '\r' instead of the ascii- if ( dato != '\n' && dato != '\r' ) ...

@imjosh yeah that's more readable.


text:
Can I write to Flash Memory using PROGMEM?
On the documentation of Arduino, I quote:

http://playground.arduino.cc/Learning/Memory
  Note: Flash (PROGMEM) memory can only be populated at program burn time. You can’t change > the values in the flash after the program has started running.

And on the PROGMEM description:

http://arduino.cc/en/Reference/PROGMEM
  Store data in flash (program) memory instead of SRAM. There's a description of the various types of memory available on an Arduino board.
The PROGMEM keyword is a variable modifier, it should be used only with the datatypes defined in pgmspace.h. It tells the compiler "put this information into flash memory", instead of into SRAM, where it would normally go.

So can we or can't we? Or it's not the same thing?

While you can write to (flash) program memory at run time (unless it is locked), the process is a bit more involved, and cannot be accomplished with the PROGMEM directive, which basically just control the allocation process.  If you want to see how it can be done, look at the bootloader source.

Page write blocks does not make writing to flash impractical. In fact its something looked forward to.

The short answer is no: PROGMEM data is read-only.
Flash memory limitations
The first thing to understand is that Flash memory (where program space lives) is designed for long-term fixed storage. Reading from it is very fast and precise. However, generally speaking, you can't modify it on a byte-by-byte basis (e.g. changing a specific variable). You usually have to erase and re-write it in large blocks. That makes it completely impractical for run-time manipulation, because you'd have to store a lot of redundant information somewhere else while you do the erase and write cycle.
What PROGMEM actually does
Any literal data specified in your code (such as strings and numbers) always reside in program space at first (i.e. in Flash). However, when your sketch actually wants to use that data at runtime, it normally has to allocate some space for it in SRAM and copy it over. That means you end up with two copies: the fixed original in Flash, and the temporary copy in SRAM.
When you use the PROGMEM modifier, you're telling it not to make that second copy in SRAM. Instead, your sketch will simply access the original in Flash. That's very useful if you only ever have to read the data, as it avoids the allocation and copy operations.
However, copying it to SRAM is essential if you want to modify the data. Aside from the Flash limitations I mentioned above, it's also a question of code safety.
If you're able to modify the data stored in program space, then it follows logically that you could also modify the code stored in program space. That would mean that a simple mistake (or in theory a malicious attack) could result in your sketch being partially or fully rewritten at run-time. This could have very unpredictable results, ranging from simply ceasing to work, through to damaging/destroying any connected equipment.
More information
You can learn more about the low-level PROGMEM stuff from here:

http://www.fourwalledcubicle.com/AVRArticles.php

An older version of the same PROGMEM tutorial is available here:

http://www.avrfreaks.net/index.php?name=PNphpBB2&file=viewtopic&p=243018

https://mon.im/2014/11/modifying-avr-progmem-at-runtime.html


text:
Arduino Uno and Leonardo SPI clock can't be measured
I want to measure the SPI clock (pin 13) using the Arduino example code for the SPI library (very simple example). Basically independent from the loop function, the clock should be fired continuously.
I deployed the Arduino SPI example code on the board and measured pin 13 on an oscilloscope, but nothing was found, always zero volt.

Note: In contrast to Arduino Uno, on the Arduino Leonardo the SPI clock (SCK) is not connected to pin 13 (see SPI library, sub section "Connections")

On Arduino Leonardo the SPI signals are only available on the six-pin ICSP header.

Please note the SPI clock will only be active while it is shifting data. So simply put the spi.transfer in a hard loop
#include <SPI.h>

void setup() {
  SPI.begin();
  while (1) {
    SPI.transfer(0x00);
  }
}

Thnaks alot mpflaga for your help. i will test it today and i hope it will work..thanks alot really !!


text:
Interference at digital input (UNO)
I was trying out a basic button tutorial on my new Arduino UNO. But for some reason, the Arduino was detecting the button as on (pressed) even when it was off (unpressed).
After some experimentation, I found that the digital pins were flickering between HIGH and LOW, even if there was just a loose wire plugged in with nothing at the other end. And the state of the button, etc. wasn't making any difference. I tried this with pins 5,6 and 7, and it's happening with all of them, even when the neighbouring pins are connected to the ground.
Is this behaviour normal or is there something wrong with my input pins?
Since I'm new to Arduino, there might also be something wrong with my testing code. Here's what I used...
const unsigned int LED_PIN = 12;
const unsigned int BUTTON_PIN = 7;
const unsigned int INDICATOR_PIN = 13;

void setup() {
  pinMode(LED_PIN, OUTPUT);
  pinMode(LED_PIN, OUTPUT);
  pinMode(BUTTON_PIN, INPUT);
  digitalWrite(LED_PIN, LOW);
}

void loop() {
  const int BUTTON_STATE = digitalRead(BUTTON_PIN);

  if (BUTTON_STATE == HIGH) {
    digitalWrite(LED_PIN, HIGH);
    digitalWrite(INDICATOR_PIN, LOW);
  }
  else if (BUTTON_STATE == LOW) {
    digitalWrite(LED_PIN, LOW);
    digitalWrite(INDICATOR_PIN, HIGH);
  }
}

This code makes the lights always in opposite states: when one is on, the other is off. When I ran the code, both lights seemed on, which meant they were probably flickering, which meant that there was some interference in the input pin.

It sounds like you're seeing entirely normal behaviour. If you leave a digital input unconnected (or connected to an open button) then it's 'floating'. That means it can pick up interference from all sorts of things, and may appear to drift between high and low.
The usual way to resolve this problem is using a pull-up or pull-down resistor. This is usually a high-ohm resistor (e.g. 10,000 Ohm or more) which will gently pull the pin HIGH or LOW in the absence of any other signal. When another signal comes in (e.g. from a button being pushed), it should have a much stronger effect than the resistor, so that is what the input will see.
Your Uno has built-in pull-up resistors which you can use for this, although it will require a couple of changes. In your setup() function, you can enable the pull-up on your input pin like this:
pinMode(BUTTON_PIN, INPUT_PULLUP);

That will cause the input to appear HIGH when the button is not pushed. That means you'll need to wire the other end of your button to ground (negative) instead of the voltage supply (positive). If you've set it up correctly, the input should appear LOW when the button is pushed.

Thanks for the tip about the resistor! I also realized that my breadboard was separated in the middle, so my "ground" line wasn't actually connected to the Arduino's GND pin.


text:
Control/count rotations of a DC motor
Using an Arduino and an L293D IC, can I control the number of rotations a DC motor makes? Or can I only control the direction and speed of the motor?
I purchased a two-wheeled robot platform to learn Arduino programming and electronics. The platform is here: http://www.robotshop.com/en/dfrobot-2wd-mobile-platform-arduino.html
Each wheel is controlled by a DC motor. I followed Adafruit's tutorial (https://learn.adafruit.com/adafruit-arduino-lesson-15-dc-motor-reversing) to control the motors with the help of an L293D IC.
Now I realize that I can't directly control the rotations of the motor. I can control the direction, voltage, and time of the rotation. For example: turn forward at 50% voltage for 500 milliseconds.
But that's difficult to translate into actual rotations. The speed of the motor varies according to voltage (like if I switch from 2AA batteries to 4AA's) and weight (adding sensors slows the motors down). Every time I change voltage or weight, I have to guess how much voltage/time causes a single rotation.
I think I should just buy stepper motors. Before I do that, I'll ask the community: Is there a way to control DC motors by rotations rather than time?

Other than with a rotary encoder?

I don't understand how to connect a rotary encoder to a DC motor. I see rotary encoder has a knob on it, and the three pins tell the Arduino how many degrees the knob has turned. But how would you tie that knob to the DC motor (or the wheel the motor turns)?

With gears, a belt, or a chain.

Or a shaft coupler, though that can require more precise alignment.  Steppers motors are generally not used for mobile robots as they are fairly heavy and power hungry for their power.  Depending on your resolution needs, you can also make your own optical or magnetic encoders, especially if you can work near the rim of a wheel. A quadrature system will give you 4 times the element resolution, so if you have a working diameter that can support 8 or 16 physical elements with two spaced sensors you can get a decent resolution (32 or 64 counts/revolution) for motion. See robotics.stackechange.com

Thanks for the advice. Would a question like this be more suited to robotics.stackexchange.com?

Or use a motor with built-in (gear and) encoder.

As you've discovered, there are a lot of variables involved, so you need some sort of feedback.  A popular way to do this is with an encoder, but depending on your needs, other kinds of sensors can make do.  For example, if your problem is keeping the robot going in a straight line, an electronic compass can help.  For a line following robot, the line sensors are usually enough.  Range sensors can track your distance.  You get the idea.

Stepper would be heavy and battery consuming, as Ignacio says.
Pololu makes an encoder for a wheel: http://www.pololu.com/product/1217, but obviously you can implement this in other ways too.


text:
How to control Keyboard inputs using arduino(serial monitor) and python keyboard libraries?
I am able to control my monitor and most other applications by giving serial input to python through arduino.
Arduino code:
void setup()
 {

  pinMode(2, INPUT);
  pinMode(3, INPUT);
  pinMode(4, INPUT);
  pinMode(5, INPUT);
  pinMode(6, INPUT);
  pinMode(7, INPUT);
  Serial.begin(9600);

}

void loop()
{
  if(digitalRead(2) == HIGH)
  {
    delay(5);
  }
  else
  {
    Serial.println("up");
  }
  if(digitalRead(3) == HIGH)
  {
    delay(5);
  }
  else
  {
    Serial.println("down");
  }
  if(digitalRead(4) == HIGH)
  {
    delay(5);
  }
  else
  {
    Serial.println("left");
  }
  if(digitalRead(5) == HIGH)
  {
    delay(5);
  }
  else
  {
    Serial.println("right");
  }
  if(digitalRead(6)== HIGH)
  {
    delay(5);
  }
  else
  {
    Serial.println("space");//orange
  }
  if(digitalRead(7)==HIGH)
  {
     delay(5);
  }
  else
  {
    Serial.println("nitro");//brown
  }
 }

Python code:
import serial
from pymouse import PyMouse
from pykeyboard import PyKeyboard

k = PyKeyboard()

ser = serial.Serial('COM7', 9600)

#sp.write("AT\r\n".encode('ascii'))

while True:
    p=ser.readline()
    print p
    if ('up' in p):
        k = PyKeyboard()

        k.tap_key(k.up_key)

    if ('down' in p):
        k = PyKeyboard()

        k.tap_key(k.down_key)

    if ('right' in p):
        k = PyKeyboard()

        k.tap_key(k.right_key)

    if ('left' in p):
        k = PyKeyboard()

        k.tap_key(k.left_key)

    if ('space' in p):
        k = PyKeyboard()

        k.tap_key(k.space_key)

    if ('nitro' in p):
        k = PyKeyboard()

        k.tap_key(k.enter_key)

My problem is that..I am not able to play games such as NFS and other similar games using these controls..
What should i do??

This appears to cover much the same ground as http://arduino.stackexchange.com/questions/1148/use-an-arduino-as-a-user-interface-for-the-computer

Your examples of sending input to the Arduino IDE monitor and to Python involve the Arduino sending data via "Serial over USB" convention. However this is not seen by the operating system (Windows, MacOS) as legitimate keyboard/mouse/joystick input.
There are separate USB conventions (device types) for keyboard/mouse/joystick. Only Arduinos where the USB interface is programmable are able to present those conventions, and some more easily than others, and require understanding some USB client libraries.  The link provided by Chris Stratton has some useful background.
A particularly easy way to get into this is with the PJRC Teensy, https://www.pjrc.com/teensy/, which comes with libraries and examples that let you do this out-of-the-box. See the "Teensyduino" section of their website for USB Keyboard, Mouse, Joystick and so on. These pages are useful background even if not using Teensy. It has attracted a small following of users interested in this area. Plus the various Teensies are conveniently small boards that fits nicely in some user-interface device you might want to build.

I'm later, but, I think you should redesign your python and arduino code, to make messages like "start up", "end up", and if message is "start *", hold that key, if "end *", release that key. This should work as intended. I will pin python and arduino code later here. (Also sorry for my english, i'm russian)


text:
Pull Chain Switch
I'm a bit new to electronics/Arduino projects, so am looking for some help on some wiring needed for a project involving this Pull Chain: http://proto-pic.co.uk/pull-chain-switch/
The chain works like a fan chain would.
I am using an Arduino UNO
I have wired up the pull chain to a mini breadboard with a light that turns on and off just to test it's working. What I want to do, is get an analog/digital read each time the chain is pulled?
Is this possible? If so, would you be able to help me with how it would be wired up, as I am completely new to the electronics side of Arduino. I simply need to get a reading each time the chain is pulled, I don't need it to switch a light on.
Thanks all!

Connect it between ground and an interrupt pin configured as an input with the pullup enabled. Configure the interrupt to trigger on any state change. Check the digital value of the pin in the ISR.