text:
SD Card shield and TCRT5000 sensor aren't working together on arduino uno
I need to work with SD card and TCRT5000 sensor (Reflective Optical Sensor with Transistor Output) and save data from sensor to file. So I select Arduino Uno and added to it a SD card shield(from LC STUDIO) and a TCRT5000 sensor but it isn't working.
My circuit and code is here:

#include <SPI.h>
#include <SD.h>

const int chipSelect = 10;

void setup() {
  Serial.begin(9600);
  pinMode(chipSelect, OUTPUT);
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    while(true);
  }
  Serial.println("card initialized.");
  File dataFile = SD.open("test.txt", FILE_WRITE);
  dataFile.close();
  dataFile = SD.open("test.txt", FILE_WRITE);
  if(dataFile){
    dataFile.println("Start:");
  }else{
    Serial.println("Error in creating file.");
    while(true);
  }
}

void loop() {
  float value = analogRead(A3);
  File dataFile = SD.open("test.txt", FILE_WRITE);
  if (dataFile) {
    dataFile.println(value);
    Serial.println(value);
    dataFile.close();
  }else{
    Serial.println("Error in opening file.");
  }
  delay(5);
}

When TCRT5000 isn't connected SD card working without any problem.
I think it is related to current and supply current. Any idea?

I would like to believe that you made a mistake with +5 and GND from board???

60mA can not do any problem. Maybe you connected it wrong? 90% problems are in wiring :))

I checked it again. The circuit isn't wrong. I do it like this and this. If problem is not related to current,it is related to what? Why the SD card work when I remove TCRT5000 from circuit without any change in wiring?

Try disconnecting only D+. That way you know if the problem is with the IR-diode or the phototransistor.

The 5V to the breadboard power rails is 100% not in the right spot. Both the 5V and GND are in the same rail, causing a short. I assume this is just an error in the diagram, like @Martynas said?

Did you figure this out yet? If not, you have the +5 volts going to the GND on the breadboard, causing a short.


text:
Is it possible to sample sound with arduino?
I have the arduino duemilanove with atMega328.
The frequency is 16Mhz.
I want to sample and record from the audio jack.
I searched and i found if i want to record "everything - so to speak", i have to sample at 44100Hz.
That means this is unfeasible with my arduino, since my frequency is only 16MHz?

16 MHz is 16000000 Hz. The "M" is relevant.

For the AtMega328's ADC the datasheet says

• Up to 76.9kSPS (Up to 15kSPS at Maximum Resolution)

So, sampling two channels at 10bit resolution and 44.1kHz is not possible.
If 8bit resolution is enough, and if there's only one channel to sample, it should be able to do the job.
Edit:
To answer Connor's comment:
Of course, this does only apply when using the internal ADC. Connecting an external ADC (via SPI or whatever) makes it possible to sample data at the desired speed.
But anyway, the next question is: Is 16MHz fast enough to process the sampled data (which are received every (22.6/channels) microseconds? ;-)

This assumes you're using the ATmega's internal ADC.

Unless one is going after very strong high frequency sounds, it's probably not wise to maximize sample rate at the expense of resolution.

source: Stack Exchange

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

sort: votes


text:
Wireless Sensor (IMU) to Arduino
I was doing some research about this subject and I only have more questions than answers.
I want a little IMU sensor (I don't know which hardware I should get) that sends data wirelessly to my Arduino.
The sender part (IMU + sender + battery) should be small (tennis ball size is fine) and the receiving part should be an Arduino.
What should I buy? How can I achieve this? I was looking at a lot of ideas: Xbees, bluetooth, radio receivers, Arduino Nano, etc.
My focus is on the Arduino code, I just need that the IMU sends data at least at a ratio of 10ms.
As a plus I would love to have more than one Wireless IMU sensor connected to my Arduino.

What is the purpose of having the IMU and arduino in different locations in your project? What data are you specifically looking to get from the IMU?

There are in the same location (4-5mts). But its some sort of instrument and i want to avoid the use of cables. Im sending the stream of the Gyro/Accel.

A bunch of ATmega-based quadcopter boards could be an interesting platform as they often now incorporate a six axis chip such as MPU-6050, and use 2.4 GHz radios which are bidirectional.  They are also relatively cheap (replacement parts for toys built around other processors may be even cheaper)

You have not really given enough specifications for any choice of radio to make a difference in your scenario. Any list of products would be very long, overly summarized, and not relevant in a month, So I'll try and outline the thought process I would take in finding the fit for a project I was making.
Radio: Which type of radio to choose will depend on a lot of specific factors, but its more than likely that multiple options will work perfectly. You seem to know the major methods, Xbee, bluetooth, Wifi, and for very long distances, GSM.
You should consider the problem, define what you need by looking at the amount of data per second you want sent, the necessary range, the power you have available in the battery, any region specific laws, and anything else you can think of needing. Also consider if you really need an arduino as the receiver, or if you have a Bluetooth equipped laptop or wireless router on hand that could take that roll for you. Then look around at sparkfun or wherever and find the cheapest, most popular method that fits the bill.
IMU: Many IMU's exist with more or less the exact same features, so I will recommend a similar process. Look at the power consumption, output rate, sensitivity, and communication method you project needs, and find the cheapest and/or best rated item at your preferred electronics retailer that fits the bill. the MPU6000's are popular these days. The altIMUv4 has a magnetometer and barometer included as well. Shop around.
You will most likely want to put an arduino nano/micro/trinket/whatever with the IMU to translate to your communication method. Some radios work with UART serial, but not many IMU's output like this. Those that do cost more because they have a coprocessor on board. Consider if buying a co-processor equipped board will make your sensor processing easier before you discount it for the elevated price. In depth sensor fusion gets pretty hairy, and for some, not having to worry about it could be worth $50.

I followed this recommendation. For each component, evaluate every aspect of it and get the better option available that suits our budget. We finally went for Arduino Fio, XBee Trace Antenna (802.15.4) and the IMU (ITG3200/ADXL345)

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


text:
problem using std::map. Are there known obstructing macros?
I have a header file, where I try to collect global variable declarations. When trying to typedef a map I get the following error:
n file included from Dis0_10.ino:7:
/var/folders/jl/nv1qvh6n569cxq9xxfd6dx980000gn/T/build8295701509021940161.tmp/globals.h:23: error: expected initializer before '<' token

relevant code snippets from global.h are:
#ifndef GLOBALS
#define GLOBALS
#include <map>

...
typedef std::map<uint8_t,uint8_t> memmap_t;

I have no clue, why this statement should fail. I consider it rather straight forward. So I think there must be some problems of this kind here. Or am I missing another include?

The C++ standard library is not available for arduino.
Some implementations of similar containers or certain functions exist on the web, but for the most part the standard library is impractical on a device with such small amounts of both RAM and program memory.
An implementation of SGI STL for AVR has been documented here: http://andybrown.me.uk/wk/2011/01/15/the-standard-template-library-stl-for-avr-with-c-streams/
map is mentioned as being particularly impractical for anything less than an arduino mega(1280). An example of maps working is included on the page so it seems like a good lead if you really must use one, but I've never done this myself so I cant guarantee it still works.

In general, any sort of dynamic memory allocation is usually considered poor practices in embedded code development.

Ok this is definitely decision making information. I thought of map as a way of saving memory and cpu time. If the memory overhead is rather, I can go back to a sparse array and put into program memory. Thanks for the clue.


text:
Controlling Dynamixel MX24T, MX64T servo wirelessly using Arduino Mega?
I am planning to control multiple Dynamixel servos (MX28T or MX-64T) wirelessly using an Arduino Mega. Since this servo uses serial communication, I need an additional serial port to interface with XBee module. Although it seems to be very common application controlling these servos wirelessly based on Arduino, I could't find any of them in web. I found the two very well constructed libraries.

https://code.google.com/p/slide-33/downloads/list. This library is for MX28T servo, which is the same servo I am trying to use, but it uses UNO;therefore, I cannot interface with XBee.
The Arduino/Dynamixel Resource Page... This library uses UART1 (serial1) to interface with servo (AX-12) motors. Therefore, I can connect XBee module to UART0. But, the problem is that this library is outdated and not compatible with MX64-T servo anymore.

So my questions are:

Is there any one who has experience in controlling Dynamixel MX24T, MX64T servo series using XBee module simultaneously? If you have experience, please share with me.
Is it possible for Arduino Mega can interface with Xbee module using Serial1 (i.e., RX18 TX19)? If it can, I might be able to use the library1 without any modification.

I know, Although it is not ZigBee, ROBOTIS Arduino Shield(https://emanual.robotis.com/docs/en/parts/interface/dynamixel_shield/) can use BLE module (BT-410). My recommendation is Arduino compatible OpenCM 9.04(https://emanual.robotis.com/docs/en/parts/controller/opencm904/).
Arobotix-M(https://www.trossenrobotics.com/p/arbotix-robot-controller.aspx), you can use ZigBee.

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


text:
Why can't I read anything but Pin 0 of PORTC?
So I am working on this lab for my Embedded Systems class, but I can't seem to read anything but the first bit of PORTC.  What's even weirder is that if any of the pins go low the first bit will go to 0, while all the others stay at 0 no matter what.
Here is my code:
 /*
 * Lab_4A.c
 *
 *  Reads the value of one distance sensor
 *  and reports if light/dark to the LCD.
 *
 *  Created on: Sep 24, 2014
 *  Author: Austin R. Bartz
 *
 *  LCD Connections:
 *  E   - PB4 (Digital 12)
 *  RS  - PB5 (Digital 13)
 *  R/W - GND
 *  Data 4,5,6,7 - PD4,5,6,7 (Digital 4,5,6,7)
 *
 *  Sensor Connections:
 *  Sensor 8 - PC0 (Analog A0)
 *  Sensor 7 - PC1 (Analog A1)
 *  Sensor 6 - PC2 (Analog A2)
 *  Sensor 5 - PC3 (Analog A3)
 */

#include <avr/io.h>
#include <inttypes.h>
#include <MSOE/delay.c>
#include <MSOE/bit.c>
#include <MSOE/lcd.c>
#include <user/initPorts.c>
#include <user/readPorts.c>
#include <user/writePorts.c>

void printBinaryLCD(uint8_t);
uint8_t readSensors();

int main(void)
{
    lcd_init();
    lcd_clear();
    while(1)
    {
        uint8_t val = readSensors();
        printBinaryLCD(val);
    }
}

void printBinaryLCD(uint8_t val)
{
    lcd_home();
    uint8_t A = ((PINC & (1<<3)) == (1<<3));
    lcd_print_uint8(A);
    lcd_goto_xy(1,0);
    uint8_t B = ((PINC & (1<<2)) == (1<<2));
    lcd_print_uint8(B);
    lcd_goto_xy(2,0);
    uint8_t C = ((PINC & (1<<1)) == (1<<1));
    lcd_print_uint8(C);
    lcd_goto_xy(3,0);
    uint8_t D = ((PINC & (1<<0)) == (1<<0));
    lcd_print_uint8(D);
}

uint8_t readSensors()
{
    DDRC = 1;
    PORTC = 1;
    delay_us(10);
    DDRC = 0;
    PORTC = 0;
    delay_ms(1);
    return PINC;
}

Any help would be much appreciated!

What kind of sensors did you plug to PORTC pins 0-3?

What Arduino board do you have? I guess you can read the port, but your sensors are not connected properly (missing supply voltage?). As you set PC0 to output High for some time (why are you doing this?), and then back to tristate, it still may have High level when reading it.

DDRx is the Data-Direction-Register-x so this can be DDRC or DDRD or anything. One register has 8 bits, 1 bit for every pin.
Making a bit 1 will result in the pin being an output. Making it 0 will result in the pin being an input.
Let's say we want to make pin 4 and 5 of port C an output.
We simply do this in the setup:
       //76543210  Pin numbers.
       //IIOOIIII  Input/Output indicator
DDRC = 0b00110000;//Code that actually does it.

So this way we can read pin 4 & 5.
But if we want to read the complete port, I suggest setting every pin of the port to input. DDRC = 0b00000000;
Then we can read the port as simply as uint8_t portValueC = PORTC;
portValueC will now have a value that represents the port's values.
It'll be binary, but you read it as decimal.
So it'll be:
0 for no inputs.
1 for only pin 0
2 for pin 1
3 for pin 0 & 1
4 for pin 2
5 for pin 2 & 0
6 for pin 2 & 1

Well. it's binary.
Let's say (pin 7,5,3,1 high)(pin 6,4,2,0 low).
This will result into the decimal value of 170.
The binary value, however, will be easier to read 0b10101010
    //76543210
  //0b10101010 (Could be the value) (pin 7,5,3,1 high)(pin 6,4,2,0 low)
//^ is decimal: 170

You should add these macros to your project to make it easier to get single bits from this value:
#define bit_get(p,m) ((p) & (m))
#define bit_set(p,m) ((p) |= (m))
#define bit_clear(p,m) ((p) &= ~(m))
#define bit_flip(p,m) ((p) ^= (m))
#define bit_write(c,p,m) (c ? bit_set(p,m) : bit_clear(p,m))
#define BIT(x) (0x01 << (x))

This way, now you can do:
if(bit_get(PINC, BIT(3)))
{
 //Do only this if PORTC pin 3 is high
}

Read this first:
Info on the registers
Info on bit fiddling

Judging from your readSensors() function, these seem to be capacitive
sensors:

you charge them to Vcc (DDRC = 1; PORTC = 1;)
you wait until they are fully charged (delay_us(10);)
you tri-state the pin (DDRC = 0; PORTC = 0)
you wait for them to partially self-discharge (delay_ms(1);)
you read the pin (return PINC;)

If my assumption is correct, and if all of those sensors are similar,
then here is your first bug: you are only charging the sensor on PC0. If
you want to charge the four sensors, you need to set bits 0 to 3 of the
port to active high. Thus, the first two statements in readSensors()
should be:
DDRC = 0x0f;   // bits 0 to 3...
PORTC = 0x0f;  // ...set to active high

Your second bug is in printBinaryLCD(). The function name, and the way
you call it, implies it is meant to print on the LCD the value passed as
a parameter. Instead, it is completely ignoring its parameter, and
reading PORTC itself. This is bad because the reading of the
capacitive sensors is time sensitive, so you should let readSensors()
do the work. You should then change printBinaryLCD() so that it
examines val instead of PORTC:
void printBinaryLCD(uint8_t val)
{
    lcd_home();
    uint8_t A = (val & (1<<3)) != 0;
    ...etc...

Nice catch on the capacitive sensors, I kinda feel the "question asker" should've mentioned that.
I also feel that  ((PINC & (1<<1)) == (1<<1)); Is wrong.
PINC&(1<<1) Should evaluate to 0b1 (or 0b0), comparing it with (1<<2) (0b100) just doesn't make sense?

@FuaZe: Comparing to 1<<1, although inelegant, does work. Say PINC == 0bxxxxxxYx, where x is “don’t care” and 1<<1 = 0b00000010. Then PINC & (1<<1) == 0b000000Y0. It’s a “bitwise and” operation.

Yes, though my remark wasn't on the syntax.
I wanted to show that the questioners: uint8_t C = ((PINC & (1<<1)) == (1<<1)); will not give the desired behaviour. But your code uint8_t A = (val & (1<<3)) != 0; did actually fix that problem.

@FuaZe: My remark isn't on the syntax either: it's on the semantics. ((x & (1<<1)) == (1<<1)) is semantically equivalent to (x & (1<<1)) != 0. I just prefer the != 0 version for a matter of style: the “do not repeat yourself” principle.

I'd say they're not equivalent. In ((x & (1<<1)) == (1<<1)) the part
(x & (1<<1) will evaluate to true/false (1 or 0?) and (1<<1) will evaluate to 0b00000010 thus they will never be equal?

@FuaZe: No. The & operator is a “bitwise and”, not a “logical and”: it's not just false or true, in the sense 0 or 1. Specifically, x & (1<<1) evaluates to either 0 or 0b00000010. If you are not convinced, try it yourself.

Ah, I see, it's not like a logic AND the (1<<1) is a mask for the bit pattern of PINC which afterwards is checked again using the same mask/pattern.
I was confused as using an mask on a pattern would always cause it to be either 0 or "true" in a way it being anything bigger than 0. But yeah, you can check the outcome of it to be like the pattern itself, didn't catch that as it feels quite unlogical (and logical differs from bitwise in this case ;D).

i can't be certain, but i reckon it has something to do with
DDRC = 1;

this equates to b000001, meaning only pinC0 is an output. i think


text:
SD card fails to write every 5 or 6 minutes
My SD card initializes fine in the beginning. It finds the right file and opens it. However, after 5 or 6 minutes of data logging, the error "file not found" appears on my LCD. Why would this be the case? I need this to work consistently for at least an hour, this 5 to 6 minutes will not do.
Also, in my code the "sv" and "cpm" data is not yet initialized, due to another problem incorporating a sensor. I left these in there, and the data is just logged as 0 for those variables.
#include <SPI.h>
#include <MPL115A1Lib.h>  // Pressure Sensor MPL115A1
#include <DHT.h>  // Temperature and Humidity Sensor RTH03
#include <U8glib.h>  // LCD Display 128x64
#include <floatToString.h>  // Converts floats to strings
#include <GPS610F.h>  // GPS-610F Module
#include <RFZuluArduino.h>  // Zulu 2km RF Module
#include <SD.h> //SD data logger

//----- Defining Modules and Variables ------//
// Pressure Sensor
MPL115A1Lib PressSens;  // Defines Pressure Sensor for library
#define FT_TO_M(x) ((long)((x)*(0.3048)))
#define KPA_TO_INHG(x) ((x)*(0.295333727))
#define KPA_TO_MMHG(x) ((x)*(7.50061683))
#define KPA_TO_PSIA(x) ((x)*(0.145037738))
#define KPA_TO_KGCM2(x) ((x)*(0.0102))
#define INHG_TO_PSIA(x) ((x)*(0.49109778))
#define DEGC_TO_DEGF(x) ((x)*(9.0/5.0)+32.0)

float press_pKa = 0;
float temp_c = 0;
long alt_ft = 0;
char charPress[7];  // Stores pressure
char charTemp[6];  // Stores temperature in C
char charAlt[5];  // Stores altitude
// Temperature & Humidity Sensor
#define DHTPIN 48     // Defines signal pin connection
#define DHTTYPE DHT22   // Defines Sensor model # DHT22 (RTH03)
DHT dht(DHTPIN, DHTTYPE);  // Defines the Temp/Humd Sensor
float t = 0;  // temp
float h = 0;  // rel. humd.
float f = 0;  // temp in f
float hi = 0;  // heat index
char rh[6];  // Stores Relative Humidity
char tempC[6];  // Stores Temperature in °C
char tempF[7];  // Stores Temp in F
char heatIndex[7];  // Stores heat index
char degree[3] = {176, 67};  // Stores °C symbol
char degreeF[3] = {176, 70};  // Stores °F symbol
// LCD Display
U8GLIB_ST7920_128X64_4X u8g(41, 42, 43);  // Defines LCD pins (SPI: EN = 41, RW = 42, RS = 43)
// GPS Module
GPS610F gps(17, 16, 28, 26, 44, 27, 9600);  // Defines GPS pins (SDI, SDO1, SDO2, PIO, PPS, RST, baudRate)
String gpsData;
char charGPS[82] = "";
String strnmeaProto;
String strutcTime;
String strgpsStatus;
String strlatitude;
String strnsIndicator;
String strlongitude;
String strewIndicator;
String strspeedOverGnd;
String strcourseOverGnd;
String strutcDate;
String strmagVarDegrees;
String strmagVarDirection;
String strmodeIndicator;
String strcheckSum;
char nmeaProto[6] = "";
char utcTime[11] = "";
char gpsStatus[2] = "";
char latitude[11] = "";
char nsIndicator[2] = "";
char longitude[11] = "";
char ewIndicator[2] = "";
char speedOverGnd[6] = "";
char courseOverGnd[6] = "";
char utcDate[7] = "";
char magVarDegrees[6] = "";
char magVarDirection[2] = "";
char modeIndicator[2] = "";
char checkSum[3] = "";
char tempTime[9] = "";
char tempDate[9] = "";
char tempLat[12] = "";
char tempLong[13] = "";
// RF Module
RFZuluArduino rf(15, 14, 2, 3, 4, 5, 4800);  // Defines the RF module's pins (rx1, tx1, RTS, CTS, RST, PD, baudRate)
//Data Logger
const int chipsSelect = 10;
File Data;
String Header = "DATE(utc)  TIME(utc)  STATUS  MODE  LATITUDE(deg)  LONGITUDE(deg)  SPEED(km)  COURSE(deg)  Temperature(C)  Temperature(F)  Humidity(%RH)  Heat Index(F)  Pressure(kPA)  Altitude(m"; //CPM  uSV/hr";
int dcounter = 0;
//Geiger Counter
unsigned int gcount = 0;
unsigned int countStartTime = 0;
int countsPerMinute;
float coefficientOfConversion = 140.0 / 60000.0;
float sV = 0;
String str;  // temporary string
int draw_state = 0;
int tracker = 0;

void setup() {
  pinMode(53, OUTPUT);
  dht.begin();
  if (!SD.begin(10, 11, 12, 13)) {
    // see if the card is present and can be initialized:
    u8g.firstPage();
    do {
      drawCardError();
    }
    while (u8g.nextPage());
    while (1);  // don't do anything more:
  }
  Serial1.begin(9600);
  // start serial port for geiger counter
}

void loop() {
  delay(1000);
  //----- Get Sensor Data -----//
  // Temp/Humid
  h = dht.readHumidity();
  t = dht.readTemperature();
  f = dht.readTemperature(true);
  /*if (isnan(h) || isnan(t) || isnan(f)) {  // check for failed reading from sensor
    return;
    }*/
  hi = dht.computeHeatIndex(f, h);
  // Pressure Sensor
  press_pKa = PressSens.calculatePressurekPa();
  alt_ft = PressSens.calculateAltitudeFt(press_pKa);
  // GPS
  gpsData = gps.getData();
  strnmeaProto = gps.dataFields(0);
  strutcTime = gps.dataFields(1);
  strgpsStatus = gps.dataFields(2);
  strlatitude = gps.dataFields(3);
  strnsIndicator = gps.dataFields(4);
  strlongitude = gps.dataFields(5);
  strewIndicator = gps.dataFields(6);
  strspeedOverGnd = gps.dataFields(7);
  strcourseOverGnd = gps.dataFields(8);
  strutcDate = gps.dataFields(9);
  strmagVarDegrees = gps.dataFields(10);
  strmagVarDirection = gps.dataFields(11);
  strmodeIndicator = gps.dataFields(12);
  strcheckSum = gps.dataFields(13);

  //----- Convert to Transmit -----//
  // Temp/Humid
  floatToString(rh, h, 1);  // relative humidity
  floatToString(tempC, t, 1);  // temperature in C
  floatToString(tempF, f, 1);  // temp in F
  floatToString(heatIndex, hi, 1);  // heat index
  // Pressure Sensor
  str = String(FT_TO_M(alt_ft));  // convert altitude in ft to m
  str.toCharArray(charAlt, 5);  // covert string to char array
  floatToString(charPress, press_pKa, 2);
  // GPS Module
  gpsData.toCharArray(charGPS, 80);  // convert string to char array
  strnmeaProto.toCharArray(nmeaProto, 6);
  // time
  strutcTime.toCharArray(utcTime, 11);
  tempTime[0] = utcTime[0];
  tempTime[1] = utcTime[1];
  tempTime[2] = ':';
  tempTime[3] = utcTime[2];
  tempTime[4] = utcTime[3];
  tempTime[5] = ':';
  tempTime[6] = utcTime[4];
  tempTime[7] = utcTime[5];
  strgpsStatus.toCharArray(gpsStatus, 2);
  // latitude
  strlatitude.toCharArray(latitude, 11);
  strnsIndicator.toCharArray(nsIndicator, 2);
  tempLat[0] = latitude[0];
  tempLat[1] = latitude[1];
  tempLat[2] = 176;   // °
  tempLat[3] = latitude[2];
  tempLat[4] = latitude[3];
  tempLat[5] = latitude[4];
  tempLat[6] = latitude[5];
  tempLat[7] = latitude[6];
  tempLat[8] = 39;  // '
  tempLat[9] = ' ';
  tempLat[10] = nsIndicator[0];
  // longitude
  strlongitude.toCharArray(longitude, 11);
  strewIndicator.toCharArray(ewIndicator, 2);
  tempLong[0] = longitude[0];
  tempLong[1] = longitude[1];
  tempLong[2] = longitude[2];
  tempLong[3] = 176;   // °
  tempLong[4] = longitude[3];
  tempLong[5] = longitude[4];
  tempLong[6] = longitude[5];
  tempLong[7] = longitude[6];
  tempLong[8] = longitude[7];
  tempLong[9] = 39;  // '
  tempLong[10] = ' ';
  tempLong[11] = ewIndicator[0];
  strspeedOverGnd.toCharArray(speedOverGnd, 6);
  strcourseOverGnd.toCharArray(courseOverGnd, 6);
  // date
  strutcDate.toCharArray(utcDate, 7);
  tempDate[0] = utcDate[0];
  tempDate[1] = utcDate[1];
  tempDate[2] = '/';
  tempDate[3] = utcDate[2];
  tempDate[4] = utcDate[3];
  tempDate[5] = '/';
  tempDate[6] = utcDate[4];
  tempDate[7] = utcDate[5];
  strmagVarDegrees.toCharArray(magVarDegrees, 6);
  strmagVarDirection.toCharArray(magVarDirection, 2);
  strmodeIndicator.toCharArray(modeIndicator, 2);
  strcheckSum.toCharArray(checkSum, 3);
  // transmit the data
  rf.transmit(gpsData, tempC, rh, charPress);
  //-----Writes Data to SD Card-----//
  Data = SD.open("DATA", FILE_WRITE);
  if (!Data) {
    u8g.firstPage();
    do {
      drawFileError();
    }
    while (u8g.nextPage());
    while (1);  // don't do anything more:
  }
  dcounter++;
  if (dcounter == 1) {
    Data.println(Header);
  }
  Data.print(strutcDate + "     " + strutcTime + "   " + strgpsStatus + "      " + strmodeIndicator + "     " + strlatitude + "     " + strlongitude + "     " + strspeedOverGnd + "        " + strcourseOverGnd + "          ");
  Data.print(t);
  Data.print("          ");
  Data.print(f);
  Data.print("            ");
  Data.print(h);
  Data.print("         ");
  Data.print(hi);
  Data.print("            ");
  Data.print(press_pKa);
  Data.print("         " + str + "  ");
  Data.flush();
  Data.print(countsPerMinute);
  Data.print("  ");
  Data.println(sV, 5);
  Data.flush();
  //----- Output to LCD Display -----//
  u8g.firstPage();
  do {
    draw();
  }
  while (u8g.nextPage());
  tracker++;
  if (tracker <= 2) {
    draw_state = 0;
  } else if (tracker <= 5) {
    draw_state = 1;
  } else if (tracker <= 8) {
    draw_state = 2;
  } else {
    tracker = 3;
  }
}

//----- LCD Display Drawings -----//
void drawCardError() {
  u8g.setColorIndex(1);
  u8g.setFont(u8g_font_baby);
  u8g.drawStr(12, 32, "Card Failed, or not present");
}

void drawFileError() {
  u8g.setColorIndex(1);
  u8g.setFont(u8g_font_baby);
  u8g.drawStr(5, 32, "Error opening DATA");
}

void draw(void) {
  LCDprepare();
  switch (draw_state) {
    case 0:
      AECLlogo();
      break;
    case 1:
      SensorInfo();
      break;
    case 2:
      GpsInfo();
      break;
  }
}

i am having trouble formatting, someone please help me with this!

fixed, I have remvoed some of the ending code thought. They were just functions for the lcd

The section under //-----Writes Data to SD Card-----// should go in setup().

yes thank you, i realize that my program opens the file when it already opens causing a memory leak, that and also the string class is apparently a big issue

Try removing all the u8g stuff to check for SPI problems.

Manan, if you have actually figured out the real problem and fixed it, could you write an answer that will help the next person with this problem? (As recommended on the help page, at [meta](http://meta.stackexchange.com/questions/17463/can-i-answer-my-own-questions-even-if-i-knew-the-answer-before-asking, etc.). Or are you just saying that you fixed the formatting?

@Manan as you can see, David Cary's remark still applies. Today your question was bumped to the homepage again. Please, write an answer and mark it as accepted. You will gain reputation points, and this question will stop being bumped to the homepage every now and then...

Might be a flaky SD card, you get that sometimes. Try changing to another card and see if it helps.
SD card formatter tool might also be useful: https://www.sdcard.org/downloads/formatter_4/

Answered by OP in the comments
"fixed, I have remvoed some of the ending code thought. They were just functions for the lcd"

I believe that comment was just saying they had solved their formatting problems with the question. However, their next comment: http://arduino.stackexchange.com/questions/4419/sd-card-fails-to-write-every-5-or-6-minntes#comment9656_4419 does make me think they found that a memory leak was the cause of the problem but unfortunately didn't bother to properly answer their own question.

Are you sure there are no rollovers / overflows? Keep in mind the limitations of FAT16, max volume size is 2GB, and only with the max sector size of 512B.
At minimum dcounter will overflow in 9 hours if you log every second.

OK, it looks like this question is going to be floating with not accepted answer for all of eternity since the poster clearly isn't responding to comments.
But if it works for a few minutes and then dies it's probably something silly like opening the same file every second and never closing that's the cause of the issues rather than a bad SD card or a counter that will overflow after 9 hours.


text:
Stepper motor clock
I am currently using an Adafruit motor shield on my arduino uno for the first time.
The idea is turning the stepper motor with basicly 1RPM. But i just cant do it.
This is the first time working with this setup, and i dont know what to do.
Can you people help me?
i'm using the Arduino Uno with ADAFRUIT motorshield. The steppermotor is 48steps / rev
DATASHEET
The code i have at the moment:
#include <AFMotor.h>

AF_Stepper motor(48, 1);

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

  motor.setSpeed(1);

  motor.step(48, FORWARD, DOUBLE);
  motor.release();
  delay(10);
}

void loop () {
  motor.step(48, FORWARD, DOUBLE);
}

Greetings from Holland.

You'll need to provide more inout if you want to get some useful answers: source code uploaded to your board? Board type? Stepper references with link to datasheet? Power supply? What have you done so far?

When you execute this program, what happens? Nothing at all? Most of the time, when encountering problems with stepper motors, the root cause is the wiring: did you check it twice?

That's not a 48-step stepper. That's one with 64 steps per revolution and with 64 reduction gearing inside. So you end up with 64*64=4096 steps per revolution of the outer shaft. So it's moving 85 times too slow. Hope that helps. Greetings back from the Netherlands.

I wonder if employing a motor with 180 steps which is divisible by 60 would be of any advantage? Here is a reference page which may assist you in evaluating the best component for your design: Introduction to Stepper Motors

But i just cant do it. - can't do what? I don't understand what you are asking. What is your question? How is it wired? What happens when you run the code? I'm going to close this question. Feel free to edit it with new information. Thanks for your understanding and cooperation!

If the stepper gives you 48 steps and an hour has 60, you need to provide 1,25 rounds in one hour given you only move the minute hand. Then with some gearing you should be able to move the hour hand every round there.
So the best way to do this is to is either to move the hand once and then delay 1 minute, 1 minute = 60 seconds x 1000 milliseconds.
You then need to figure out what it requires of the stepper motor to make 1 step, with some stepper motors you need to move forward 1 cycle and then back a half. to make a step. You should find all this in the documentation.
Please provide feedback in the comments below so we can improve the answer.

Most stepper drivers can do microstepping.

Unsure what you need help with, but this might help:
I believe that the 28BYJ-48 has a lot more steps per rotation, around 4000 I think. I had a few problems myself getting this to work. It also has four steps to cycle through, not 2.
Take a look at this library which has the 28BYJ-48 set to default. CustomStepper


text:
Combine Code Arduino GSM Shield and Adafruit GPS Shield
I have a problem to combine both code for Arduino GSM Shield and Adafruit Ultime GPS Shield. I already change my code to the basic one like examples. I think i found the problem. The problem is when i want to do get request to the url/web.
Here is the link to the Adafruit Ultimate GPS Shield.
Adafruit Library
Adafruit Ultimate GPS Shield Info
My code base on example of Arduino GSM Library (GSM Web Client) and Adafruit GPS Library (Parsing)
This is the code that make my code not working. If i put the code i do not receive any data at serial.

 // if you get a connection, report back via serial:
 if (client.connect(server, port))
 {
    Serial.println("connected");
   // Make a HTTP request:
   client.print("GET ");
   client.print(path);
   client.println(" HTTP/1.1");
   client.print("Host: ");
   client.println(server);
   client.println("Connection: close");
   client.println();
 }
 else
 {
  // if you didn't get a connection to the server:
  Serial.println("connection failed");
 }

This is the basic code that working so far

// ********************************************
//   GPS Library
// ********************************************
#include <Adafruit_GPS.h>
#include <SoftwareSerial.h>
#include <stdlib.h>

// ********************************************
//   GSM Library
// ********************************************
#include <GSM.h>

// ********************************************
//   Sim Card Pin Number if available
// ********************************************
#define PINNUMBER ""

// ********************************************
//   Set Up APN data for GPRS Connection
// ********************************************
#define GPRS_APN       "Maxis" // replace your GPRS APN
#define GPRS_LOGIN     "maxis"    // replace with your GPRS login
#define GPRS_PASSWORD  "wap" // replace with your GPRS password

// ********************************************
//   Initialize GSM Library
// ********************************************
GSMClient client;
GPRS gprs;
GSM gsmAccess;

// ********************************************
//   Setup Arduino to browse URL/web through GPRS
//   The code below will setup path like:
//   http://arella.com.my/urltomysql.php?firstname=Muhammad&lastname=Faiz
//   When Arduino browse the web, it will submit firstname:Muhammad
//   and lastname:Faiz into database. I want to store GPS data into database       later
// ********************************************
char server[] = "arella.com.my";
char path[] = "/urltomysql.php?firstname=Muhammad&lastname=Faiz";
int port = 80; // port 80 is the default for HTTP

// ********************************************
//  Set Adafruit GPS to use software serial on pin
//  D9 & D10 on Arduino. Use Jumper Wire from D7,D8 to D9,D10
// ********************************************
SoftwareSerial mySerial(10, 9);
Adafruit_GPS GPS(&mySerial);

// Set GPSECHO to 'false' to turn off echoing the GPS data to the Serial console
// Set to 'true' if you want to debug and listen to the raw GPS sentences.
#define GPSECHO  false

// this keeps track of whether we're using the interrupt
// off by default!
boolean usingInterrupt = false;
void useInterrupt(boolean); // Func prototype keeps Arduino 0023 happy

//***********************************************
// convert NMEA GPS Format to Google Map Format
//***********************************************
int degLatInt, degLongInt;
float minLatFloat, minLongFloat, googleMapsLat, googleMapsLong;
char* lat_str = new char[10];
char* long_str = new char[10];
char degLatString[5], degLongString[5];

void setup()
{
   Serial.begin(115200);
   gsmAccess.begin(PINNUMBER);
   gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD);

   boolean notConnected = true;
   while(notConnected)
   {
      if((gsmAccess.begin(PINNUMBER)==GSM_READY) &
         (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD)==GPRS_READY))
         notConnected = false;
      else
      {
         Serial.println("Not connected");
         delay(1000);
      }
   }
   // If i enable the code below, my code not working.
   /* if (client.connect(server, port))
      {
      Serial.println("connected");
      // Make a HTTP request:
      client.print("GET ");
      client.print(path);
      client.println(" HTTP/1.1");
      client.print("Host: ");
      client.println(server);
      client.println("Connection: close");
      client.println();
  } */

 //***********************************************
 // Setup Adafruit GPS Shield
 //***********************************************
 // connect at 115200 so we can read the GPS fast enough and echo without  dropping chars
 // also spit it out

 Serial.println("Adafruit GPS library basic test!");

 // 9600 NMEA is the default baud rate for Adafruit MTK GPS's- some use 4800
 GPS.begin(9600);

 // uncomment this line to turn on RMC (recommended minimum) and GGA (fix     data) including altitude
 GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);
 // uncomment this line to turn on only the "minimum recommended" data
 //GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCONLY);
 // For parsing data, we don't suggest using anything but either RMC only or RMC+GGA since
 // the parser doesn't care about other sentences at this time

 // Set the update rate
 GPS.sendCommand(PMTK_SET_NMEA_UPDATE_1HZ);   // 1 Hz update rate
 // For the parsing code to work nicely and have time to sort thru the data, and
 // print it out we don't suggest using anything higher than 1 Hz

 // Request updates on antenna status, comment out to keep quiet
 GPS.sendCommand(PGCMD_ANTENNA);

 // the nice thing about this code is you can have a timer0 interrupt go off
 // every 1 millisecond, and read data from the GPS for you. that makes the
 // loop code a heck of a lot easier!
 useInterrupt(true);

   delay(1000);
}

// Interrupt is called once a millisecond, looks for any new GPS data, and stores it
SIGNAL(TIMER0_COMPA_vect) {
   char c = GPS.read();
   // if you want to debug, this is a good time to do it!
   #ifdef UDR0
   if (GPSECHO)
   if (c) UDR0 = c;
   // writing direct to UDR0 is much much faster than Serial.print
   // but only one character can be written at a time.
   #endif
}

void useInterrupt(boolean v) {
   if (v)
   {
      // Timer0 is already used for millis() - we'll just interrupt somewhere
      // in the middle and call the "Compare A" function above
      OCR0A = 0xAF;
      TIMSK0 |= _BV(OCIE0A);
      usingInterrupt = true;
   } else
   {
      // do not call the interrupt function COMPA anymore
      TIMSK0 &= ~_BV(OCIE0A);
      usingInterrupt = false;
   }
}

uint32_t timer = millis();

void loop()                     // run over and over again
{
   // if a sentence is received, we can check the checksum, parse it...
   if (GPS.newNMEAreceived()) {
   // a tricky thing here is if we print the NMEA sentence, or data
   // we end up not listening and catching other sentences!
   // so be very wary if using OUTPUT_ALLDATA and trytng to print out data
   //Serial.println(GPS.lastNMEA());   // this also sets the newNMEAreceived()  flag to false

   if (!GPS.parse(GPS.lastNMEA()))   // this also sets the newNMEAreceived() flag  to false
      return;  // we can fail to parse a sentence in which case we should just wait for another
   }

   // if millis() or timer wraps around, we'll just reset it
   if (timer > millis())  timer = millis();
   // approximately every 2 seconds or so, print out the current stats
   if (millis() - timer > 5000) {
      timer = millis(); // reset the timer

      Serial.print("\nTime: ");
      Serial.print(GPS.hour+8, DEC); Serial.print(':');
      Serial.print(GPS.minute, DEC); Serial.print(':');
      Serial.print(GPS.seconds, DEC); Serial.print('.');
      Serial.println(GPS.milliseconds);
      Serial.print("Date: ");
      Serial.print(GPS.day, DEC); Serial.print('/');
      Serial.print(GPS.month, DEC); Serial.print("/20");
      Serial.println(GPS.year, DEC);
      Serial.print("Fix: "); Serial.print((int)GPS.fix);
      Serial.print(" quality: "); Serial.println((int)GPS.fixquality);
      if (GPS.fix) {
         /////////// Latitude /////////////
         // Convert NMEA Latitude to String
         dtostrf(GPS.latitude, 7, 4, lat_str); //convert GPS.latitude from float to String. 7 - means 8 characters long ; 4 - means 4 decimal point

         // Get Degree substring from latitude String
        strncpy(degLatString, lat_str, 1); // Get Degree from Full Latitude String. Example 311.7799 - Get 3

        // Get Minutes substring from latitude String
        char* minLatString = lat_str + 1; // Move pointer up 1 position. Example 311.7799 will move to 11.7799

        // Convert Deg String to int
        degLatInt = atoi(degLatString);

        // COnvert Min String to float
        minLatFloat = atof(minLatString);

        //Convert NMEA latitude to Google Maps latitude
        googleMapsLat = degLatInt + (minLatFloat / 60);
        Serial.print("Google Map Latitude: ");
        Serial.println(googleMapsLat, 4);

        //////////// Longitude /////////////
        // Convert NMEA Longitude to String
        dtostrf(GPS.longitude, 8, 4, long_str); //convert GPS.latitude from float to String. 8 - means 9 characters long ; 4 - means 4 decimal point

        // Get Degree substring from latitude String
        strncpy(degLongString, long_str, 3); // Get Degree from Full Latitude String. Example 10141.91699 - Get 141

        // Get Minutes substring from latitude String
        char* minLongString = long_str + 3; // Move pointer up 3 position. Example 10141.9169 will move to 41.7799

        // Convert Deg String to int
        degLongInt = atoi(degLongString);

        // COnvert Min String to float
        minLongFloat = atof(minLongString);

        //Convert NMEA latitude to Google Maps latitude
        googleMapsLong = degLongInt + (minLongFloat / 60);
        Serial.print("Google Map Longitude: ");
        Serial.println(googleMapsLong, 4);

        Serial.print("Speed (KM): "); Serial.println(GPS.speed * 1.85);
      }
   }
}

I'm working on the same project (with the same hardware) and I have an identical problem.
Seems like an HTTP request blows up your serial monitor, but is not true in my view.
In fact, if you use the TinyGPS++ library will not have this problem anymore.
Take as reference the GsmWebClient example, you can add a few lines of code.
This is all you need for parse with tinyGPS:
#include <AltSoftSerial.h>

#include <TinyGPS++.h>

TinyGPSPlus gps;

AltSoftSerial ss;

//Add this to your sketch, in loop() or setup()

ss.begin(9600);

while (ss.available() > 0)

    if (gps.encode(ss.read())) {
        gps.location.lat(); //return latitude as a double
        gps.location.lng(); //return longitude as a double
}

Does that code fix the issue?

Thanks penguin for editing!
This is not a real fix for the error, it's a bypass.. I think the problem is given by AdafruiGPS lib, and everything is solved using TinyGPS. This code is all you need for get the coordinates with the new library.


text:
Atmel STK500 and Atmel Studio
Is the Atmel STK500 worth using as a AVR programmer and Dev board? I am starting to get to into AVR programming with Atmel studio. I plan on purchasing the AVRDragon and also looking into purchasing the Atmel STK500. This might be too broad of a question, but are their any benefits in using the Atmel STK500?
Atmel STK500

From reports, no. Stick to the Dragon.

Realize you don't need any of this - any ATmega-based Arduino with it's existing bootloader will do, completely unmodified.

@ChrisStratton - yes of course, but the Arduino does not have debugging and its also a pain when switching from prototyping on the arduino to flashing the AVR.

Did you try connecting to the ISP header?

No, never tried. Perhaps I should.

It's pretty antique (doesn't even has usb). I'm not even sure if it does debug-wire. Stick to the Dragon. Maybe buy a cheap USBASP on eBay, for spare/convenience. They work great for ISCP programming.

Benefits of STK500? Sure:
- It has push buttons
- It has LEDs
- It has easy accessible connectors to any controller pin

Actually that's all. If you want/need to make use of this, buy both. Use the STK for "rapid prototyping" and the Dragon for debugging.
But if your budget allows it, have a look at the STK600 instead of 500. It's more expensive, but not so "old-fashioned", and it has much more features.


text:
Newbie has difficulty compiling unedited svn Arduino code that should work
I'm having some trouble getting this arduino code to compile. It's not my project, but it should compile totally fine. Having never worked with the Arduino before, these errors are a bit intimidating, but I'll try to be specific enough for someone to get a guess. So...
I have this directory with these files:  .
I found that the ArduCAM_OSD.ino has the loop and setup functions. When I try to compile the ino and solution I get these errors:
In file included from ArduCam_Max7456.cpp:4:

ArduCam_Max7456.h:78: error: expected class-name before '{' token

ArduCam_Max7456.h:84: error: 'uint8_t' has not been declared

ArduCam_Max7456.h:84: error: 'uint8_t' has not been declared

ArduCam_Max7456.h:87: error: 'uint8_t' has not been declared

ArduCam_Max7456.h:91: error: 'uint8_t' has not been declared

ArduCam_Max7456.h:91: error: 'uint8_t' has not been declared

ArduCam_Max7456.h:98: error: 'size_t' does not name a type

ArduCam_Max7456.h:99: error: 'uint8_t' has not been declared

ArduCam_Max7456.h:100: error: 'BetterStream' has not been declared

ArduCam_Max7456.h:102: error: 'uint8_t' does not name a type

ArduCam_Max7456.cpp: In member function 'void OSD::init()':

ArduCam_Max7456.cpp:38: error: 'video_mode' was not declared in this scope

ArduCam_Max7456.cpp: In member function 'void OSD::setMode(int)':

ArduCam_Max7456.cpp:109: error: 'video_mode' was not declared in this scope

ArduCam_Max7456.cpp:110: error: 'video_center' was not declared in this scope

ArduCam_Max7456.cpp: In member function 'int OSD::getMode()':

ArduCam_Max7456.cpp:123: error: 'video_mode' was not declared in this scope

ArduCam_Max7456.cpp: In member function 'int OSD::getCenter()':

ArduCam_Max7456.cpp:138: error: 'video_center' was not declared in this scope

ArduCam_Max7456.cpp: At global scope:

ArduCam_Max7456.cpp:162: error: prototype for 'void OSD::setPanel(uint8_t, uint8_t)' does
not match any in class 'OSD'

ArduCam_Max7456.h:84: error: candidate is: void OSD::setPanel(int, int)

ArduCam_Max7456.cpp: In member function 'void OSD::openPanel()':

ArduCam_Max7456.cpp:177: error: 'row' was not declared in this scope

ArduCam_Max7456.cpp:177: error: 'col' was not declared in this scope

ArduCam_Max7456.cpp: In member function 'void OSD::closePanel()':

ArduCam_Max7456.cpp:206: error: 'row' was not declared in this scope

ArduCam_Max7456.cpp: At global scope:

ArduCam_Max7456.cpp:212: error: prototype for 'void OSD::openSingle(uint8_t, uint8_t)' does
not match any in class 'OSD'

ArduCam_Max7456.h:91: error: candidate is: void OSD::openSingle(int, int)

ArduCam_Max7456.cpp:236: error: no 'size_t OSD::write(uint8_t)' member function declared in
class 'OSD'

ArduCam_Max7456.cpp:251: error: prototype for 'void OSD::control(uint8_t)' does not match
any in class 'OSD'

ArduCam_Max7456.h:87: error: candidate is: void OSD::control(int)

ArduCam_Max7456.cpp:268: error: prototype for 'void OSD::write_NVM(int, uint8_t*)' does not
match any in class 'OSD'

ArduCam_Max7456.h:99: error: candidate is: void OSD::write_NVM(int, int*)

The most notable of these is the first error. Here's the class, in a header file, throwing the error:
class OSD: public BetterStream
{
  public:
    OSD(void);
    void init(void);
    void clear(void);
    void plug(void);
    void setPanel(uint8_t start_col, uint8_t start_row);
    void openPanel(void);
    void closePanel(void);
    void control(uint8_t ctrl);
    void detectMode(void);
    void setMode(int mode);
    void setBrightness();
    void openSingle(uint8_t x, uint8_t y);
    int getMode(void);
    int getCenter(void);
    virtual int     available(void);
    virtual int     read(void);
    virtual int     peek(void);
    virtual void    flush(void);
    virtual size_t write(uint8_t c);
    void write_NVM(int font_count, uint8_t *character_bitmap);
    using BetterStream::write;
  private:
    uint8_t start_col, start_row, col, row, video_mode, video_center;
};

Now, since I know confidently that this should compile, I'm convinced that I've made some
small syntactical error that can be fixed easily. In case anyone needs to see more of the files, you can access them all on the google code page here. Alternatively, please feel free to ask any questions.

Is it your own code? I guess you have not properly imported the complete project. This is just a class. where are other files? the main? Or may be you have not properly installed the compiler of this IDE. Which IDE is this?

is it your complete class? you have not included  ´BetterStream` and you are inheriting it.

add #include before the class definition

@Mahmood I'm using Arduino IDE 1.0.5-r2 . It's not my own code. All of the code is at the link at the bottom,  though I'll look for a main. I believe I was told to look for setup and loop to determine the ino to compile, which is in ArduCAM_OSD.ino .

add #include"BetterStream" if it works. tell me

@Mahmood adding "#include "BetterStream.h" did work to get rid of all those errors after I went and found a copy of BetterStream.h. Thanks!

@Mahmood I only have one more error. One of my include statements is failing, even though the file is indeed in the same directory. Another file is referenced the same exact way, yet it can't see this one particular file.

which file? name the file I will see

#include "menu.h"
#include "c++.h"
In file included from AP_Common.cpp:16:
/AP_Common.h:38:35: error: c++.h: No such file or directory
What's weird is that menu.h and c++.h exist in the same location, yet menu is included fine.

I guess you are missing some files in the library of your installation of IDE. Because these files seems to be libraries. Does you ide works perfectly? Is it your first program you are testing? try something other working one.

@Mahmood I found that the issue was that I wasn't using the IDE to include all the libraries so it wasn't seeing any of the references. After including all of the relevant libraries I finally got it to compile. Thanks so much!

This is really ambitious for a first project. Do yourself a favor and go through the basic tutorials before you start frying components. Learning how to include libraries properly is something you will pick up if you go through the basics. Arduino isn't "safe" - it's easy to fry the Arduino and easy to melt components too.

It sounds like you are missing the libraries that the project was build for. BetterStream was part of the library system of the Ardu projects at diydrones.com
Normally for Ardu projects they use a modified version (their own) of the Arduino IDE but I don't know if the Arducam project works the same way.
I think you will find a better answer over in the support forum as http://www.diydrones.com which is where Arducam comes from.
Some of the source files look like they replace libraries so it might be that you just need a different core from diyd


text:
Arduino output pin from 5V to 3.3V
I just have a question regarding Arduino output-pins and Voltage divider, because I am getting other results than what my calculations are giving me.
I have measured the output-pin (from the Arduino) at 4.74V, according to my caulculations I will have and output voltage of 3.39V, with R1 = 4k ohm and R2 = 10k ohm, but when I use my multimeter to measure I read a voltage of 0.97V.
I have tested with a 9V battery, measured to 8.72V. With the same resistors, the calculations gives me 6.23V as output, when I use my multimeter I can read a output of 6.21 which I consider as ok.
So my question is, why is my output from the Arduino only 0.97V with the voltage divider?
For information: I am using Arduino OSEPP Uno R3 Plus.
Hope someone can give me helpfull information.
***************************************update********************************************
My code:
int echoPin = 7;
int trigPin = 6;

int SignalPin = 10;

void setup(){

  pinMode(echoPin, INPUT);
  pinMode(trigPin, OUTPUT);

}

void loop(){

  float distanceCentimeters;
  int pulseLenMicroseconds;

  digitalWrite(trigPin, LOW);
  delayMicroseconds(20);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(100);
  digitalWrite(trigPin, LOW);

  pulseLenMicroseconds = pulseIn(echoPin, HIGH);

  distanceCentimeters = pulseLenMicroseconds / 29.387 / 2;

  if(distanceCentimeters <= 35 && distanceCentimeters >= 10){

      digitalWrite(SignalPin, HIGH);

  } else {

      digitalWrite(SignalPin, LOW);

  }

  delay(400);

}

Image of the setup (not with Raspberry Pi).

4kohm is a strange value. Are you sure about it?

Are you sure the Arduino pin is actually driven as an output, rather than being an input with the internal pull-up active?  Your measured .97 V could be a result of your resistive divider being fed through about 35K ohms of internal resistance, which is a quite plausible value for the effective resistance of the "weak" internal pull-up feature.  You can tell by measuring the voltage at the high side of R1 - with an output, this should still be close to 5v, but with a pull-up it will may be only slightly higher than the low side of R1.

I assume you are planning to connect to something using 3.3V. A resistive divider is a poor solution. It may be OK for a high impedance connection, but you would be better to use other solutions e.g. Series resistor and diode clamp.

Thank you guys for answering and giving useful information! I have updated the post with my code and a picture of the connection. Thought that would be more helpful. I have measured the R1, and its high side is slightly higher than the low side.I am going to connect it to a Raspberry Pi, where the GPIO pins have a tolerance of 3.3V.

If the high side of R1 is only "slightly" higher than the low side, then you do not have the pin configured as an output.

Your code does not configured SignalPin as an output, but only trigPin.
As already explained in comments, your observed voltage is due not really to the voltage divider you constructed, but rather one formed by the "weak" internal pull-up resistance and your external resistors.  From your measurement, it appears the value of the weak internal pull-up is about 35K, which is within the range of expectations.  That and your 4K external form the top of the divider (39K) while your 10K forms the lower half, yielding about a fifth of the supply voltage.
In some versions of the Arduino library, writing to an input pin enables and disables the internal pull-up resistor, so you could have observed your program seeming to control the pin - but at minimal drive strength.
To get the desired behavior, you merely need to add
pinMode(SignalPin, OUTPUT);

I got one more question, and I don´t expect an answer since it´s towards the RPi. I have written a program that should write out a text if the GPIO-pin is high or low. I have tested it with a button an the RPi´s own 3.3V output-pin. When I press the button it changes. But when I use the Signalpin from the Arduino it does not change at all. The pin has 3.24V now, same as I get with the RPi 3.3V pin. Do you have any idea what it could be?

Try putting several seconds of delay after setting the output pin state, to make sure the pi has ample time to see it.  Of course that is excessive, but you could see see if you can use an interrupt mode on the pi.  Note the existence of raspberrypi.stackexchange.com if your challenges become mostly about the pi; right now it's not clear which end the problem is on.

Signalpin from the Arduino would be 5V. How are you giving it to the 3.3V Pi?

That's the purpose of the resistive divider.  In practice, the 4k series resistance will probably do the job by itself, though slew rate will be limited with this high an impedance.

Did not have time to test this before, but now I have. Have set the delay for some seconds, but still nothing happens. The program on the Pi is working fin with the button and using its own 3.3V pin (measuring it to 3.24). I measure the Arduino output-pin to 3.26V but the program is not registering any changes. Have also test with placing a object in front of the sensor so the output stays at 3.26V, but nothing happens. Can it be related to the current?

Not if you measure it as 3+ volts while connected to the pi - that should indicate it is fine.  You do have a common ground, right?

Yes, I use the GND on the Arduino and that is connected to the - on the breadboard. From the voltage divider the ground goes back to - on the breadboard. But when I test the button with the RPi´s own 3.3V output pin I don´t use GND.


text:
Pixy(CMUcam5) robot Distance code
Can anyone help me with the code-ing to allow the robot to stop at a certain distance when the robot is approaching the tracked object. I am trying to implement it as a colour tracking wheel chair. For Example, the motorized wheelchair is able to track the colour of the shirt of the person infront is wearing and follow the person, and at the same time it is able to leave a distance between the person infront and the wheelchair to prevent collision.
the pixy robot : https://learn.adafruit.com/pixy-pet-robot-color-vision-follower-using-pixycam/overview
The code :https://learn.adafruit.com/pixy-pet-robot-color-vision-follower-using-pixycam/the-code
Currently the code is only able to track the object till it reaches the object. But my objective is to let it chase the object, but at the same time, leaving a 1 metre distance
away from the object.
Please help me. Thank you

Try to play with this one:
int forwardSpeed = constrain(400 - (size/256), -100, 400);

By changing the value of 256 and 400, not at the same time though, you better use 2 potentiometer to change those values. That's a trial and error though, I hope this will give you an idea.

Old question, but I'd simply use the angle of the Pixy tilt mechanism. If the camera is mounted low (on a wheelchair) and looking up (to see a t-shirt), the angle will be more "up" when the t-shirt is close.
void loop()
{
   if(tiltAngle < 45) // Angle in degrees
      moveWheelChairForward();
}

However, if someone bends down, the tilt angle will go down, so the wheelchair will ram them! Thus, a proximity sensor is probably still going to be needed.


text:
Arduino GSM Shield not responding?
I'm trying to get my Arduino GSM shield working with the example "Send SMS" code provided. However, when I upload and compile the program, the serial monitor displays "SMS Messages Sender" and nothing else occurs.
Would greatly appreciate it if someone can tell me where I could have gone wrong.
EDIT : I'm currently using the Arduino Mega. The shield I'm using is the Arduino GSM Shield. I'm following the guide provided by the Arduino's website with the code part of the example that comes with the Arduino program, see Sending a SMS message. Attached is what is shown on the monitor.
I am using both a USB cable and an external power supply. I have performed the jumper wire modification required for the Mega to work with the shield as well.

Could you provide some more information please? It might be useful to have details of exactly which Arduino board and shield you're using, and what code you're trying to run.

Please, also add the code you have uploaded to your MEGA, rather than just saying "the code provided"; try to ease the job of people who want to help you, thus give a chance to your question of being answered!

This is an old post, but for future people:
The shield may have not been switched on — it has its own power button, which is right next to the SIM card. It's tiny, but it's there.


text:
What is the use of ISP and ICSP in Arduino?
I am trying to connect gsm module with my arduino uno. confused about the use of isp and icsp

What GSM module are you using?  And what is the cause of the confusion?

i hav a module of sim900a and someone advised me to connect it to ard uno using isp or spi. now i m having queries like can we program using isp? why cant i use spi or i2c? how are they different? xcept i2c which uses uart, right?

ISP/ICSP has no role when utilizing a typical, properly functioning Arduino, as the program code compiled from sketches is instead downloaded via a bootloader (either serial, often behind an on-board USB-serial converter, or else directly USB).
The role of ISP in the Arduino ecosystem is mostly limited to:

Loading a bootloader into new chips which do not have one, or have somehow lost theirs (note however that you can buy pre-loaded ATmega328's from many sources at a small premium)
As an alternative program loading scheme when the tiny amount of program memory used by the bootloader must be re-claimed for a particularly large sketch
Programing alternate targets to which the Arduino libraries have been partially ported, especially resource-constrained ones where the bootloader takes up a larger fraction of the total memory, such as the the ATtiny25/45/85
Replacing or modifying the firmware of an on-board USB-serial micro such as the 16u2 on an Uno to perform a different function, such as emulate a keyboard or mouse.  However, this chip can also be programmed over its USB interface in DFU mode.
Programming other non-Arduino devices used in a project (though these often have a different ISP scheme than the ATmega series).

But a typical project using purchased board(s) will involve none of these.

SPI vs. ISP
As jfpoilpret points out, a very popular way of interfacing chips to a microcontroller is the Serial Peripheral Inteface, or SPI.  Like ISP, this is a synchronous (has a distinct clock line) serial interface with a master and a slave, a mode or enable pin, and a distinct data line in each direction.  Some Arduinos use MCUs like the ATmega328p which re-use their SPI pins for ISP (with the reset functioning as the mode pin).
In effect, ISP is a sort of special "SPI-like" interface mode for programming an ATmega - often using the master-mode SPI engine of the programer to do the actual transfers.  But "ISP" applies only when programming an ATmega - the more generic case of communicating with a peripheral would be "SPI".
It's my impression that most GSM modules use asynchronous serial interfaces (ie, utilizing a UART engine), but there may be some which use SPI or other synchronous schemes, at least as an option.

Don't you forget the thousands of devices using the ISP bus as the only way to communicate with them (just like I2C). That makes a common use for ISP in Arduino projects! Although I admit that you don't have to use the 2x3 header for it as you can find MOSI, MISO... on other pins as well, but you could.

@jfpoilpret - no, that is SPI, not ISP.  The ATmega328p happens to use the same pins for both, and they are indeed quite similar - we might consider ISP to almost be a special case of SPI.  But SPI is not a case of ISP.

Damn! How could I make this mistake? Of course you are right! Sorry for the confusion.

point 5 of roles, using that can i program at89c51 or other mcu?

That would depend on the scheme used by the MCU in question.  The at89c51 uses a parallel programming scheme, rather than a serial one.  You probably could build a programmer with an arduino, but would have to look into details such as if you would need an I/O multiplexer to drive all the lines, and if you need a transistor to enable a 12v programming supply, or if you have the version of the chip which programs at 5v.


text:
Send Processing color data into Arduino
I am trying to send color() data from Processing to Arduino.
Here is my code from Processing:
import processing.serial.*;
Serial myPort;

void setup(){
  myPort = new Serial(this, Serial.list()[7], 9600);
}

void draw(){
  color[] c1 = {color(99,0,0),color(255,0,0) };
  for (int i = 0; i < c1.length; i++ ){
    int value = int(red(c1[0]));
    myPort.write(value);
    println(value);
    delay(2000);
  }
}

It sends the 99.0 data to Arduino. Here is the Arduino code for getting:
void setup(){
  Serial.begin(9600);
}

void loop(){
  while(Serial.available() > 0){
    int recieved = Serial.read();
      Serial.print(recieved);
    }
}

The problem is when Arduino receive data it doesn't take one by one. When i watch Arduino serial monitor, the data comes at different chunks like, 9...99...999..9.. etc.
I am trying to send several color info from Processing into arduino, it might be a long array of value. What is the best way to achieve this?

The 'best' solution depends on many things, your skill, the performance of the system, and the other tasks it needs to do in the available time. There are some examples of doing data transfer between Processing and the Arduino in the Arduino example programs. So it is worth looking through them.
There seems to be some inconsistencies in your question.
You wrote "It sends the 99.0 data to Arduino", which has a decimal point.
Yet the code is printing an int i.e.
int value = int(red(c1[0]));
myPort.write(value);

Further, the processing code only looks at the red component of c1[0]:
int value = int(red(c1[0]));

so it can only send a sequence of '9'. So that looks like a bug.
There are a few basic strategies to write data that can be easily read. Two popular ways are:

send fixed length messages, or prefix a message with the size of the
data, and have a fixed format of data. For example, use a one byte
count to say how many colours are being sent, then send three bytes,
in the same order, for each colour
use non-data bytes to separate the data. For example use a ','
between R, G or B and '\n' to mark the end of the data. To keep
things simple, never use those values as data values. That is pretty
much how programming languages work. It is much more complex to read
than fixed format data, but can give more flexibility.

Data is often sent as printable characters (e.g. 173 would be three bytes havig the ASCII values '1', '7', '3'). If it is fixed format, it would always be three bytes. For your purposes, I'd probably send each data byte as two hex characters (ASCII '0' to '9' and 'A' to 'F'. This is slightly more complex than pure binary. However it is fixed format, and more importantly it is easier to test by hand using the Arduino serial monitor, you can just type stuff and it is relatively easy to do.
Pure binary data is much more difficult to fully test, and often relies on a piece of software which also needs testing.
Summary: There are a couple of ways, it is hard to say which is best. For simplicity try to make it simple by being fixed format.

I put the dots for trying to visualise serial monitor in real time. Take them as waiting intervals. My point was Arduino is receiving at different order or rate. i tried sending "\n" with looking at this example but it did not work. Anyway, thanks for the suggestions.

You have to implement a serial protocol.
This can be either binary or ASCII. Binary has the advantage that the messages are short and well structured due to fixed parameter size. ASCII has advantage that you can type the messages into the serial monitor for debugging and typically data bytes are numerical ('0', '1' etc) while message bytes are text ('setcolour' etc) which means conflicting bytes do not have to be escaped.
To get started, try the Messenger library. Note that #include "WProgram.h" has to be changed to #include "Arduino.h" in the .cpp and .h files.
For the set colour message, if you used something like:
setcolour,99,0,0,255,0,0\n
You could use Messenger to parse it like:
Preamble:
#include "Messenger.h"
Messenger message = Messenger(','); //Message values separated by ','

In setup():
message.attach(messageCompleted);

In loop():
while(Serial.available()) {
    byte inbyte = Serial.read();
    message.process(inbyte);
}

Then implement the callback function:
void messageCompleted()
{
    if (message.checkString("setcolour")) {
        colour1[0] = message.readInt();
        colour1[1] = message.readInt();
        colour1[2] = message.readInt();
        colour2[0] = message.readInt();
        colour2[1] = message.readInt();
        colour2[2] = message.readInt();
    }
}

where colour1 and colour2 store the two RGB values.

Thanks for the answer. I am going to try this method. I am so new to programming so excuse my noob questions. First of all, this library seems to be obsolete, can i still use this one? Second question is i do not understand the changing #include thing. i try to use your code as written and it gives 'Messenger does not name a type'.

The library is still good, even though the page recommends to use CmdMessenger I find that that library is more complex than for what I need. To use the library, unzip it and then copy the Messenger folder (under Firmware) into you Arduino library folder (check where it is in preferences) and restart the Arduino IDE. In the file Messenger.cpp the 7th line is #include "WProgram.h". Change this to #include "Arduino.h", as this is the new header file used by the 1.XX versions of the Arduino system.

The error means the compiler can't find the definition of the class Messenger. The fix is to make sure that Messenger library is in the right place (as described above) and to put #include "Messenger.h" near the top of you sketch.

I try sketch examples for Messenger and still not compiles.  Now it gives several errors which starts "WProgram.h: No such file or directory".

Change "WProgram.h" to "Arduino.h" in the examples.

Now it gives 'Messenger' has not been declared compile error.

int value = int(red(c1[0])); gives you 99 not 99.0
You could read a byte (that's what Serial.read returns; not an int), and make some decision based on that character, then read again.
Or, you could read all the available data till '\n' new line character comes. What println(value); line does it sends 99+'\n
Code:
// Buffer to store incoming commands from serial port
String inData;

void setup() {
    Serial.begin(9600);
    Serial.println("Waiting for Processing color...\n");
}

void loop() {
    while (Serial.available() > 0)
    {
        char recieved = Serial.read();
        inData += recieved;

        // Process message when new line character is recieved
        if (recieved == '\n')
        {
            Serial.print("Arduino Received: ");
            Serial.print(inData);

            inData = ""; // Clear recieved buffer
        }
    }
}

In case this is not working change your processing code line:
myPort.write(value);
to
myPort.println(value);
or
myPort.write(value);
myPort.write('\n');

The communication between the arduino and processing is 9600bit/s I suppose.
This will mean, that one bit needs 0.104ms to be sent. But with your Arduino code and the while-function you don't wait till the 8 bits of your byte are arrived and the arduino-loop is to fast for the serial connection. Wit other words: you cant use our wihile() function, use an if statement:
int x;
if (Serial.available()>0) {
  x = Serial.read();
}

and for debugging you can include once more the Serial.print()-function
(Sorry for my terrible English...)


text:
Power servo with external power using a hacked USB cable
I want to use a servo motor and control it by an Arduino Duemilanove (or a Leonardo). It seems to work fine when I connect it directly to Arduino's VCC, GND and an PWM pin. But I am a bit worried if this is a good idea. The multimeter shows that it draws up to 0.6A which is about 10 times of what I'd expect that the Arduino can provide. Is this correct or does this apply only to the digital out pins? Would it be better to power the servo using an external power supply?
I thought it would be a nice and easy solution to power the Arduino using a USB power supply and to cut the USB cable and connect the servo directly to the +5V of the USB. But is there even a difference in powering the Arduino via USB and connecting the servo to the VCC of the Arduino? Is it a problem to connect GND and UGND?
(After first tests, I think that the Arduino led is pulsating less using the hacked USB cable, but still a pulsating LED shows that the servo is drawing a lot of power from the board.)
Bonus question: does your answer apply to all Arduino models? (I am interested especially in Leonardo and Duemilanove.)
Similar discussion:
http://forum.arduino.cc/index.php/topic,22132.0.html

What kind of servo are you using? PWM pin isn't providing any current. USB only rated at 500mA. So your best bet is to use an external power supply. You will indeed need to connect the ground of the arduino and the ground of the external power supply together. Limiting factor is USB not the arduino board (which by itself only uses 20mA).

USB 2.0 is normally only rated at 0.5A. So 0.6A is already 'border line'. How did you measure the servo current was 0.6A? Was the servo moving, or were you holding it still ('stalled')? If it was moving, expect the servo to have a much bigger 'stall' current; in this case USB will not be enough. If the servo stalls, which is easy to do by accident, the USB power supply may switch off or even fail.


text:
Arduino mini requires uploading on every power up?
My Arduino mini is experiencing some really strange problem.
I'm using the BlinkWithoutDelay example sketch for testing:
const int ledPin =  13;
int ledState = LOW;             // ledState used to set the LED
long previousMillis = 0;        // will store last time LED was updated
long interval = 1000;           // interval at which to blink (milliseconds)

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

void loop()
{
    unsigned long currentMillis = millis();

    if(currentMillis - previousMillis > interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW)
        ledState = HIGH;
    else
        ledState = LOW;

   // set the LED with the ledState of the variable:
   digitalWrite(ledPin, ledState);
  }
}

The program basically turns pin 13 on and off every 1000ms.
When I uploaded this sketch into the mini (via Arduino Uno board, sans Atmega chip), the scope reading of pin 13 shows nice square waves (1s pulsewidth, 2s period), as expected.
I then unplug the USB cable powering the mini through the Uno board, wait for a few seconds for the scope traces to settle (I only have an old analog one at hand), and then plug it back in to turn on the board. However, the pin output is different - I now get a train of three pulses (60ms wide, 60ms between pulses) at sporadic intervals.
Uploading the sketch then yields the desired square waves again.
What is going on here? I'm fairly sure the mini has nonvolatile memory and it's intact (otherwise the bootloader through which I upload the sketch would not work).

What does the led do? The led will fade during the bootloader phase. Try disconnecting the scope while power cycling.

There is no LED actually connected. The sketch simply alternates the pin between HIGH and LOW for 1s, and I'm just monitoring the output on the scope.
Are you suggesting that having a high impedance load connected (the scope) to the output during power cycling someone interferes with the Arduino correctly executing instructions?

It shouldn't matter. But then again, your program shouldn't misbehave, like it does, either. Try using a different pin. Also, what happens if you press the reset button (instead of, or after power cycling)?

I've used multiple pins, the behavior persists.
When I press the reset button, there's no output for a little bit, then the same triple-pulses start again.
I'm going to do the same thing on my Arduino Uno, to check if my mini is somehow screwed up.

There was a defective bootloader that shipped on some Arduino devices which caused the symptom you describe. See:
http://forum.arduino.cc/index.php?topic=51172.0
http://forum.arduino.cc/index.php?topic=74090.0
If that's the case, your options are to re-write the bootloader yourself (if you have the capability) or return to the manufacturer.

Thanks a lot for the links. That would make sense, I'll probably flash the bootloader then.


text:
I want to be able to upload a batch of tweets to a twitter bot to be qued' for tweeting
I have built a twitter bot with my Arduino and an Ethernet shield
right now, the way to make it tweet something is to manually add a phase into the code and upload it to the board for each new tweet,
I would like to create a simple way of scrolling through a queue of phrases and tweeting each consecutive one after a given amount of time (several hours).
the issue I'm seeing is that, the code needs to rerun for each tweet, and I can't figure out what needs to be in what loop. Also the entire thing needs to delay for 3.6e^6(1 hour) milliseconds (the code takes delays in milliseconds) so that I don't spam the feed,
the twitter for this project is @ether_bot.
Code is below:
#include <SPI.h>
#include <Ethernet.h>
#include <Twitter.h>

/*
void speech()
{
  //this is where i would put the que of tweets
}
*/

// the next three lines connect the ethernet shield to the local network and establish a link with the twitter account
byte ip[] = { 192,168,1,104 };
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xEU }; //address for the shield
Twitter twitter("2790106893-5ljE7WPyyGe16SqTMEm8CN5gpwDquhGnyjH2TCM");
char msg[] = "hello again, im getting some major work done soon!"; // message to tweet

void setup()
{
  delay(30000);
  Ethernet.begin(mac, ip);  // makes the connection
  Serial.begin(9600); //opens a serial interface similar to the prnt window in bluejay
}

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

  if (twitter.post(msg))
  {
    int status = twitter.wait();

    if (status == 200)
    {
      Serial.println("OK.");
    }
    else
    {
      Serial.print("failed : code ");  //stuff happens here idk
      Serial.println(status);
    }
  }
  else
  {
    Serial.println("connection failed.");
  }

  do {} while(1);
}

You mention a "queue" of messages; a queue has to be fed somehow: how would it be fed in your situation? If it is static, then it is not really a queue and the problem is rather simple to solve (see @geometrikal answer below).

i would like the next tweet in the queue to be tweeted after a certain amount of time, (say every few hours)

You did not answer my question: is the lsit of tweets in the queue "static", ie known and fixed at compile-time, or is it dynamic, ie it can change at runtime; in the latter cas, how is the queue fed with new tweets?

static. the tweets would be typed in before the compile. i would generate all of them myself and they would all be in the code from the beginning. after the tweets in the queue are all tweeted, then i would type new ones into the code and re-upload

Ok. Then @geometrikal answer fits your question.

First create an array of all the messages:
#define NUM_MESSAGES 3
const char *msg[NUM_MESSAGES] = {
    "This is the first message",
    "This is the second",
    "Third time lucky" };
int msg_num = 0;

Then in the loop, switch between messages and add a delay
void loop()
{
  Serial.println("connecting ...");
  if (twitter.post(*msg[msg_num]))
  {
    int status = twitter.wait();
    if (status == 200)
    {
      Serial.println("OK.");
    }
    else
    {
      Serial.print("failed : code ");  //stuff happens here idk
      Serial.println(status);
    }
  }
  else
  {
    Serial.println("connection failed.");
  }

  //Next message
  msg_num++;
  if (msg_num >= NUM_MESSAGES) msg_num = 0;
  delay(1000*60*60);
}

so i put some stuff together and got this error at this line... im a totatl noob at coding so i dont really know how to make it work,,,,
if (twitter.post(*msg[msg_num]))
sketch_oct06a.ino: In function 'void loop()':
sketch_oct06a:18: error: invalid conversion from 'const char' to 'const char*'
sketch_oct06a:18: error: initializing argument 1 of 'bool Twitter::post(const char*)'

Try removing the * in front of *msg[msg_num]. This now compiles for me but I don't have a WiFi/Ethernet shield to test it.


text:
Can I have backup power for an Arduino device?
I have an arduino project that will work while plugged into a generic outlet. But I want to connect a battery in case the power goes out. I know there are various power sources (coin cell, polymer lithium, 9V, etc.). But if I code my project to use the backup power if the main power goes down, would that mean the backup always has to be running? How would I go about this?
Thanks for the help! Every time you help me you save a kitten!!

You could set up a relay to work in reverse with the mains power.
Have your backup battery connected to the gate contacts of the relay, and then use the mains power running your project to open the relay and keep it open as long as there is power. If the mains turns off, then the relay closes and the battery is connected.
You might want to put something in line with the power to the Arduino to make sure you don't get any spikes when things switch.
I hope this helps as I love kittens

Thanks! I have to look into the code, but this sounds like a great possibility!

I doubt if a relay would work. It would cause a drop-out in power as it switched from mains to battery.

This needs a big capacitor, to survive the time it takes for the relay to throw.

@Jasmine what farad value would you recommend OP?

The cap would slowly eat the battery charge :/

@user400344 - not enough information. You need to know the time to flip the relay - some are really fast, some are slower. You also need to know the maximum draw of any connected devices. Then you pick a cap twice as big as you need to deliver that current draw over the time it takes to throw the switch.

I have been looking into this myself.  After getting some advice online I have come up with this circuit :

http://everycircuit.com/circuit/5059191601364992
The top left power source is the mains supply and the bottom  left is the battery.
A voltage divider is connected to both that then feeds into an OPAMP comparator.  For illustrative purposes there is a switch at the top left you can toggle to see the circuit in action.
When the mains power gets cut off the op amp comparator sends a logic level signal through the diode and into the mosfet which enables the battery circuit.   the capacitor is there to keep power while the comparator makes the switch.
The link on every circuit is interactive, so feel free to have a play about with it.  The LED represents your Arduino.  The OpAmp is powered by the Positive and negative rails of thi diagram (impossible to draw on EveryCircuit)
Be sure to attach a voltage regulator to this circuit (at the input of the Arduino) so that the voltage doesn't change to your Arduino.
Here's where I researched about comparator OPAMPS ... Setting up a comparator OpAmp circuit
The LM358 is a good very cheap OPAMP for this circuit.   All parts well sourced will cost you about £1 (or less).
Or if your battery is rechargeable you can try this circuit :

http://everycircuit.com/circuit/5232232327282688
Again this is just for illustrative purposes.   You will need a 5V step-up converter to get 5v from a 3.7v battery.  Also the battery I am using has a builtin protection circuit, if yours doesn't it's important you include it in your schematic.
Here's a video of it working for me with a 3.7V Li-Polymer Battery:
https://www.youtube.com/watch?v=Sv2rjVqQg3U

Three problems: First, what powers the op-amp?  Not that it can't be resolved, but you haven't specified.  Next, you appear to back-drive the mains supply when it is unpowered - that may or may not work, for example, it may load the battery supply.  Finally, you appear to be supplying either 5v or 9v, but the typical arduino does not have any power input which can accept both of those values and function as intended.

It's highly simplified due to a lack of components on Every Circuit.   I would probably attach a voltage regulator in there.   The OpAmp gets powered by the battery, the mains or the capacitor depending on the situation (ie its power is from the negative and positive rails on the diagram).
I'm new to electronics, but I based this circuit off examples and advise from around the internet.

The point is that this can't be used without changes.

Feel free to draw up a circuit diagram for my benefit and for those reading this post.

I suggest this "Battery boost" circuit from AdaFruit. It's designed to do exactly what you describe. An Arduino needs a smooth, steady 5 V supply with no "blips". The AdaFruit unit does just that, and charges the battery while on Mains supply.

You could solve this very simply with some diodes or get creative with a bridge rectifier.  Connect both positive sources to the ac input one on each leg.  then the positive side of the bridge rectifier would be your positive source.  the grounds need to be all tied together

You can use https://www.regaldreamtech.com/micro-ups/ for the backup 5V power supply to Arduino in absence of main power. It has 5000mAh battery and 5V 2A output. It will handle the switching on its on between main and battery power.
Disclosure: We manufacture this product.


text:
Cannot compile C++11 code via Makefile
I am building my Arduino project with a makefile:
BOARD_TAG = uno
ARDUINO_PORT = /dev/ttyACM0
USER_LIB_PATH = /home/prakhar/dev/alfred/arduino/libraries
CPPFLAGS=-x c++ -std=c++11 -Wall -DUNIX_ENVIRONMENT -DHAVE_NAMESPACES -DHAVE_STD
include /usr/share/arduino/Arduino.mk

I keep getting this error:
cc1plus: error: unrecognized command line option "-std=c++11"

I googled and this says that I need to update g++/gcc. I already have the newset versions:
prakhar@sim74stic ~ $ avr-g++ --version
avr-g++ (GCC) 4.9.1
Copyright (C) 2014 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

prakhar@sim74stic ~ $ avr-gcc --version
avr-gcc (GCC) 4.9.1
Copyright (C) 2014 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

prakhar@sim74stic ~ $ g++ --version
g++ (GCC) 4.9.1 20140903 (prerelease)
Copyright (C) 2014 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

I installed arduino from the AUR (packages aur/arduino 1:1.0.6-1 and aur/arduino-mk 1.3.4-2).
Can anybody point out what I'm doing wrong?

Check out the first few comments here: https://aur.archlinux.org/packages/arduino/  It may help.

Thanks for pointing me in the right direction. I C++11 to work.

As I turns out, the avr-gcc (GCC) 4.9.1 goodies weren't being used at all! The arduino package was using a decrepit version of gcc,
prakhar@sim74stic ~ $ /usr/share/arduino/hardware/tools/avr/bin/avr-g++ --version
avr-g++ (GCC) 4.3.2
Copyright (C) 2008 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

prakhar@sim74stic ~ $ /usr/share/arduino/hardware/tools/avr/bin/avr-gcc --version
avr-gcc (GCC) 4.3.2
Copyright (C) 2008 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

All I had to do was specify:
AVR_TOOLS_DIR = /usr

to exexute with -std=c++11 flag (I also had to add an -fpermissive flag to compile C with g++).


text:
Setting data pin with NanodeUNIO
I'm using a sketch that helps to reset Da Vinci XYZPrinter cartridge EEPROMs, and it's based on the NanodeUNIO library. It uses digital pin 7 for data. I want to use my TFT Touch Shield to set the extruder temperature, but the shield also makes use for digital pin 7. Being that the sheild is wired to use pin 7, it can't be changed. But any pin that can be used as a digital pin should be useable with NanodeUNIO (at least, that is my assumption), but I can't find where in NanodeUNIO it sets the data pin. Where is that pin set, and how can it be changed?

Did you try looking for a call to pinMode()?

It has a single call for pin 13, which is the LED to tell you when it's done. The pin is used both to red the contents of the EEPROM as well as to set it. Full code is here: https://github.com/voltivo/davinci_filament_reset_arduino/blob/master/xyz_dv_eprom.ino

xyz_dv_eprom.ino uses low-level access rather than Arduino calls to manipulate PD7, most likely for speed reasons. Lines 96 through 104 (specifically 96, 97, 100, and 104) need to be modified in order to change both the port and the bit used.
ATmegaXX8 pin mapping
ATmegaXXX0 pin mapping
ATmegaXXU4 pin mapping


text:
Counting pulses with interrupt
I have been trying to count pulses from a 12,500 Hz square wave to trigger an output. Here's the code I have so far. When the Arduino is reset it prints 315 to the serial over a 25 ms sample. 315 x 40 = 12600. Which seems to me it's working perfectly.
My only problem is it only returns this number once upon reset of the board. Now if I move that same code down into void loop, it counts consecutively giving me inconstant returns.
I am not understanding what I need to put in the loop section so I can repeatedly and accurately count how many toggles of the input pin I am getting over a period of time so I can do something to the output based off the presence of the 12,500 Hz signal or not.
volatile int IRQcount;
int pin = 2;
int pin_irq = 0; //IRQ that matches to pin 2

void setup() {
   // Put your setup code here, to run once:
  Serial.begin (9600);
  attachInterrupt(pin_irq, IRQcounter, RISING);
  delay(25);
  detachInterrupt(pin);
  Serial.print(F("Counted = "));
  Serial.println(IRQcount);
}

void IRQcounter() {
  IRQcount++;
}

void loop() {
  // Put your main code here, to run repeatedly:
}

Using the above code, every time I press the reset button I get one line in the serial window.
Counted = 441
Counted = 442
Counted = 441
Counted = 441
Counted = 441

Now I want to get the same result, but repeating over and over. That way if the signal drops out I can trigger an output to turn off (LOW). When the signal is present the output will go high.
My attempt was to move the attach interrupt down into void loop, so it would repeat. Here's what it looks like.
volatile int IRQcount;
int pin = 2;
int pin_irq = 0; //IRQ that matches to pin 2

void setup() {
  // Put your setup code here, to run once:
  Serial.begin (9600);
}

void IRQcounter() {
   IRQcount++;
}

void loop() {
  // Put your main code here, to run repeatedly:

  attachInterrupt(pin_irq, IRQcounter, RISING);
  delay(25);
  detachInterrupt(pin);
  Serial.print(F("Counted = "));
  Serial.println(IRQcount);
}

The return I get is self-updating, but the "count" instead of starting from 0 each time starts from the previous count. So it gets larger and larger. I am looking to return a constant value that represents my 12500 Hz signal so that, and only that, will trigger my output.
Counted = 442
Counted = 886
Counted = 1330
Counted = 177
Counted = 2221
Counted = 2667
Counted = 3112
Counted = 3557
Counted = 4002
Counted = 4448
Counted = 4893
Counted = 5338
Counted = 5784
Counted = 6229
Counted = 6674
Counted = 7120
Counted = 7565
Counted = 8010
Counted = 8456
Counted = 8901
Counted = 9347
Counted = 9792
Counted = 10237
Counted = 10683
Counted = 11130
Counted = 11576
Counted = 12022
Counted = 12469
Counted = 12915
Counted = 13361
Counted = 13808
Counted = 14254
Counted = 14700
Counted = 15147
Counted = 15593
Counted = 16040
Counted = 16486
Counted = 16932
Counted = 17378
Counted = 17825
Counted = 18271
Counted = 18717
Counted = 19164
Counted = 19610
Counted = 20056
Counted = 20503
Counted = 20949
Counted = 21395
Counted = 21842
Counted = 22288
Counted = 22735
Counted = 23169
Counted = 23616
Counted = 24062
Counted = 24508
Counted = 24955
Counted = 25401
Counted = 25730
Counted = 25756
Counted = 26200
Counted = 26646
Counted = 27093
Counted = 27539
Counted = 27985
Counted = 28432
Counted = 28878
Counted = 29324
Counted = 29770
Counted = 30217
Counted = 30663
Counted = 31110
Counted = 31556
Counted = 32002
Counted = 32449
Counted = -32641
Counted = -32195
Counted = -31748
Counted = -31302
Counted = -30855
Counted = -30408
Counted = -29962
Counted = -29515
Counted = -29069
Counted = -28622

"Now if i move that same code down into void loop it counts consecutively giving me inconstant returns." means what exactly?

I edited my question to try and better explain myself

You need to reset IRQCount back to 0 before attaching the interrupt again. Otherwise it will just continue counting from where it stopped last time.
I would actually keep the interrupt attached and just reset the variable just before the delay. That way the overhead of attach/detachinterrupt doesn't get added to the 25ms delay.
volatile int IRQcount;
int pin = 2;
int pin_irq = 0; //IRQ that matches to pin 2

void setup() {
  // put your setup code here, to run once:
  Serial.begin (9600);
  attachInterrupt(pin_irq, IRQcounter, RISING);
}

void IRQcounter() {
  IRQcount++;
}

void loop() {
  // put your main code here, to run repeatedly:
  IRQcount = 0;
  delay(25);
  int result = IRQcount;
  Serial.print(F("Counted = "));
  Serial.println(result);
}

Since an int is 2 bytes an interrupt might occur in the middle of setting/reading those two bytes. This might result in an occasional wrong value. To prevent that you should disable interrupt while setting/reading the value
volatile int IRQcount;
int pin = 2;
int pin_irq = 0; //IRQ that matches to pin 2

void setup() {
  // put your setup code here, to run once:
  Serial.begin (9600);
  attachInterrupt(pin_irq, IRQcounter, RISING);
}

void IRQcounter() {
  IRQcount++;
}

void loop() {
  // put your main code here, to run repeatedly:

  cli();//disable interrupts
  IRQcount = 0;
  sei();//enable interrupts

  delay(25);

  cli();//disable interrupts
  int result = IRQcount;
  sei();//enable interrupts

  Serial.print(F("Counted = "));
  Serial.println(result);
}

Thanks Gerben! Using that code i get the occasional junk return. What would be the easiest way to denounce this? Make an out take lets say 3 readings before making a decision on what to do. Or averaging pulses over a span instead of a raw count? Heres an example of the return, i get the anomaly every few seconds.
Counted = 439,
Counted = 438,
Counted = 430,
Counted = 48,
Counted = 318,
Counted = 438,

I lengthened the delay to give a larger sample size. This gives me a workable return from my noisy input source. This seems to work perfect! Thank you!

I assume you used the code with the clis and seis in it. Rather strange having two consecutive wrong values.

Gerben, Yes i used the code with the cli and sei in it.   Do you mean its strange getting the two wrong returns in a row? It seems the returns are correct, it is the incoming signal that is not stable giving junk returns.  If i sample over lets say 100ms it gives plenty of pulses per sample to safely activate or kill the circuit. I really appreciate your help!

But the 48 and 318 you got are both lower that the average of about 435. I don't know the connected circuit, so it could just as well be the circuit, instead of the arduino code. Anyways, as long as you are happy with the end result... Glad to have helped.

I believe the issue is software related to the host computer itself. I have tried several charge pump circuits, and ended using arduino because of the the unsteady signal. I have ran many experiments using many forms of code on the arduino as well as other types of hardware approaches to this. The problem is the instability of the incoming signal, not the arduinos interpretation of it. Every piece of hardware i have used to monitor the signal has showed great variance in it. The arduino {with your help} allowed me to debounce  the charge pump circuit which was giving me fits!

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


text:
Arduino Mega 2560 as ISP for ATTINY2313 / ATMEGA328P
I have posted this on the Arduino forum also, but I give it more chance if posted here also.
I've been trying to use my Arduino Mega as an ISP for programming two different ATMEGA328P's and a ATINY2313, but I just don't succeed.
I am running the Arduino IDE (version 1.5.8 ) on windows 7. I've been using these http://www.instructables.com/id/How-to-use-Arduino-Mega-2560-as-Arduino-isp/ http://www.instructables.com/id/Arduino-ATtiny2313-Programming-Shield/ instructables for help. The circuit are built on a breadboard. On my Arduino Mega is use the pins reset: 53, MOSI: 51, MISO: 50, SCK: 52.
First I upload the arduino as ISP sketch on my Mega. There are LEDs on the programming, error and heartbeat outputs, the heardbeat is pounding. I then select the according board from the boards list (the ATINY2313 1MHz from the instructable for the ATTINY and either the Arduino UNO or the Arduino Duelimanove for the ATMEGA328P) and after that the programmer árduino as ISP'. When uploading the Blink sketch I get errors like:
avrdude: Yikes! Invalid device signature
avrdude: stk500_getsync(): not in sync: resp=0x00
avrdude: stk500_disable(): protocol error, expect=0x14, resp=0x51
I have tried things like capacitors/resistors between the reset and the ground or between the reset and the +5V, but nothing different. I have searched for help on the internet and alot of people have problems with it, but no clear or working answers. I have been looking at the MegaISP guide form Arduino, but this is not very clear to me.
I have no idea where to start anymore. Does anybody have an idea what I can try or where to start searching for answers?
I appriciate all the help I can get!

Try a bigger capacitor. Also, putting it between reset and GND sound more logical to me. Looking at the schematic you can also put a jumper between 5V and RST. similar error

This worked for me dude :)
See this:
http://www.instructables.com/id/Bootloading-ATmega328-with-Arduino-Mega2560/?ALLSTEPS

You might want to cite the most interesting parts of your source/link.
In case the link might go dead.
Also, to avoid getting 10's of answers with only links. Which isn't manageable and you'll have to visit each link to check what the good/best answer is.
Read this for more information on single-line or link-only answers: http://meta.stackexchange.com/questions/156941/one-line-answers