text:
Should I use an Arduino or not?
I am building an electronic gadget eventually to sell.
I think the Atmega IC is used in the arduino and could this be programmed as easily as the arduino?
I'm wondering if I can use the chip and buy just what I need for my circuit, which would be cheaper as there would be no licensing obligations to the Arduino company
Cheers
Eamonn

What "licensing obligations" are you worrying about? The Arduino is open source hardware, which has been cloned by many other companies. Also, you will probably find that a cheap clone costs less than you would pay for the parts.

@DaveP. I had a look on the Arduino site and they mentioned a fee for producing a product for sale. Maybe its just if you want to have the product promoted on their site and you would have the arduino logo on the product. I will do a bit more rescearch so thanks for the info.

Short answer: Yes. After all, Arduinos are made by starting with an ATMega (or other AVR) IC.
Longer answer: People - including myself - routinely build with a bare ATMega328p (or other MCU), programming them off-board on another system, or providing connections to allow programming them in place. Beyond that you only need the soldering skills for the chip you choose (if you're building the boards yourself). I use DIP ICs and off the shelf through-hole PCBs and hand-build one or a couple at a time. Quad Flat-Package or Surface-Mount chips are another step up in complexity for the hand-builder.

I'd like to second the other posts - if you are familiar with Arduino, going to a stand-alone chip is very easy.
You miss out on the following things: programming via USB, 7-12volts through the power jack, and/or power through USB, reset button, led on pin 13, and the clock. Depending on where you get your Atmel chip, you may also need to set the fuses.
The code is exactly the same, even if you go down to a smaller chip (or larger - whatever suits your project best!).
Programming: I use a FreeTronics ICSP (ISP) to program the chips, and have the 6-pin ICSP header on all my projects for easy reprogramming. This particular programmer has a "slow clock" jumper, because when you get the chip from the Atmel factory, their internal clock runs at 1mhz, too slow to program with the Arduino IDE default settings. You can leave it at 1mhz, if your project doesn't need any more, or change the fuses. You will need an ICSP to set the fuses (see further down). By using an ISP rather than usb, you also save a little memory - you don't need a bootloader (which is pre-programmed on Arduinos, but not when you buy the chips from the factory).
You will need to sort out your own power - this depends on what you need, and what you have. You can use a 5-volt AC-DC power supply ("Wall wart") and plug it into mains. Or, you can power it off USB - if you only use USB for power, you can solder the socket directly on your board. You can use a regulator (which is what the Arduino uses for the 7-12v power socket), or, if running it off a 12v power supply, it might be easier/cheaper to buy a car phone charger from the dollar store, and a lot of the work will be done for you. Also, the power supply doesn't have to be 5v - depending on your application, you might run it from 5.5v to as little as 1.8v, depending on your clock speed. Find the data sheet for the chip you use.
A reset button is very easy to add, if you need it - all it takes is a resistor and a pushbutton. Weather you need it or not, depends on your project.
The same applies to the led on pin 13 - it depends on your project.
Finally, the clock. The Arduino has a 16mhz quartz clock. You can do the same, it only takes 3 components (you will have to set the fuses, see further down). You can use a clock up to 20mhz, giving you a 25% speed boost if you need it (you may need to change some settings, because timing functions like delay depend on the clock speed - your delays will be 25% shorter). Or, you can use the internal 8mhz clock (either at full speed, or as from factory, at 1/8 speed, so you get 1mhz). At 4mhz or less, you can run the Atmega at 1.8 volt, or 0.7 volt for the "pico power" chips.
As I have mentioned, you may need to set the fuses to the correct value. The best idea is to go to http://www.engbedded.com/fusecalc/ to work out what fuse settings you want. Specific things to look for: the clock source (internal or external? what speed?), divide clock by 8 internally, and brown-out detection (Arduino chips turn themselves off when the power goes below 4.3v). Warning: setting wrong fuses may set your chip so it is very difficult to fix. You can set the fuses using an ISP; if the clock speed is very slow (I think < 4mhz? which it is when it comes from the factory), then you will have to "slow program" - some ISPs have a "slow program" jumper, but you can use an option to avrdude to do the same - I think it's -B e.g. -B10).

^ for a comprehensive answer.

That's what I do all the time. You might want to buy an ISP programmer to program the chips (e.g. USBASP or usbtinyisp). If you just want to try things out first, you can use your arduino board as an programmer by uploading the ArduinoISP sketch.
The Arduino Uno uses an ATMega328, but you could use other AVR chips too. E.g. the ATMega8, which is slightly cheaper. Or an ATTiny85, which only has a few pins, and is therefor a lot smaller (also cheaper). So you can choose a chip that best fits your needs.

Arduino of course started as a prototyping platform. Build this first, get it working, then move to a circuit board of your own design with the same chip and go from there. However, as the cost of all the components and really the boards themselves drops, I frequently find my self thinking, why not just use the board. Obviously if you are going to market something, having a full arduino in there might be a bit much, but if its just for your own application, I don't see any reason why you wouldn't just buy boards and use them as necessary.

Thanks for all the replys. I have a lot to learn as I only heard of arduino a month ago.
Didn't have a reason before.
My arduino hasn't arrived yet so I made my basic circuit with components on a breadboard.
I think I will need the arduino as I need some monitoring in the circuit.
Thanks again much appreciated.
Eamonn

Since you are already using Arduino, I think you not should use atmega, but must! To prevent future headaches, since you look new to electronics, I HIGHLY recommend to check for app notes by Atmel. Just type it "Atmel app notes" at google and you will find a lot of useful tips. Some of them are start to routing by crystal resonator, them GND and Vcc. Use, if possible, on each IC a 100nF ceramic SMT capacitor nearest as possible and another one of 10uF (can be electrolytic) on most robust ones (like microcontroler). Always route opposite signals (like Vcc and GND) tied together with the same size to low its impedance... If you are doing with high inductance loads you should use another sorce (and maybe also a diode as rectifier or an optocoupler).
There's a lot of good practices and if you want to sell your work, you really have to study them.
Good luck! Also look for the electronics SE


text:
Arduino Raspberry Pi USB Communication
I am trying to connect an Arduino and Raspberry Pi over USB.  I would like to send serial commands, just like the serial monitor in the Arduino IDE.  I know how to do this on the Arduino end but I'm not sure how to send/receive serial communication on the Pi end.  Ideally the solution would utilize Python.

Welcome to Arduino SE! Sorry, this is not on topic because it's about the Pi. If you Google your question with the word "python," you will get several articles to show you where to go.

You will need PySerial to accomplish this. A tutorial on interfacing Arduino and the RPi using a usb can be found here

linking to offsite resources as the meat of your answer is not useful in the longterm, please update your answer to include more information.

You would be better to ask this on http://raspberrypi.stackexchange.com
You can use program minicom on the Pi; this is a terminal program like the serial monitor in the Arduino IDE, and of course you can use Arduino IDE on the Pi.
If you look at the Pi site you will see lots of Python serial communication programs.

There's nothing particularly "pi" about this - it's rather a generic linux/unix question.

Why do you want to use the USB port on the Pi? Isn't it easier to connect the Arduino directly to the UART pins (Pins 8 and 10) on the PI and then read out the UART in your python programme?

this would be more appropriate as a comment. You are not answering the question. There could be lots of reasons to use a direct usb connection or the OP might not know that they can do what you propose, either way though the question they asked is about connecting via usb.

Do realize that it's the same serial software API either way?  While it's true that the USB serial imposes an additional latency, it's wise to design communication schemes that can tolerate that, because more often than not today one will be involved.  Regardless, you haven't answered how to implement either the original question or your own proposal - which is ironic as an answer to either would be an answer to both.

Why are you guys getting so upset with my comment? All I tried was to help. What I have written may technically, according to your orthodoxy, not be an "answer", i.e. providing a complete and final solution for the USB connection. However, I suggest an alternative solution to the original problem, i.e. sending serial commands.

The reason I want to use USB rather than the GPIO on the Raspberry Pi is that 1) The Arduino will be powered over USB, so less wires to run (the Arduino and Pi will not be immediately next to each other) 2) It is a neater solution 3) Latency is not an issue, and 4) The Pi is a 3.3V device while Arduino is 5V.  For now, signals only go Pi>Arduino, which should work, but I want the option to go Arduino>Pi without level shifting.

source: Stack Exchange

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

sort: votes


text:
How to save the SHA256 with HMAC into a variable instead of serial print?
#include "sha256.h"

uint8_t hmacKey1[]={
0x65,0x63,0x73,0x74,0x61,0x63,0x79
};

void printHash(uint8_t* hash) {
int i;
 for (i=0; i<32; i++) {
   Serial.print("0123456789abcdef"[hash[i]>>4]);
   Serial.print("0123456789abcdef"[hash[i]&0xf]);
  }
 Serial.println();
}

void setup() {
   uint8_t* hash;
   uint32_t a;

 Serial.begin(9600);

 // HMAC tests
  Serial.println("Test: RFC4231 4.2");

Serial.print("Result:");
Sha256.initHmac(hmacKey1,20);
Sha256.print("Hi There");
 //My TRIAL ATTEMPT
 int i;
 for (i=0; i<32; i++) {
 hash[i] =Sha256.resultHmac();
 Serial.println(hash[i]);
 }
}

How do I save the hashed result into a variable? I disregarded the Printhash function above and tried it with my own code but it displays
 sketch_feb14a:32: error: invalid conversion from 'uint8_t*' to 'unsigned char'

I don't understand the printhash function above and found little to no documentation on the web. I'm thinking of using AES library but I guess it's more complicated over here. The above code is based on Spaniako's CryptoSuite here
Heading

The  printHash function takes the upper and lower 4 bits of each byte, and uses them as an index to the string of hex digits.

My solution was making a new function that returns a String with the hash
String GetHash256(uint8_t* hash) {
    char tmp[16];
    String sHash256 = "";

    int i;
    for (i=0; i<32; i++) {
        sprintf(tmp, "%.2X",hash[i]);
        sHash256.concat(tmp);
    }

    return sHash256 ;
}

The hash is a series of binary digits. They are usually represented in hexadecimal form for readibility. You are just printing out the raw bytes, which will give a series of random ASCII characters. Some of these may be control characters which interfere with serial port communication.

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


text:
New to Arduino: Should I learn C, C++ or both (C & C++)?
From what i've researched here is my thoughts on both

C++
I heard that you can create libraries using C++ in arduino. And you can use the Arduino IDE to do that stuff.  Here is the proof

http://arduino.cc/en/Hacking/LibraryTutorial
Notice that it uses the C++ syntax.
I also see arduino projects on github written on C++
https://github.com/search?l=C%2B%2B&q=Arduino&type=Repositories&utf8=%E2%9C%93

C

I heard that you can use AVR GCC and code it without the arduino ide. And I heard it's much faster than the arduino language because it's more closer to the metal. But I think it's harder to set up because you need a programmer into the Atmel chip, which is much more costlier compared to directly plugging in the arduino using the USB to printer cable. And you also need to download a bunch of stuff to get coding in pure avr gcc (win-Avr GCC, atmel studio etc.).
Which one should i learn C or C++? I prefer the easy to debug route. Or is it beneficial if i learn both?

The basic syntax of C and C++ is very similar, to the point that C code can typically be compiled directly as C++. You'll also find C standard functions (such as printf and malloc) can be used from C++ programs.
The major difference in the core language is that C++ has a lot of extra stuff such as classes and templates. Conventionally, C++ also has a huge standard library which doesn't work on C. However, that's not usually available (nor really appropriate) for Arduino programming, so you don't need to worry too much about it unless you migrate to e.g. desktop programming.
Basically, it's probably sensible to learn C first, because the same knowledge works in C++. You can then move on to the C++-specific stuff, such as classes.
As a side note, the Gnu Compiler Collection (GCC) actually covers both C and C++. It's what the Arduino IDE at Atmel Studio use under-the-hood for all their compilation. It's even possible to work directly with GCC but still upload programs to Arduino via USB.
It's also worth noting that programs compiled within the Arduino IDE aren't necessarily going to run any slower than programs compiled some other way (whether C or C++). The main difference is whether or not you use the Arduino functions. Since they are general purpose, they're not necessarily doing things the most optimal way. You could get more efficiency in theory by manipulating the microcontroller's special registers directly, which is you can do from within the Arduino IDE as well. It's usually very tricky for a beginner though, so it's probably not something you want to attempt until you're more comfortable with C/C++.

Granted, as you said it's mostly unrelated to embedded programming, but I'm not sure I'd use the word 'huge' to describe the C++ standard library.  Sure, it's a covers a lot more ground than the C standard library, but compared to virtually any other popular programming language, it's quite spartan.

Arduino supports c++, but does not support many of the standard libraries.
The vast bulk of the functions in the Arduino IDE are c functions.
You can do almost everything in c, except for a few advanced items.
Due to the limited c++ libraries it will be difficult to learn c++ on Arduino; indeed it is not the ideal platform to learn c, as most of the tutorials will not work (because there is no I/O on Arduino).

Several standard Arduino libs are C++, the first that comes to mind is Serial, but there are others!

@jfpoilpret I never said the libraries were not c++, but all the advertised functions are callable in c. This is a question by a beginner who is unlikely to be overriding the serial class (or any other).

For starting out? I would say neither. The arduino IDE is based on a programming language called processing. Which you can look at. Honestly, if you have done any programming in the past you will be fine for the basics. The advanced stuff might make you look at working with c++ files. But there is nothinging overly complex there. A lot of the add-on hardware that you can purchase comes with existing arduino libraries. Use these as a baseline.

The arduino text-editor uses C(++). "Processing" is a horrible abortion of a wrapper on Java (it's still java, just much worse). None of this is original, and there are no new languages involved.

@ConnorWolf Way too kind.
Arduino is based on Wiring, which is based on Processing, which is a kludge of Java, resembling C++ running on an embedded prototyping platform ill suited for learning programming by any Definition.  Many libraries half written and confusing, implementing only as much as the original author needed, not the entire spec (SPI being a great example).
Get a Pi for the same price, at least it is an end user computer for poor people.
Besides, if you have something that can run the Ardunino IDE why are you learning to program on an Arduino? You need to be proficient in C or C++ before you attempt anything for real on an Arduino. Blinking lights is fine, beyond that, good luck.
Learn C or C++ (preferred as it is newer) on what you have, then start using the Arduino. Eclipse or Microsoft Visual Studio Community are both free and support both languages. (Both also support Arduino development when the time comes, avoid the Arduino IDE it is terrible). There are enough samples for either to keep you busy for a long time. Embedded programming REQUIRES understanding of low level hardware and IS NOT suitable for learning.
Forget modern debugging. Paid engineers grumble when they have to do it and it cost a decent price for the enabling hardware. Stick to the old fashioned printf debugging style.

It's perhaps slightly confusing to say C++ is 'newer'. It was certainly invented more recently, but both languages are still being maintained/updated.


text:
Interfacing SD card with arduino without shield
I am trying to connect SD card with arduino without using a shield. To convert to 3.3v, I have used voltage divider circuit as described in these two sites:
http://garagelab.com/profiles/blogs/tutorial-how-to-use-sd-card-with-arduino
http://www.martin-gardner.co.uk/how-to-connect-your-old-sd-card-to-an-arduino/
When I uploaded the code i got the following error on serial monitor:
Initializing SD card...initialization done.
error opening test.txt
error opening test.txt

Can you show us your code and circuit diagram?

The code is exactly of Examples/SD/ReadWrite

Is the SD card properly formatted. FAT or FAT32?

Yes, it has been formatted to FAT32.

Does your code use CS pin 10 as shown in your wiring diagram, or use CS pin 4 as shown in the martin-gardner.co.uk site code? It's related to the initialization code if (!SD.begin(4)) {.

@MarkU We have changed the code 'if(!SD.begin(4))'  to   '(!SD.begin(10))'

I can't understand what exactly happened, but i first uploaded CardInfo file from Examples > SD > CardInfo and after that i uploaded ReadWrite and i got the correct output.


text:
Error code 10 for arduino device driver
How can I fix error code 10 while installing the device driver for Arduino in Windows 8.1?
The LED on the board is blinking after connecting it to the laptop, so I don't think so that the board is damaged. What is the cause of this issue?

"The board" is more than just the LED and the part that makes it blink.

First of all, test if you even need a new driver. On Windows, the Arduino drivers for my Uno and my Mega were installed automatically by Windows. I'd advise to restart your computer, using the actual restart button, not manually shutting off and turning on... this is very important with Windows 8.1 and its Hybrid Boot default!!! A normal reboot doesn't fully reload all of the drivers. Next, open the Arduino IDE, and then see if you can successfully upload the "blink" example sketch.
If that doesn't work, let's try something else.
First of all, open up Device Manager and find your device:

It should be under the Ports (COM & LPT) section. After that, right click and click on Properties.

Then, let's go to the Driver tab and click on Update Driver. Then, click on Search Online Automatically for this Driver.

First, try seeing if an automatic update finds any drivers capable. If not, I've found previously that there's sometimes a Reinstall or Fix button somewhere if the driver isn't working correctly.
In addition, you can also update it manually using Device Manager. Instead of clicking on Search Online Automatically for this Driver, click Browse My Computer Manually. For me, there was a Mega driver under the Let me pick from a list of compatible device drivers on my computer and there was a Mega driver for me (although I don't know if that's because I have it installed already).
You can also use that same menu to point it to the location of the installation of the Arduino IDE and it will search for any compatible drivers.
Rolling back the driver is another option if the Arduino IDE tried to install a faulty driver that somehow got corrupt over a working driver installed by the computer.
The last thing I would suggest trying as a last resort is using the Uninstall Driver button and then trying to reinstall the driver manually. I've never done this with an Arduino board, although there have been some times with other drivers that this has helped to remove the faulty driver.
If none of this works, it may be a faulty board.

I had the same issue. The drivers, which shipped with Arduino IDE didn't work for me.
Actually, the reason was that I was using Arduino UNO clone. And it required another driver.
This video helped me to find the answer: https://www.youtube.com/watch?v=r9MGJ16pRLc
In my case I had to install the CH340 chipset usb driver. The driver can be downloaded from this page: http://www.microcontrols.org/arduino-uno-clone-ch340-ch341-chipset-usb-drivers/
After I installed CH340 driver, the upload from Arduino IDE started working perfectly.

After wasting a huge amount of time trying get the Arduino IDE to upload the sketches to my new starter robot I came across the following document in the Arduino Website :"Guide to the Arduino Leonardo and Micro"... In this document they explain how the serial port communication work on the leonardo (which is the ME-Baseboard from MakeBlock)...They state that auto-reset is initiated when the computer opens the serial port at 1200 baud and then closes it... Whatever that means... I went into the makeblock driver setting (under windows 8.1 device manger) and change the baud rate to 1200... Surprise surprise... all  works fine now, I can compile and upload the sketches for the starter robot... What frustration !!!! And for the people at Makeblock... I have been trying to create a community userid and while the system say that it will send me an email, it never does !!!

I am sad to report that what actually happened it that changing the baud rate also led to a change in board type in the arduino IDE... So the sketch did compile and load but assuming that the board is a UNO.  End result, still facing same problem and robot behave a bit erratically probably because the upload was not performed for a leonardo board.  I have tried counless times with countless different procedures on an acer laptop with Windows 8.1, an acer laptop with Windows 7 and a surface pro with Windows 7.  Same problem everywhere.  If someone from Makeblock read this blog, I would appreciate if you could send me the validating email so I engage this troubleshooting process on their community discussion board.


text:
Arduino Based Home Automation System
I am working on my project of home automation system using Arduino GSM SIM900 & four channel relay module. I am facing a problem in my code. Can any one help me on this, SMS is receiving but its not switching the relays?
#include <SoftwareSerial.h>

// EN: String buffer for the GPRS shield message
String msg = String("");
// EN: Set to 1 when the next GPRS shield message will contains the SMS message
int SmsContentFlag = 0;
//control pins of relay.
int relay_a=4;
int relay_b=5;
int relay_c=6;
int relay_d=7;

// EN: Code PIN of the SIM card (if applied)
//String SIM_PIN_CODE = String( "XXXX" );

void setup()
{
  Serial.begin(19200);                 // the GPRS baud rate
  // Initialize  PINs
  pinMode( 4, OUTPUT );
  pinMode( 5, OUTPUT );
  pinMode( 6, OUTPUT );
  pinMode( 7, OUTPUT );
  digitalWrite( 4, LOW );
  digitalWrite( 5, LOW );
  digitalWrite( 6, LOW );
  digitalWrite( 7, LOW );
 Serial.println( "AT+CMGF=1" );
 delay(200);
}

void loop()
{
    char SerialInByte;
    if(Serial.available())
    {
        SerialInByte = (unsigned char)Serial.read();
       delay(5);

        // -------------------------------------------------------------------
        // EN: Program also listen to the GPRS shield message.
        // -------------------------------------------------------------------
       // EN: If the message ends with <CR> then process the message
        if( SerialInByte == 13 ){
          // EN: Store the char into the message buffer
          ProcessGprsMsg();
         }
         if( SerialInByte == 10 ){
            // EN: Skip Line feed
         }
         else {
           // EN: store the current character in the message string buffer
           msg += String(SerialInByte);
         }
     }
}
// EN: Make action based on the content of the SMS.
//     Notice than SMS content is the result of the processing of several GPRS shield messages.
void ProcessSms( String sms ){

  if( sms.indexOf("ona") >= 0 ){
    digitalWrite( relay_a, HIGH );
  }
   if( sms.indexOf("onb") >= 0 ){
    digitalWrite(  relay_b, HIGH );
  }
   if( sms.indexOf("onc") >= 0 ){
    digitalWrite(  relay_c, HIGH );
  }
  if( sms.indexOf("ond") >= 0 ){
    digitalWrite(  relay_d, HIGH );
  }
  if( sms.indexOf("offa") >= 0 ){
    digitalWrite(  relay_a, LOW );
  }
  if( sms.indexOf("offb") >= 0 ){
    digitalWrite(  relay_b, LOW );
  }
  if( sms.indexOf("offc") >= 0 ){
    digitalWrite(  relay_c, LOW );
  }
  if( sms.indexOf("offd") >= 0 ){
    digitalWrite(  relay_d, LOW );
  }
}
// EN: Request Text Mode for SMS messaging
void GprsTextModeSMS(){
  Serial.println( "AT+CMGF=1" );
}

void GprsReadSmsStore( String SmsStorePos ){
  Serial.print( "AT+CMGR=" );
  Serial.println( SmsStorePos );
}

// EN: Clear the GPRS shield message buffer
void ClearGprsMsg(){
  msg = "";
}

// EN: interpret the GPRS shield message and act appropiately
void ProcessGprsMsg() {
  if( msg.indexOf( "Call Ready" ) >= 0 ){
   //  Serial.println( "*** GPRS Shield registered on Mobile Network ***" );
     GprsTextModeSMS();
  }

  // EN: unsolicited message received when getting a SMS message
  if( msg.indexOf( "+CMTI" ) >= 0 ){
   //  Serial.println( "*** SMS Received ***" );
     // EN: Look for the coma in the full message (+CMTI: "SM",6)
     //     In the sample, the SMS is stored at position 6
     int iPos = msg.indexOf( "," );
     String SmsStorePos = msg.substring( iPos+1 );
   //  Serial.print( "SMS stored at " );
  //   Serial.println( SmsStorePos );
     // EN: Ask to read the SMS store
     GprsReadSmsStore( SmsStorePos );
  }

  // EN: SMS store readed through UART (result of GprsReadSmsStore request)
  if( msg.indexOf( "+CMGR:" ) >= 0 ){
    // EN: Next message will contains the BODY of SMS
    SmsContentFlag = 1;
    // EN: Following lines are essentiel to not clear the flag!
    ClearGprsMsg();
    return;
  }

  // EN: +CMGR message just before indicate that the following GRPS Shield message
  //     (this message) will contains the SMS body
  if( SmsContentFlag == 1 ){
 //   Serial.println( "*** SMS MESSAGE CONTENT ***" );
 //   Serial.println( msg );
 //   Serial.println( "*** END OF SMS MESSAGE ***" );
    ProcessSms( msg );
  }

  ClearGprsMsg();
  // EN: Always clear the flag
  SmsContentFlag = 0;
}

Not related to Arduino, but I think the people reading the question might be interested to know z-wave protocol appears to be in, but not turned on, Windows 10 for the Pi.

I think you'd want to include a call to ClearGprsMsg() right before the line GprsReadSmsStore( SmsStorePos );.
Then, msg += String(SerialInByte); is probably wrong, see for example http://arduino.cc/en/Tutorial/StringConstructors:
// using a constant integer:
stringOne =  String(13);
Serial.println(stringOne);      // prints "13"


text:
Program button to switch between two values
There is a function on one of my programs I want to be switch on and off by pressing a button. The button is unbiased otherwise I would set the function to read the button's status of HIGH or LOW.
So I need to create variable named "switch" with an initial value of 0. Then I would create a function would read if buttonPin is HIGH change the value of "switch" by +1. Next time the buttonPin is HIGH change the value by -1 so that every time the button is pressed the value of "switch" alternates between 1 and 0. Now before my loop calls the function I want on or off it can compare the value of "switch" and run or not run the function.
I don't know how to express this in the Arduino sketch. I'm am also open to alternate ways of achieving the same result.

Pseudocode:
value = 0
if button is pressed:
  value = 1 - value

So simple! I'm almost embarrassed I didn't think of it myself.

Be aware that you will need to debounce the input pin, otherwise you will get erratic results due to the mechanical bounce of the contacts.

So that means I will need to set it back to low with digitalWrite(pin,LOW)?

No, that means that you will have to use the method in the Debounce example to detect button presses if your button isn't already debounced.

Would a pull down resistor have the same function?

No, it would not.

It sounds like you are using a number as a boolean (true/false) value.
You might consider using a a boolean instead.
boolean value = false;
if button is pressed {
    value=!value
}
if value {
    // do something here.
}

You can set it to true or false, or change it to it's opposite (with value=!value as shown above). You can also do if value or if !value ("if not value") - these are equivalent to if value=true or if value=false.

Thank you for the suggestion. I was not aware of the Boolean option.

int buttonPin = 10;
`boolean value = false;
void setup(){
pinMode(buttonPin, INPUT);
Serial.begin (9600);
}
void loop(){
if (digitalRead(buttonPin) == HIGH) {
value=!value;
}
Serial.println(value);
delay(10);
}`
I am using this code. The readout on the serial.Print still reads 0 even if I press the button. I have installed a LED to make sure the button is working and the light turns on whenever I press the button.

The code you gave, just looking at it quickly, should turn value on and off every 10 milliseconds while you press the button. What happens if you move the println inside the if() statement?


text:
How to get Baite Pro Mini working?
I have recklessly bought the Baite Pro Mini and I find it difficult to upload any program. I use Ubuntu Linux, but out of frustration I am ready to install Windows, if it is necessary.
I've read the information from the blog http://nerdralph.blogspot.ca/2014/01/baite-pro-mini-review.html . Too bad, that the blog owner didn't put much details. Can anyone here fill some blanks for me?

How exactly should I connect the Arduino device to the computer?
I have a converter USB to serial pl2303HX:  which I tried to connect with the Baite Pro Mini in almost any plausible permutation of the wires, but never got any result.

edit:
Here is the description of pins of the pl2303HX:
(source: fasttechcdn.com)
I did connect it the following way:
Baite Pro Mini      pl2303HX
GND
GND  <------------> GND
VCC  <------------> +5V
RXI  <------------> TXD
TXC  <------------> RXD
DTR

I also tried the permutation with different GND pin. I also tried pressing the reset button on the Baite Pro Mini around the time of hitting the "Upload" button on the Arduino standard compiler.
I believe my failure might have something to do with the absence of DTR pin on the converter that resets the board just before upload. Are my worries justified? Is there anything I can do?

Which exactly Arduino bootloader do I need?

How to connect USBASP to the Beite Pro Mini?

GND to GND, VCC to VCC, TX to RX and vice versa.

@IgnacioVazquez-Abrams That was my second try (not first... ;-) ) and it didn't work. I believe my failure might have something to do with the absence of DTR pin on the converter that resets the board just before upload. Are my worries justified? Is there anything I can do?

@IgnacioVazquez-Abrams I've updated the question

I have several clone Pro Minis I got from several sources on ebay for ~ £2 ($3) each. I also use Ubuntu (10.04 on this old PC but it's fine).
I started with a USB converter similar to yours and it was a bit hit-and-miss choosing when to press the reset to upload. Once I got connections right and worked out when to press reset it became a more reliable procedure but still a pain.
I realised that it would be better to use the auto-reset from DTR so I got a cheapo USB to serial from ebay which claimed to be FTDI (or compatible?) though I didn't know what that meant at the time. With a small converter board to make the right connections it works well.
Your connections look good so if you haven't damaged anything it's probably a matter of when to press reset. Windows won't help!
You must choose the correct board in the Tools menu of the Arduino IDE - Pro Mini with correct AVR chip, speed and voltage. I use programmer AVR ISP (I think)

His connections look bad - gnd & Vcc are adjacent on the processor board and separated by 2 pins on his converter.
A reset does not seem to be needed when using the Baite processor AND Baite USB module.

@RussellMcMahon I didn't mean with my diagram to show the actual layout of the cables, only the labels on one side and (in random order) the labels on the side of the controller and which pin was connected where.

I am waiting for a delivery of the USB converter that supports the reset (has a DTR pin). I hope it will solve my problems. The chip itself doesn't seem to be broken; when powered the blue diode is blinking exactly the same as it was the first day.

Your connections are incorrect if you are "straight through" connecting.
Gnd & Vcc are adjacent on the processor board and separated by 2 pins on your converter.
If you find Gnd, Vcc, TX, RX on USB module and processor then you should

Connect Gnd to Gnd
Connect Vcc to Vcc
Connect ........TXD to RXD and
 ........................RXD to TXD
Ensure that you have the correct USB converter drivers loaded.

A reset does not seem to be needed when using the Baite processor AND Baite USB module.

I have a number of Baite Pro Minis working perfectly.
In my experience (3 or 4 sales so far) Baite's products are usually of acceptable quality .
Connecting "almost any plausible permutation of the wires" is a fine way to attempt to destroy the converter and/or the BPM. Logical connection should work - if you have not damaged something.
Connect as Ignacio says.
Note that you connect BPM-TX to USB-converter-RX, and RX to TX and **NOT RX to RX). The BPM has connections shown on the PCB.

Baite provide this diagram

Your converter module has a different pinout which needs to be allowed for.

You must also have drivers on your system for the USB to serial bridge IC used on your converter. The Baite converter uses a CH340G IC. Your may or may not.

Thank you for your beautiful answer. Don't pay attention to the layout of the pins on the right side, I don't use the "straight through" connection. Pay attention only to the labels. It is cumbersome to draw crossed lines in ASCII.

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


text:
Loading local libraries
I'm new to Arduino/C development (coming from a JavaScript/Ruby environment), but I was wondering if it was possible to include a library from a custom folder within a sketch?
So this is my situation;
project.ino
libs/
  MyNewLib/
    MyNewLib.h
    MyNewLib.ccp

Now my question is: how can I include my custom library? I've tried several variations on this;
# project.ino

#include <libs/MyNewLib/MyNewLib.h>
#include "libs/MyNewLib/MyNewLib.h"
#include <./libs/MyNewLib/MyNewLib.h>
#include "./libs/MyNewLib/MyNewLib.h"

But none of them works. Can anyone tell me if this is possible? I've looked into this question around the web, but I can't find any satisfying answer. Hopefully you guys can help.
Cheers.
UPDATE
I'm aware you can put your libraries in your global libraries folder, but I want them in my local project folder. I want to share them through git with my team.

Please read my question again @Tyson. I'm aware of the global libraries solution, but I want them inside my project.

You have to first tell the IDE where to find the library (see prior link) then within your sketch you call the library.  #include <LibraryName.h>  AFAIK you can not combine the two into a single include specifying the path/to/library/ which is what I guess you're asking.

Okay, so I can't include files from subfolders.. That's a pity..

Windows Symlinks

Yeah I guess symlinks are the only option. Or a custom Makefile, but I'm not sure about that. Thanks!

On windows you can use Visual Micro and Visual Studio. Supports local Arduino libraries. For an example sketch with a local library click "File>New>Project>Arduino Library"

You are stumbling on the fact that the Arduino tools are fundamentally incompatible with real, mature or professional software practices.  They'll probably also incessantly complain about that .git directory, though it won't actually break the build.

Okay, here is how it works, and I checked it to make sure.
Sure you can use hard paths, but every programmer hates using hard paths. They are not portable at all, and they lock your program in place. You use soft or hard links to the files in the project (look up the man pages on "ln"). But,... talk about ugly! So the question is how to do it "correctly"? The key is learning with what parameters and in what path the C/C++ compiler runs.
You will find the conclusion is NOT intuitive at all. Cutting to the chase: relative paths don't work correctly. Now, why?
But first, let me explain why anyone would want to place program files outside the project directory. Programmers like writing program classes, structs, methods, functions, macros, etc., once. As soon as the programmer solidifies the program fragment, he/she wants to put the files in a common tree and move on. Every program thereafter could use that private library. Also, by having the files in a central place, you won't have multiple copies and versions of each. One private library for many private programs.
As of 1.6.13 (Teensy does not yet support 1.8.*), relative includes start from the library, not your directory. It appears that the ano-to-C filter (remember that Arduino does a "conversion" to the target then calls the C/C++ compiler) starts where you installed your Arduino tree. In my case, I installed in "~/bin/arduino". Teensy's home is "./hardware/teensy". The entire home path for the libraries is "~/bin/arduino/hardware/teensy/avr/libraries" where you will find all the support program trees.
In a source file, the '#include "test.hpp"' statement correctly picks the file from your current directory. HOWEVER, if you use '#include "../test.hpp",' the include path does not start in your project directory. Instead it starts in "./libraries"! So the resulting path is:
#include "../test.hpp" ==> ./arduino/hardware/teensy/avr/libraries/test.hpp
In conclusion there is no clean way of making your own tree of tools in  a nearby directory. The only course is to commit your work in the Arduino library and be aware of those rules as well.

I recently tested this local library structure. It works with:
#include "libs/MyNewLib/MyNewLib.h"

The Arduino IDE 1.6.7 build pre-processing will even pick up the source code for the library.
Cheers!

Must be new in 1.6.7

It seems that indeed the newer versions are more flexible and you can include libraries in relative paths. However I still ran into problems when the included files also include other files relative to their location.

Hmm the include problems I just wrote about are not related to paths. It appears that the Arduino IDE does not handle *.ipp files well. See this arduino forum thread

Doesn't work for me in 1.8.1 on Windows.

The Arduino plugin for Visual Studio supports local libraries you can find the plugin here

I am just back to using the arduino after some time away and am somewhat bewildered
by similar issues and confused by different info from different sites and for different
versions of the ide.
What I have found is that if you have a sketch in a directory, then shut down the Ide you can drop .h, .cpp... files in the directory and the ide, when restarted, will open them with the sketch.
Include them by using simple quotes on the file names, no path, no angle brackets.
I am sure this is only part of the full answer, but it has gotten me started.

As far as I know, you can include your libraries from a custom location by using their absolute path.
Since absolute paths could be boring from a code-portability point of view, you could define some macros to get the absolute path from a given relative one. In this way, you would just have to fix the 'project root' path when passing from a device to another.
Define your project's root folder :
    #define PROJECT_ROOT C:\path\to\your\project\folder

Define a relative-to-absolute macro 'transformation' :
    #define TO_STRING(s) #s
    #define ABSOLUTE_PATH(root, relative_path) TO_STRING(root\relative_path)
    #define RELATIVE_PATH(library) ABSOLUTE_PATH(PROJECT_ROOT, library)

Include your files using the relative path :
    #include RELATIVE_PATH(some\file\relative\path.h)
    #include RELATIVE_PATH(another\file\relative\path.h)

I hope it will be useful.

The simplest way I've found to do this is store the libraries in your local sketch directory and create a symbolic link in the [HOME]/Arduino/libraries directory.  Then you can check them in to Git easily with your sketch/project and Arduino's still happy because the libraries are accessible in the global folder.
Maybe even create an install script that creates these links automatically and check that into Git too.

Another really bad fix - create a file called libraries.cpp, which contains:
// force the linker to build the libraries
#include "libraries/LIB1/src/FILE1.cpp"
#include "libraries/LIB1/src/FILE2.cpp"
#include "libraries/LIB2/src/FILE1.cpp"

Of course, this only works if the library does not itself contain any includes...


text:
Issue with removing files progrmatically created under "/www/..."
I am having an issue with removing temporarily files I am creating under the /www directory. I have a subdir, "/www/csv",  where csv formatted files are being written based on sensor data. The files are created on-demand on the YUN, placed in the /www/csv dir, with the whole process driven by a REST call and an AJAX implementation in a browser.  The files are created with no problem with a Filesystem.open(path, FILE_WRITE); call. I can also use the Process calls from the bridge library to rename the file after it is full written. However, if I try to use Process calls (i.e. p.begin("rm");, etc, etc) to remove the files after use, the files are never deleted. I also tried the "mv" the files to /tmp so they would get cleaned up by the OS eventually, but that fails also. I have the rights to /www and /www/csv set to "777". I am assuming this is an access rights issue, however I am unsure what user my REST calls are running as (it would be whatever the default is for a YUN as I have created no additional users on the system).
Thanks in advance,
Pete

what user OWNS the files?  If it is root, then root has to delete, even if perms are 777.  Rather than sudo the rm i would chown.   (p.s. 777 is NEVER the answer).

Are you closing the files before attempting to delete them?

@Tyson Everything runs as root under the Yun so I doubt chown would help.

Owner is ROOT and the process runs as ROOT. Files are closed before attempting to 'rm' or 'mv' the files. I've changed the design to stream the XML directly to the calling web page vs. writing a temp file under /www and having the web page reference it as a static XML page. AT some point I'll go back to try to understand why this didn't work in the first place. To support this change I had to add call to the DOM parser since the REST call responses by default use a TEXT Mine type in the response header. Does anyone know how to define a custom Mime response header using REST calls?

@PeteD Please post this as an answer and mark this question closed.


text:
How to disable RX led on Arduino Micro
I am using the RX LED pin as CS for my SPI connection and experiencing problems while debugging and communicating via SPI. Is it possible somehow to disable the RX blinking while using the serial monitor?

If there isn't an easier way, you could probably neuter the TXLED and RXLED macros in pins_arduino.h. you could make a new board type called "micro-no-led" to have both options available.

When you say neuter do you mean remove them by clearing the defines? I assume removing them completely will cause compilation errors in USBCore.cpp

Sorry; By neuter I mean replacing them with a statement that compiles, but has no effect.


text:
Measure total microcontroller current?
So I have a Duemilanove board and am utilizing 7 output pins, I power a Pixy camera and pan/tilt servos from the ICSP header, i also power an HC-SR04 sonar snsor directly from the board.
Of those 7 output pins, 4 are PWMs for the motors (don't ask why), 3 are for servo control (tower pro mg-995)
when I try to output these 7 pins simultaneously things don't work, i get "components at a time" behavior. Like servos turn first, then the motors spin (servos stopped).
Initially we thought it must be a power supply problem (8 1.2v NiMh bat series) which powers the l298n h bridges (two of them) and also powers the board and servos. But now im starting to fear that it's the board itself and that it can't handle simultaneous outputs.
I've read from here (method #10) that taxing the board more than 200mA is a problem. But what exactly happens if you do just that? And is my case exactly like this one? If so, how to fix it?

Edit +

Here's how the circuit looks.

Edit:
Yes i do think there is a need for decoupling capacitors but im not sure where to put them. They dont seem to work. The bounty goes to the best answer on the proper decoupling of this circuit.
Edit:
Here's some images on the Pixy camera

Edit:
Actually from the original problem I noted when I posted this question, things don't work as expected. WHen the big servos move, the pan/tilt camera don't move when they are supposed to, or the motors briefly stop. I'm wondering if is also an Arduino idiosyncrasy because when I don't run the servo.attach(servo_pin)  code everything works fine.

Try having the power wires go directly from the battery to the motors/h-bridge, instead of via the Arduino. Adding an capacitor to the power rail might help too.

I think the main issue with your circuit is a lack of decoupling between the various big current consumers (motors, servos). Adding a few decoupling caps should help.

You should not be trying to run servos off the Arduino's 5V regulator.  Give them their own.

My experience of high power draw from an Arduino is that it endlessly re-boots so maybe not the issue for you.
The Servo library and PWM pins are probably sharing the same timer therefore motors stop while servos are running.
You could try a different Servo library.
This article is useful to understand the timer/pwm/pin relationships

the second sentence is spot on... it happens. If you could provide a solution for the motors stopping while servos are running?

okay but let's be clear. you are not causing more than 500ma to be drawn through the Uno voltage regulator because you are going to get erratic and confusing results?

i dont think i understand your question clearly. the only components directly powered by the arduino board are: Pixy (cmucam5), sonar (HC-SR04), two tower pro sg-90 servos (pan/tilt).

You are right. Prob not a good question. Should have been what happens if you disconnect the power to the servos and the cam. Do the motors run without halting when you know the servos and cam would be working? You could use a debugger or serial messages to tell you when the servos and cam should be working. This test proves if the power is related to the any issue(s)

ok good question. The servos being connected is not the problem. The problem is when there is that 'servo.attach(servo_pin)' in the code.

good that proves it is a timer/interrupt issue.  What pins are servos and motors connected to?

Here are a few suggestions that might help:

Provide its own power supply to Arduino UNO, so that no voltage drop can occur on the board itself due to high energy consumers as servos and DC motors. As someone suggested in an answer, a voltage drop on Arduino MCU may trigger the Brown-Out Detection (BOD) which will stop the MCU until voltage rises up again, above a given threshold. You could for instance power the UNO with a 9V battery (or the equivalent 7.2V rechargeable pack). Those batteries don't have much energy but it should be OK as long as they are not used for powering motors. Of course, then you'll have to remove the Vin wire to your 8-batteries pack.
Add decoupling caps (between V+ and GND) as near as possible to every energy consumer: that means adding decoupling for each motor driver power-in pins, for each servo power pins, and ALSO for the HC-SR04 sonar sensor (in my experience, it can drop voltage a lot, more than you could expect); note that you may also need decoupling for the camera, but I'm not sure on this one, because I have never used one yet.

Note on decoupling caps:
The value of caps to use depend on many factors, which would be too long to explain here (and I admit that I don't necessarily understand each of these); but typically, you would use a small cap (100nF) when you expect fast (and short) voltage drops, and a bigger cap (>=10uF) when you expect longer voltage drops.
When you don't know, you can just experiment and see what works best.
Using both kinds of caps at the same time (in parallel) does no harm (I have done this in several situations).
For higher caps, you will have to use an electrolytic cap, which is polarized: do make sure that you wire them correctly (+/+, -/-) otherwise they may blow up.
Also, choose a breakdown voltage for the cap that is much above (I'd say 50% above is fine) your power voltage; 16V is a common value that would fit your needs; of course, you can use higher breakdown voltages as well.

the pixy camera, along with the pan/tilt servos, are powered through the SPI header in the Arduino board. When the bigger servos are moving, the pan/tilt servos don't move when they're supposed to (im assuming they are experiencing brownouts). How do you propose to decouple a connection through the SPI header?

I don't see the pan/tilt servos in your circuit; you mean they are directly part og the pixy camera and get their power directly from the SPI header? I'd be surprised about that! I could not find a complete datasheet for TowerPro SG90, but I think it should be powerable by your 7.2V AA batteries pack.

If those servos are really powered through the same SPI power pins as the pixy camera then, I'm afraid you will have to set an extra 5V power supply (regulated) just for it.

yes they are powered by the pixy camera by regulating power off the 5V SPI power pins. Im planning to power them from the regulated 5V of the Arduino board instead. Would that be fine?

That would be the same: the SPI 5V is the Arduino regulated 5V. I can't remember the max current you can draw from here, but I guess it must be quite limited. I doubt just adding a decoupling cap here would be enough.

From the Servo library documentation:

On boards other than the Mega, use of the library disables analogWrite() (PWM) functionality on pins 9 and 10, whether or not there is a Servo on those pins.

This is, as has been suggested, because of conflicting usage of the timers. You should just move your DC motors to other PWM-capable pins.

I know this is after the fact but "Back EMF " is more than likely the issue with the starting and stopping of the servo's and most likely the DC motors.
The power supply could receive a pulse 4 to 5 times its supply voltage. The cpu could be scrambled or reset. Or pulses sent to servos corrupted. Divert the energy of a motor's collapsing magnetic field back into itself with a diode, cathode to the positive supply rail. Basically any time you stop or start a motor its magnetic field has to go somewhere.Digital hates that.

When power goes through a wire, it heats up the wire. The more current you draw, the more it heats up. The "wires" inside a chip such as the one that adjusts the power aresmall, which means it heats up more, and also it takes less to burn it out.
A fuse is essentially a very thin wire. If you draw too much current (amps) through it, it will burn out (melt the wire). Wires inside a chip or on a PCB are much the same, It may recover when it cools down, or not. Some devices have protection, some do not - you may find the arduino shuts itself off to protect itself, to restart after a period. Or it may not.
As has been suggested, you can bypass the board to power the h-bridge - there should be one or two pins to power the h-bridge separate from the signalling, specifically for this reason.
Also, if the board is powered by batteries, the batteries may not be able to supply the current, causing one or more parts not getting enough power.
If you do bypass the voltage regulator and use power directly from the power source, remember that you are using a different voltage - the voltage from the power source, not +5v.
If you are powering your board from USB, then be aware that there are limitations to the power able to be supplied via USB - the USB specs say 150milliamps; any higher power has to be negotiated with the host (PC), so you may get different answers for a laptop vs. a desktop vs. a mains power adapter.

as a matter of fact im using 2 h bridges to drive 4 motors. 4 PWMs connect to the in1, in2, in3, in4 of the drivers (the drivers share a pin for the same "in").

I noticed that my assumptions about powering direct were wrong, and rewrote about half the answer.

my circuit power supply is a series of 8 1.2V NiMH AA batteries. It directly powers the arduino and the motor drivers. Refer to the uploaded image.

when i try to output all the 7 pins to drive all the components (yes all), the board keeps flashing. And the servos merely jitter instead of turning, the motors turn from time to time but not how they were programmed to, and the Pixy (including pan/tilt) doesn't even work.

i also noticed that at this state, when I pull off some of the control wires from the output pins, things start to work for the remaining control pins.

Perhaps you are getting brownouts. I suggest running as many motors as work reliably at the same time, then using a multimeter to measure the voltage between 5V and GND (5v is the one hooked up to HC-SRO4 VCC by the look of it). If this ever drops below 4.3 volts, your chip will shut down ("brown out detection") ; the will typically shut down the motors, raise the voltage, and restart the chip - this results in "flashing" of the power led.

You might also want to measure the voltage across the batteries - this will drop as you draw more power. You will need at least 7 volts across the batteries to run the Arduino at 5v.

Let us continue this discussion in chat.


text:
Programming arduino with Objective-C
Can you use clang, with --mpu=arm, etc. and avrdude to program an Arduino Due (Arm Cortex M3)?

theoretically possible or practically possible?

It's actually the other way round: C/C++ is a subset of Objective C (or more accurately, Objective C is based on C/C++).

OK So programming directly in Obj-C is not a good idea, but if you where dead set on doing it you could look at a tool which translates the Obj-C into C/C++ and then compile the output.  There are/were tools like this around I had to use one to do C++ to C many years ago.

It can be done, however, it is inadvisable. In order to implement this, one must implement the Objective-C runtime, which, though not insurmountable, is very near insurmountable as far as difficulty is concerned. Perhaps someday some brave soul will see fit to grace the world with their custom Arduino Objective-C runtime, but until that day, the rest of us mere mortals have naught to do but wait for the coming of the Objective-C prophet.
If there are any brave souls in the audience who wish to take on this ultimate challenge, then let them. But otherwise, keep the code in C and hold your peace.

Simple version: No, you cannot program Arduino using Objective-C.
Long version:
The Arduino IDE uses avr-gcc as it's compiler, and avr-gcc is a C/C++ compiler, not an Object-C compiler. The Arduino libraries are written in C/C++.
There are other compilers that exist for AVR processors, and so it is possible to use other languages for the AVR.
However, if you switch to a different compiler for your code, you will not be able to use the Arduino libraries with it, because they are written in C/C++ for the avr-gcc compiler. (It may be possible to compile the Arduino libraries with avr-gcc, and then link them to your code using external language linking methods, but that could be a significant challenge.)
Also, I do not know of any existing Objective-C compilers for AVR; it's possible one may exist, but after a quick web search, I didn't find any.

Theoretically, many things are possible. There is an easy way to code Arduino on Xcode with EmbedXCode (http://playground.arduino.cc/Main/EmbedXcode), but in C and CPP.
You need a compiler that will compile your Objective-C to for the AVR (if you are using an AVR-based Arduino), this may be difficult to find. Once your code is compiled, then you need to upload it to the Arduino.
So in any reasonable means, it is at least very challenging.


text:
How Do I Send An Email WITHOUT An Ethernet or WiFi Shield
I can only find info relating to the wifi shield, but I want to send an email without the wifi shield. For now, I just plan on leaving my arduino plugged into a computer, so I just want to use the computer's network connection. Is there a library or something I can grab for this?

If you mean plugged-in via USB, then no. There's nothing you can do on the Arduino that would let you use the computer's network connection directly.
You would need to have a program running on the computer which would communicate with the Arduino via serial. It would effectively act as an intermediary, sending the email on behalf of the Arduino.
Unfortunately, I suspect you'd have to write the program yourself. It's possible that something similar already exists, but at the very least you'd probably have to modify it to suit your needs.

Thanks I found an example of your answer: http://www.instructables.com/id/Tweet-a-Pot-Twitter-Enabled-Coffee-Pot/?ALLSTEPS. This project uses Python as the intermediary.

SLIP or "Serial Line Internet Protocol" is an older idea not heard of as much these days, but should accomplish this goal. http://en.wikipedia.org/wiki/Serial_Line_Internet_Protocol


text:
ISR executes even though an interrupt is not triggered
I am trying to implement a function queue scheduling system. INT1 is connected to a button and int1task causes an LED to flash.
typedef void (*funcptr)(void);
TPrioQueue *queue = NULL;

void int1ISR() {
  if (debounce(&int1time)) // Checks if the interrupt is caused by switch bouncing
    enq(queue, (void*) int1task, 1);
}

Next, I execute the function in loop() by:
typedef void (*funcptr)(void);

void loop(){
  funcptr func = (funcptr) deq(queue);
  if (func != NULL)
    (*func)(); // Stuck in a loop
}

For some reason, the LED keeps flashing even though I have not pressed the button. Why does this happen?
When I remove the line below, the ISR works properly.
enq(queue, (void*) int1task, 1)

The relevant sections of the code:
int debounce(unsigned long *debTimer) {
  unsigned long tmp = *debTimer;
  unsigned long currTime = millis();

  if ((currTime-tmp) > 500){
    *debTimer = currTime;
    return 1;
  }
  else
    return 0;
}

// Flashes LED at pin 6 five times at 2 Hz
void int1task(){
  for(int i=0; i<5; i++){
    digitalWrite(6, HIGH);
    delay(250);
    digitalWrite(6, LOW);
    delay(250);
  }
}

void setup() {
  pinMode(6, OUTPUT);
  attachInterrupt(1, int1ISR, RISING);
  Serial.begin(115200);
}

Code I used for the queue
Here is the schematic I am using:

If debounce() calls millis(), then it will not work, as millis() do not change within an ISR. Can yoi show the code of debounce()?

@jfpoilpret I have edited the code to call millis() only once. Similar to https://community.spark.io/t/how-to-track-debouncing-in-an-interrupt-function/6918

I don't see any code that toggles the led. I don't see any code initializing the interrupts.

Could you please also show the code of int1task? Without it it may be hard to diagnose your issue.

It seems the int1task is never removed from the queue, which would explain it's running forever. Where do the enq and deq come from? How was queue variable declared?

@jfpoilpret enq and deq are declared in a separate file. The queue is part of a struct called 'TPrioQueue'. I declare it TPrioQueue *queue = NULL

@jfpoilpret I do not understand why int1task is not being removed from the queue? I am dequeue-ing it in loop()

I suspect a concurrent access problem (by loop() and the ISR). I think you should post the code of enq, deq and also the TPrioQueue or a link to the code if it is a 3rd-party library.

@jfpoilpret code for the queue

The queue has to be initialized with makeQueue().

May be just a matter of style, but you may just write if (func) func();.

Your snippets are still lacking a few important lines of code: we would like to see the declaration of all variables: queue, int1time. Also, did you check what @EdgarBonet mentioned in a previous comment, ie initialize queue with makeQueue()? That seems a real important point here!

I just tested your sketch on my Uno: it works as expected provided the queue is properly initialized with makeQueue().

@EdgarBonet The circuit works after adding makeQueue()

After checking the queue functions that you use in your sketch, I see there is no protection against concurrent accesses in the enq and deq functions, which is a must-have if you use any of these functions from within an ISR.
I would suggest the simplest changes to these functions as follows:
void enq(TPrioQueue *queue, void *item, int priority)
{
    TPrioQEntry *newEntry=(TPrioQEntry *) malloc(sizeof(TPrioQEntry));

    if(newEntry != NULL)
    {
        newEntry->item=item;
        newEntry->prio=priority;
        newEntry->prev=NULL;
        newEntry->next=NULL;

        // Protect against concurrent accesses starting here
        uint8_t sreg = SREG;
        cli();
        if(queue->head==NULL)
            queue->head=newEntry;
        else
        {
            // Find insertion point.

            // First special case: Item at head has lower priority
            if(queue->head->prio > newEntry->prio)
            {
                // Insert item at the start of the queue.
                newEntry->next=queue->head;
                queue->head->prev=newEntry;
                queue->head=newEntry;
            }
            else
            {
                // Find your insertion point
                TPrioQEntry *trav= queue->head;

                while(trav->next!=NULL && trav->prio < newEntry->prio)
                    trav=trav->next;

                newEntry->prev=trav;
                newEntry->next=trav->next;
                if(trav->next != NULL)
                    trav->next->prev=newEntry;

                trav->next=newEntry;
            }
        }

        queue->itemCount++;
        // Protect against concurrent accesses stops here
        SREG = sreg;
    }
}

void *deq(TPrioQueue *queue)
{
    // Protect against concurrent accesses starting here
    uint8_t sreg = SREG;
    cli();
    // Return NULL if queue is empty
    if(queue->head == NULL)
    {
        // Protect against concurrent accesses stops here
        SREG = sreg;
        return NULL;
    }

    void *ret=queue->head->item;
    TPrioQEntry *tmp=queue->head;

    if(queue->head->next!=NULL)
        queue->head->next->prev=NULL;

    queue->head=queue->head->next;
    free(tmp);

    queue->itemCount--;

    // Protect against concurrent accesses stops here
    SREG = sreg;

    return ret;
}

The above code did not work, the LED still kept flashing

If this still doesnot work, I suspect you may have some bad wiring or interferences somewhere in your circuit. Could you show a clear picture of your circuit? A schematoc would also be nice to have.

The simplest change would be to #include <util/atomic.h> and call deq() from an ATOMIC_BLOCK.

@jfpoilpret [schematic] (https://www.dropbox.com/s/51f8174815zycrg/schematic.pdf?dl=0)

Isn't declaring some of the variables volatile required for this to work reliably?

I don't think so, because the only variables here are pointers; those pointers are not chnaged only the content they point to.

Although you did not clearly mention nor show your wiring, it is possible the problem comes from here.
Barring real concurrency issues with your queue implementation, which I already mentioned in another answer, for which fixes have to be implemented anyway, there are two potential wiring problems in your circuit:

You use INT1 interrupt; that means you must connect your button to PIN 3 for a UNO, any other pin won't work.
You did not specify pinMode(3, INPUT_PULLUP) in your setup(), which means you MUST use an external pullup resistor to force a HIGH value, and connect the other pin of the button to GND (or conversely: put a pulldown resistor and wire the other pin to 5V); otherwise, while the button is left unpressed, you will have a floating input, which means its value will vary randomly between HIGH and LOW, triggering your int1ISR many times when you don't expect it.

The simplest way to solve point 2 (floating input) is to use internal pullup resistors:
void setup() {
  pinMode(3, INPUT_PULLUP);
  pinMode(6, OUTPUT);
  attachInterrupt(1, int1ISR, RISING);
  Serial.begin(115200);
}

and connect one button pin to Arduino PIN 3, and the other button pin to GND.
That will remove floating input and its consequences.

ISRs have flags, typically an enable flag and a pending flag.
The enable flag needs to be set true for the interrupt to occur at all.
The pending flag is set when the interrupt event occurs.
Within the interrupt function, the pending flag must be cleared,
otherwise the the interrupt function will immediately be executed again (and again and again and ...)

AVR resets the interrupt flag once the ISR returns.

I am relatively new to arduino. Could you elaborate more about the flags? Are they like cli() and sei()?

My mistake, INTFn is cleared when the ISR is executed.


text:
Stable frequency generation
I'm trying to work out the best way to generate a stable frequency with my Uno R3
I'm using interrupts to generate an approximately 40KHz frequency which drives some ICs/MOSFETs to effectively generate 40KHz AC which powers a transducer.
I need to receive the frequency at a second transducer and calculate any frequency shifts.

The problem is that the generated frequency drifts a little bit off of 40KHz. Is there a way to lock it in at 40KHz via software? I'm receiving approximately 40KHz output (as measured using PicoScope software) with this code:
#define LEDPIN 13
void setup()
{
pinMode(LEDPIN, OUTPUT);
// initialize Timer1
cli();          // disable global interrupts
TCCR1A = 0;     // set entire TCCR1A register to 0
TCCR1B = 0;     // same for TCCR1B
// set compare match register to desired timer count:
OCR1A = 24;
// turn on CTC mode:
TCCR1B |= (1 << WGM12);
// Set CS11 for 8-bit prescaler:
TCCR1B |= (1 << CS11);
// enable timer compare interrupt:
TIMSK1 |= (1 << OCIE1A);
// enable global interrupts:
sei();
}

void loop()
{
// main program
}

 ISR(TIMER1_COMPA_vect)
{
digitalWrite(LEDPIN, !digitalRead(LEDPIN));
}

If there isn't a way to lock it in, is there atleast a way for the Uno to accurately display/store the frequency of the signal it generated at a given time?
Or is this not plausible because the Uno would "think" it is generating 40KHz?

Thanks for  any hints or suggestions.
EDIT: @RussellMcMahon pointed me in the right direction for this, so I accepted his answer. However, I wanted to share my final code and my misconceptions I encountered. Hopefully this will assist someone else in the future. I'm obviously by no means an expert, and I will try to not give any misleading information here.
My original goal was, although poorly stated, to generate as clean a 40KHz PWM with 50% duty cycle as possible.
Problems with my original code above were:

Using an 8-bit pre-scaler
Using an interrupt
Using digitalWrite()

8-Bit Pre-Scaler
      The problem here was that the counter only ticked over once every 8 clock cycles. 16MHz clock / 8 (pre-scaler) = 2MHz clock When I asked one of my professors about this he stated something along the lines of "a cycle could be missed due to an interrupt, and would cause it to wait 7 more cycles to 'tick'". Indeed I was originally using interrupts, and when we did the calculations it seemed like it could plausibly cause up to a a 1KHz swing at 40KHz.
      To rectify this I took out the pre-scaler, and ran straight at the base clock speed to increase resolution.
Using an interrupt
      Essentially the interrupt could cause clock cycles to not be counted, further complicated by using an 8-bit pre-scaler. If one clock cycle was missed, with a 2MHz clock (after pre-scale), you add 5E-7 seconds to the counter, changing the output frequency.
Using digitalWrite()
      The digitalWrite function is pretty slow. I'm not a guru, but I read this in multiple places and there seems to be a good comparison of methods here: Digital Pin Oscillation To get around this problem it had been suggested I toggle a single bit, which is what I set out to do in my final code. (It is worth noting, now that I've completed this project, that the previous link also makes reference to a library addition for faster digitalWrite/Read/etc....)

I went through a few variations and scrounged code from all over, and made a couple working examples but they didn't do it the way I wished. I believe part of the project I based this version off of was a melding between a previous version I had working and a class example I found online.
Without further ado, I present the code that took me an embarrassing amount of time to write from numerous sources... I really should tinker with this stuff more often:
#include <avr/io.h>
#include <avr/interrupt.h>
void setup()
{
//Disable interrupts
cli();
// Clear Timer1 registers
TCCR1A = 0;
TCCR1B = 0;
// Set OCR1A (TOP): 16MHz/40KHz /2 = 200 steps.
// Divide 200 by 2 = 100 because waveforms are centered around OCR1A (because toggle)
OCR1A = 100;
// Configure Timer/Counter 1
// Select P & F Correct PWM Mode, and OCR1A as TOP. Use WGM Bits 10 and 13.
// WGM Bits are in TCCR1A and TCCR1B. Any previous settings are cleared.

// Enable COM1A0 to toggle OC1A on compare match
TCCR1A = _BV(WGM10) | _BV(COM1A0);
// CS10 to enable base clock without pre-scale
TCCR1B = _BV(WGM13) | _BV(CS10);

//Set OC1A (Digital Pin 9 / Port B Pin 1) to output
DDRB |= _BV(1);
}

void loop()
{
}

 For reference, here is the clock frequency formula. In this instance, I had to divide the result by 2 again since I am toggling.

Resultant output verified by PicoScope:

In closing, you will notice that it isn't exactly 40KHz. Research turned up that the Arduino Uno makes use of a less accurate ceramic resonator to clock the ATMEGA328P (although a 16MHz crystal oscillator is onboard to clock the USB). To further increase accuracy in a generated signal will require the Arduino to be driven with an external clock source.

Have you tried using PWM outputs? Their frequency can be changed, see http://playground.arduino.cc/Code/PwmFrequency.

Presumably processor is crystal controlled? | Cannot the timer control a pin directly without interrupts? - or is that what is happening here ? (glancing through the code it's not obvious (to me) how it completes the function you are implementing.) If this is counter timer mode why are interupts requiired - does not the pin get happily toggled by the timer without invoking an interrupt. If so, an IRQ may add variable latency to the task.

@DaveP, I don't believe I can scale the frequency down to what I need. With the digitalWrite I'm using, basically it creates a PWM from scratch.

@RussellMcMahon I missed a snippet of code when I pasted it originally - please see the updated code. I thought about just running the toggle method through a loop, but wouldn't that potentially tie up the Arduino from doing anything else? Although, if I can rely on it to generate an accurate signal I suppose I wouldn't need the Arduino to do anything else.

You can't have the arduino measure the timer1 generated signal. The clock for timer one is the same as that of the processor, so it will always tell it's right on the money. You'd have to tune it using some external measurement. By the way, I don't get why you aren't using the option of having timer1 toggle the pin, unless there is a need to use pin 13 instead of 9 or 10.

This is using Waveform Generation Mode 9 (0b1001), phase and frequency correct, which gives you a 50% duty cycle by toggling on matching OCR1A while it counts up to OCR1A and then back down.  If you need to adjust the duty cycle away from 50%, you could use you could use the OCR1B compare register to control the OC1B output pin, or you could use WGM mode 8 to set the TOP with ICR1 and control the duty cycle on OC1A with OCR1A.     You could also get to twice the maximum frequency by using the count-up-only fast PWM schemes with WGM modes 14 or 15 (0b1110 or 0b1111).

Sorry for asking but i cant see the ISR function of TIMER1 you used at your last code. I only read the setup of timer and port for digital pin 9.

You can use a timer/counter to output a square wave signal of your choosing without processor intervention or use of interrupts.
In data sheet
"ATmega48A/PA/88A/PA/168A/PA/328/P"Atmel-8271I-AVR- ATmega-Datasheet_10/2014
page 142  it says

The double buffered Output Compare Register (OCR2A and OCR2B) are compared with the Timer/Counter value at all times. The result of the compare can be used by the Waveform Generator to generate a PWM or variable frequency output on the Output Compare pins (OC2A and OC2B). See ”Output Compare Unit” on page 143 for details. The compare match event will also set the Compare Flag (OCF2A or OCF2B) which can be used to generate an Output Compare interrupt request.

The interrupt CAN be generated and used but is optional.
It looks like relevant material extends as far as page 159.

Thanks Russell, I've been struggling with this and that seems to be the right direction to head. I've been reading over the documentation and I think I about have it ironed out.

I know this thread may be dead but if it happens to somebody, the aformentioned method works perfectly fine. You just need to disable timer0 (power_timer0_disable();) and then your 40kHz signal will not fluctuate (in frequency).
In any case, yeah try to avoid digitalWrite if you want speed.

PWM is the solution.
Russel's answer is proper. My contribution here is a simplification and to relay my observations. I made a QA about PWM recently and can affirm that "bit banging" and interrupts are not going to be stable. I observed digital writes to be roughly 1 microsecond, so toggling a pin is 2 µsec. This did not affect my project, so no further tests performed about the digitalWrite() function. Writing changes to the port macro as a whole is much faster than using digitalWrite(), however this still will not have the inherent stability setting up the PWM and its output pin will provide. Anecdotally, analogRead() is roughly 100 µsec.
I set up my timer with a prescaler and then applied a count to OCRxA. Via my prescaler and WGM bits, it turns out that the OCR registers were 1:1 for microseconds. OCRxB perfectly set the pulse width I was seeking.
Observing the period on an o'scope, it might have been off from the exact integer in OCRxA but did not drift. The error I observed was in the tens of microseconds and the values in OCRxB were between 6300 and 63000. Code examples are in aforementioned link to my QA. From researching my own solution, I learned this error is likely within tolerance of the crystal providing CPU freq.

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


text:
I2C hookup - sketch just crashes
I am encountering problems with I2C when trying to attach a 9DoF Sensor to my Arduino Uno. Following these instructions (the hardware setup I have is like in the schematic) I noticed the basic example not working. I've since debugged different aspects and when I use the "I2C Scanner" example from this page it seems something basic with I2C must be wrong. The code from there I am using is:
// I2C Scanner
// Written by Nick Gammon
// Date: 20th April 2011

#include <Wire.h>

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

  // Leonardo: wait for serial port to connect
  while (!Serial)
    {
    }

  Serial.println ();
  Serial.println ("I2C scanner. Scanning ...");
  byte count = 0;

  Wire.begin();
  for (byte i = 8; i < 120; i++)
  {
    Wire.beginTransmission (i);
    if (Wire.endTransmission () == 0)
      {
      Serial.print ("Found address: ");
      Serial.print (i, DEC);
      Serial.print (" (0x");
      Serial.print (i, HEX);
      Serial.println (")");
      count++;
      delay (1);  // maybe unneeded?
      } // end of good response
  } // end of for loop
  Serial.println ("Done.");
  Serial.print ("Found ");
  Serial.print (count, DEC);
  Serial.println (" device(s).");
}  // end of setup

void loop() {}

Instead of this suggested sample output:
I2C scanner. Scanning ...
Found address: 42 (0x2A)
Done.
Found 1 device(s).

The output I am getting is in Serial monitor on the correct baud rate is:
ù
I2C s

With other examples I have tried I have similar results. As soon as something calls Wire.endTransmission() things start to crash and burn.
Any ideas what this could be or how to debug it?

Have you tried using a slower serial comms rate - ie: 9600 baud? That looks like lots serial bits. I would also add an LED heartbeat and boot indicator (flash pin 13 5 times quickly first thing in setup()) so you can detect resets or hangs easily)

Wire.endTransmission() is where the action is. Nothing is actually sent until that point. Wire.beginTransmission just gets ready for sending and Wire.write (if used) adds stuff to an internal buffer.
If it hangs at that point you probably have dodgy hardware. Check the connections are correct (ie. SDA/SCL the right way around, and that it is powered, and that you have a common ground).
Then try a pull-up resistor between SDA and +5V, and SCL and +5V. A typical value resistor (for both resistors) would be 4.7k.
I see from the linked page that the board already has 10k resistors. Hopefully you did not cut the jumper links. Whether or not you did you might want to augment them with 4.7k resistors. Also keep the cable runs short.


text:
PWM pins weird on Arduino Mega, works on Arduino Uno
I've bought one of those cheap 2.4" TFT LCD resistive touchscreens, one of these:
It works great on my Arduino Uno, using the code from this github repository.  Now I'm trying to get this to work on my Arduino Mega.
On the Arduino Uno, the LCD controller data lines are configured as:
data[0:7] = PORTB[0:1] | PORTD[2:7]

ie. data pins 8, 9, 2, 3, 4, 5, 6, 7 make up the LCD controller data lines.
On the Mega, the pin numbers are the same but the ports are configured differently, so that:
data[0:7] = ((PORTH >> 5) & 0x03)
   | ((PORTH << 3) & 0xc0)
   | ((PORTG >> 1) & 0x10)
   | ((PORTE >> 2) & 0x0C)
   | ((PORTE << 2) & 0x20)

I've rewritten the TFTLCD::read8 and TFTLCD::write8 functions accordingly.
The screen doesn't work, though.  I've cut example code down to just resetting the LCD controller and reading the chip ID register, ie:
Tft.writeData(0);
Tft.writeData(0);
Tft.writeData(0);
Tft.writeData(0);

Tft.writeCommand(0);
unsigned id = Tft.readData();

Now, 9 times out of ten, this obtains the correct device ID, 0x9325.  But the other time, it obtains the device ID of 0.
I initially suspected that this was due to the Mega running somewhat faster, but liberally sprinkling delayMicroseconds(10) through the writeData, writeCommand and readData functions doesn't seem to make any difference.
Is there something that I'm missing that is messing with the use of the PWM lines on the Arduino Mega as ordinary digital port pins?

Never mind; this was me making a mess of the bit masking.
See this github repository for working code with Arduino Mega.


text:
arduino webserver serves single web page to WAN/Internet very very slowly
I have an arduino web server running from a mega 2560 and a wiznet ethernet shield.
It serves the single page just fine (and very fast) to the LAN (192.168.1.50), but serves the same page very, very, slowly when accessed from the  WAN/Internet.
I have port forwarding set-up on the modem router so that the Arduino web page  can be accessed from the outside world, and it does work, I can see the page from anywhere, but it's page serve rate is impractically slow. The page takes 30 - 45 seconds to load up.
(I have the RaspPi with Apache set-up, also in the house, using the exact same port forwarding settings - with a different port - and it serves pages to the WAN/Internet very fast).
Has anyone any ideas what might be wrong ?
Thank you

I haven't used the ethernet library for a while, but I remember that it served up tiny packets - basically each write call went in its own TCP packet. It sounds like you may have latency issues across the WAN.
You could try using your Apache instance to proxy the Arduino pages. Details are at http://httpd.apache.org/docs/current/mod/mod_proxy.html I have this running but all my pages are small so I'm not sure how it would behave on larger pages.

The answer is :
I combined all my
client.println("Some text here
");

html statements into much longer statements eg
client.println("Some text here
All On   All Off
Socket 1 On   Socket 1 Off
");

This reduced the number of client.println("  ");  statements by about one third, which resolved the issue.

This would be a good place to get out tcpdump or WireShark (or any other tool that will let you observe network traffic). If you watch the traffic while you're making the a request that goes to the Arduino (perhaps use a phone to make the request so that it comes from outside) you will be able to observe the TCP/IP transactions and see where the delays are.