body:
I want to implement a simple musical keyboard with Arduino using `tone()` and `noTone()` functions, etc.

The desired behavior is:

 - While PC and Arduino are connected via USB/Serial...
 - ...when I press a key, a corresponding note starts playing...
 - ...and if I release that key that note stops playing...
 - ...or if I press _another_ key, another note replaces the former one.

So, basically, instead of "while key is pressed" logic, I would like to just write a byte to serial when a key is pressed, write nothing while the key is held pressed, and write another byte when that key is released.

I will be using a Python script in the PC, but examples in other languages, or just using a plain serial monitor, are fine.

title: How to tell Arduino Uno that I pressed or released a key on PC keyboard over serial?

Answers: 4

body:
You need to come up with a protocol.  Then you need to write the PC software.  The PC software will monitor the keyboard, and when you press a key it will send a certain signal through the serial port. When you release the key it will send a different signal.

How you arrange that is entirely up to you.

You might implement a protocol that sends something like:

    b4
    c4
    d3
    off
    c3
    f3
    off
    g4
    off

Where the first letter is the note, the second letter is the octave to play that note in, and the word "off" is to stop playing.

I don't have a clue (and probably few people here do) how you'd program the PC end in Python.  It most likely depends on what platform you're working on as to what kind of interface you can build.

body:
It sounds really simple, but as I think about it, the python twist makes it near impossible.

First the simple part.  What you are describing is very close to the MIDI spec. It define a sequence of character for note on/note off events over serial. I'm rusty but it something like this x'90' + chan1..16, note, velocity (3 bytes for note on) and x'80' + chan1..16, note, velocity (3 bytes for note off).  ([spec][1])

Firmata took that idea, and turned it into a remote arduino protocol, where instead of a note, a pin number is used (eg pin on/pin off) and you could dig into the firmata that is included with Arduino for some ideas.

The hard part is the keyboard.  I use a function getch, that I define myself based on whether the script is running on a POSIX host or not (although that is technically inaccurate).  It is described at
[https://stackoverflow.com/questions/510357/python-read-a-single-character-from-the-user][2]
but unfortunately it only waits for a keystroke and provide no information about a key release. You are going to have to dig deep and probably write some platform specific code, maybe even a C .DLL, to get that kind of interaction in python. Handling key down/up is trivial in any language but python (for windows anyhow, dont know about *nix)

  [1]: https://ccrma.stanford.edu/~craig/articles/linuxmidi/misc/essenmidi.html
  [2]: https://stackoverflow.com/questions/510357/python-read-a-single-character-from-the-user

body:
As mentioned by Spiked3 there are a few ways to hit the ground running with C#.

Firstly, as detailed by Majenko, you will need an application running on your PC and some code on the Arduino to interact with this. For the desktop application, the two easiest ways to get started with C# are with WinForms, or XNA/MonoGame. WinForms is targeted at Desktop application development; think legacy desktop apps. Although it is not the current defacto standard (replaced largely by WPF) it is very simple and akin to Swing in Java to use. MonoGame and XNA are targeted at video game development. The latter would be my preference as it lends itself more towards real time applications, and has a game loop much like the Arduino so it is very easy to start using. The caveat is that there is more setup involved, but you will probably find this the friendliest and best supported.

Firstly, The Code! So for the Winforms Route, We have something like this:

    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Windows.Forms;

    namespace WindowsFormsApplication1
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }

            private void Form1_KeyUp(object sender, KeyEventArgs e)
            {
                Debug.WriteLine(" Key Up! ({0})", e.KeyCode);

                // TODO: Talk with Arduino
            }

            private void Form1_KeyPress(object sender, KeyPressEventArgs e)
            {
                Debug.WriteLine(" Key Press! ({0})", e.KeyChar);

                // TODO: Talk With Arduino
            }
        }
    }

To get to this point, fire up a new winforms project, and open up the 'Form1' code (the default window which is added to the project) add the methods as outlined above. You will need to go to the designer afterwards and add events for on KeyPressand on KeyUp to tie these functions to the Window. You can do this by clicking the Window, then opening the Properties Panel, and then clicking the lightening bolt. You will see a list of event names; find the corresponding events (Key Press and Key Up) and associate them with these methods.

From here, you can perform some logic when a button is either pressed or released.

The monogame or XNA approach is a bit simpler to follow as there is no hidden magic; but may be more intimidating if you're not familiar with C# and the project type.

    using Microsoft.Xna.Framework;
    using Microsoft.Xna.Framework.Input;
    using System.Diagnostics;

    namespace GameName1
    {
        public class Game1 : Game
        {
            GraphicsDeviceManager graphics;

            KeyboardState currentState;
            KeyboardState previousState;

            public Game1() : base()
            {
                graphics = new GraphicsDeviceManager(this);
                Content.RootDirectory = "Content";
            }

            protected override void Initialize()
            {
                // Get state management started
                currentState = Keyboard.GetState();

                base.Initialize();
            }

            protected override void Update(GameTime gameTime)
            {
                // Listen for exit command
                if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
                    Exit();

                // Update the state of your keyboard object
                previousState = currentState;
                currentState = Keyboard.GetState();

                // Detect Keypress of key 'F'
                if (currentState.IsKeyDown(Keys.F) && previousState.IsKeyUp(Keys.F))
                {
                    // F Key has been pressed
                    Debug.WriteLine(" Key Pressed! ({0})", 'F');
                    //TODO Talk to Arduino
                }

                // Detect Keyrelease of key 'F'
                if (currentState.IsKeyUp(Keys.F) && previousState.IsKeyDown(Keys.F))
                {
                    // F Key has been pressed
                    Debug.WriteLine(" Key Released! ({0})", 'F');
                    //TODO Talk to Arduino
                }

                base.Update(gameTime);
            }
        }
    }

In either case, you will need to get yourself set up first. Get a compy of Visual Studio Community from the link below, and install MonoGame if desired. Then do some C# tutorials to get comfortable in your new environment.

 - [Visual Studio Community Edition][1]
 - [Mono Game][2]
 - [C# Tutorial][3]
 - [C# Mono Game Tutorial][4]
 - [C# WinForms Tutorial][5]

Lastly, you will want to talk with your Arduino. This can be done by implementing a compatible Serial interface between your desktop application and your Arduino. See the tutorial below to get started!

 - [Arduino C# Serial Tutorial][6]

I hope this information is useful. There is a very broad range of topics mentioned here, and it may seem overwhelming at first - but C# is a very idiosyncratic language in that it permits rapid development in many different scenarios, and I think that you will find it rewarding to conquer the learning curve.

  [1]: https://www.visualstudio.com/en-us/products/visual-studio-community-vs.aspx
  [2]: http://www.monogame.net/
  [3]: https://msdn.microsoft.com/en-us/library/aa288436(v=vs.71).aspx
  [4]: http://rbwhitaker.wikidot.com/monogame-tutorials
  [5]: https://msdn.microsoft.com/en-us/library/dd492132.aspx
  [6]: http://www.instructables.com/id/Interfacing-your-arduino-with-a-C-program/

body:
UPDATE: When I posted this answer I had not yet any knowledge of the Processing Language. If you came to this answer with the same intention I had (the question title), I strongly suggest you to use Processing instead, which has much more straightforward keyboard event capturing and serial communication working out of the box with minimal code.

A question showing this in action is here: https://stackoverflow.com/questions/18366482/processing-to-arduino-with-keyboard

----------

After realizing that what I actually wanted was to "capture keyboard events", I ended up using [PyGame][1] due to its minimalistic setup. Now I can send whatever I want to the Arduino using [PySerial][2].

PS.: Don't be fooled by the lame aesthetics of PyGame website, it is a very mature gaming platform.

Full code here: https://github.com/heltonbiker/Experiments/tree/master/SerialMusicKeyboard

    #/usr/bin/env python

    import pygame
    import serial
    import glob
    import time

    def pygameSetup():
        pygame.init()
        screen = pygame.display.set_mode((468, 60))

        background = pygame.Surface(screen.get_size())
        background = background.convert()
        background.fill((250, 250, 250))

        if pygame.font:
            font = pygame.font.Font(None, 36)
            text = font.render("Shut up 'n play yer keyboard!", 1, (10, 10, 10))
            textpos = text.get_rect(centerx=background.get_width()/2)
            background.blit(text, textpos)

        screen.blit(background, (0, 0))
        pygame.display.flip()

    def main():

        pygameSetup()

        initialized = False

        while not initialized:
            try:
                serialpath = glob.glob('/dev/ttyACM*')[0]
                ser = serial.Serial(serialpath, 9600)
                initialized = True
                print "serial up"
            except:
                time.sleep(500)
                print "waiting for serial"

        while True:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    return
                elif event.type == pygame.KEYDOWN:
                    print event
                    ser.write(chr(event.key))
                elif event.type == pygame.KEYUP:
                    ser.write(chr(0))

    if __name__ == '__main__':
        main()

  [1]: http://www.pygame.org/news.html
  [2]: http://playground.arduino.cc/interfacing/python


body: Which pins are the analog and digital pins? I've been searching the internet for an hour and I could get an answer.

title: Where are the digital and analog pins for the adafruit atmega 32u4 breakout board?

Answers: 1

body:
The information is right there on the product page for you. It took be a total of about 4 seconds to find it.

http://ladyada.net/products/atmega32u4breakout/

![enter image description here][1]

  [1]: https://i.stack.imgur.com/d4NSw.png


body:
I want to make a network with arduinos and nrf24l01 chips. The network will be like this:

 - 1 master arduino
 - multiple (no specific number) slave nodes

I want all nodes to have the same receiving and the same transmitting address and the master arduino to understand which one send the message from the message itself.
For example:

**Master:**
Receiving: 0xABCDABCD71
Transmitting: 0xABCDABCD01

**Slave 1**
Receiving: 0xABCDABCD01
Transmitting: 0xABCDABCD71

**Slave 2**
Receiving: 0xABCDABCD01
Transmitting: 0xABCDABCD71

**Slave 3**
Receiving: 0xABCDABCD01
Transmitting: 0xABCDABCD71

**Slave 4**
Receiving: 0xABCDABCD01
Transmitting: 0xABCDABCD71

When master send a message, all nodes will receive it.
What I want to ask is :

 - Is that possible?
 - Will there be any problems?
 - Is there any other way so I can add more nodes in the future without changing the code?

title: Multiple nodes with the same receiving and transmitting address

Answers: 1

body: as well as comment #1 the other thing will be the ack packets that the slaves will send back to the master to confirm message recieved. with all slaves sending back a ack at about the same time there will be no way for master to tell which ack is from which client, and thus who needs a retransmit. a way around this is to turn off ack for the clients and make the master transmit max times regardless. there is a rf24 fork that has broadcast mode, the makes it more easy to specify not to wait for ack before retransmitting


body: I recently bought the atmega 32u4 breakout board from adafruit. I uploaded a sketch, then it says that there isn't a timer 2 on it and it won't do as I programmed my sketch. how can I fix this?

title: What is wrong with my 32u4 breakout board from adafruit?

Answers: 1

body: You will need to port any libraries and code that depend on timer 2 to the '32U4 architecture. There is no way to add timer 2 to the chip, and it is likely that trying to force it to use a different timer won't help since it may configure things the other timer doesn't have.


body:
Few days ago, I built my own custom Arduino on the breadboard. It is built according to tutorial on http://www.crash-bang.com/resource/breadboard-arduino/. The Atmega328P-PU is already burned with the Arduino bootloader with simple blink sketch.

For the programmer, I decided to use the Arduino USB2Serial. Again, it is connected as shown on crash-bang site. Problem is I get this error when uploading a different sketch:

    avrdude -Cavrdude.conf -v -patmega328p -carduino -PCOM3 -b115200 -D -Uflash:w:build244630154737317489.tmp/sketch_may23a.cpp.hex:i

    avrdude: Version 6.0.1, compiled on Apr 15 2015 at 19:59:58
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "avrdude.conf"

         Using Port                    : COM3
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : Arduino
         Description     : Arduino
         Hardware Version: 3
         Firmware Version: 4.4
         Vtarget         : 0.3 V
         Varef           : 0.3 V
         Oscillator      : 28.800 kHz
         SCK period      : 3.3 us

    avrdude: AVR device initialized and ready to accept instructions

    Reading | ################################################## | 100% 0.00s

    avrdude: Device signature = 0x1e950f
    avrdude: reading input file "build244630154737317489.tmp/sketch_may23a.cpp.hex"
    avrdude: writing flash (450 bytes):

    Writing | avrdude: stk500_recv(): programmer is not responding

Most of the time I do not even get to this point and just end up with something like:

    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xf5

What I have done so far:

 - I already tried to reset Arduino just before uploading the sketch.
 - According to the avrdude, bootloader is fine.
 - Reinstalled drivers, Arduino IDE
 - Changed the USB cable and connected it to another USB slot
 - Burned new bootloader using ArduinoISP

Thank you for help.

title: Atmega328P-PU: Programmer is not responding

Answers: 1

body:
"Step 3 says to connect +ve rail –> AVCC (pin 20) and +ve rail –> AREF (pin 21). You can leave those pins not connected. "

+ve rail should not be connected to Aref. The +ve rail will connect via the internal operation of the ADC mux.

AVCC and both Gnds should be connected per the datasheet:
5.2.7. AVCC
AVCC is the supply voltage pin for the A/D Converter, PC[3:0], and PE[3:2]. It should be externally connected to VCC, even if the ADC is not used.

28.2.
AVCC must not differ more than ±0.3V from VCC.... Optionally, AVCC or an internal 1.1V reference voltage may be connected to the AREF pin by writing
to the REFSn bits in the ADMUX Register. The internal voltage reference must be decoupled by an external capacitor at the AREF pin to improve noise immunity.

If you connect Aref to the +ve rail externally, and then select the internal reference, things can go bad.

FTDT thru 0.1uF cap to Reset, with 10K pullup, and reverse biased diode to VCC, works for me in plenty of designs.  Not sure why it does not work in all cases. The diode dissipates any spike on the Reset line to keep the chip from thinking high voltage programming mode is being started.


body: I've been reading about the protocol DASH7 but can't find much documentation about it. There seems to be a protocol stack called OpenTag writen in C and I want to know if there is something familiar written in arduino code and why can't I find a lot about this tecnology.

title: Is it possible to use the DASH7 protocol in an arduino?

Answers: 0


body:
   I'm trying to teach myself some low[er] level code, but I just can't get it to work. I've tried OR-ing stuff in, AND-ing stuff in, and just straight up defining stuff, but it's not blinking! What am I doing wrong here?

I am using an Arduino UNO R3 DIP for this. I am just using the on-board LED, (on pin13/PORTB_5)

Current code:

    #define STATE B00001000
    #define ZERO B00000000
    void setup() {
     DDRB = STATE;
     }

    void loop(){
     PORTB |= STATE;
     delay(500);
     PORTB &= ZERO;
     delay(500);
     }

title: Starting Off Low-Level Port Access

Answers: 1

body:
It would probably help if you were using the right pin.  In the pins_arduino.h file for the Uno is this diagram:

    //                  +-\/-+
    //            PC6  1|    |28  PC5 (AI 5)
    //      (D 0) PD0  2|    |27  PC4 (AI 4)
    //      (D 1) PD1  3|    |26  PC3 (AI 3)
    //      (D 2) PD2  4|    |25  PC2 (AI 2)
    // PWM+ (D 3) PD3  5|    |24  PC1 (AI 1)
    //      (D 4) PD4  6|    |23  PC0 (AI 0)
    //            VCC  7|    |22  GND
    //            GND  8|    |21  AREF
    //            PB6  9|    |20  AVCC
    //            PB7 10|    |19  PB5 (D 13)
    // PWM+ (D 5) PD5 11|    |18  PB4 (D 12)
    // PWM+ (D 6) PD6 12|    |17  PB3 (D 11) PWM
    //      (D 7) PD7 13|    |16  PB2 (D 10) PWM
    //      (D 8) PB0 14|    |15  PB1 (D 9) PWM
    //                  +----+

That shows that pin D 13 is PB5 which would be a binary value of `0b00100000` not `0b00001000` as you have, which would be PB3, or pin D11.

The only way I can come up with `0b00001000` is if I count from the left (wrong) and start at 1 (wrong) rather than count from the right (right) and start at 0 (right).


body:
`Arduino` pins can be used as `UART` using the `SoftwareSerial.h` library. Is there any alternative for `AVR`?

I need more than one serial port on a `ATmega328P`, but i don't use `Arduino`.

`SoftwareSerial.h` is tied to `Arduino.h` and `Arduino` pins. I do not use `Arduino`, i use `avr-gcc` with `atmega328p` and `atmega8`.

title: SoftwareSerial.h alternative with AVR (Two Serial/UART ports in atmega328p)

Answers: 1

body:
AVR274 describes a single-wire, half-duplex software UART.

AVR304 describes a half-duplex, interrupt-driven software UART, and AVR305 describes a polled alternative.

AVR307 describes implementing a half-duplex UART using a USI.

All code associated with each app note can be downloaded from Atmel's website.


body:
I am using the embedded coder target for arduino following this: (http://www.mathworks.com/matlabcentral/fileexchange/30277-embedded-coder-target-for-arduino). I am having problem while running the myarduino_blink.slx demo.

My MATLAB version is R2015a, and I am using an Arduino Uno. I ran the file setup_custom_target_arduino.m after changing the relevant directory listing and the arduino version in the m file, and I got the output of Arduino on COM 3, which was correct.

After this, I checked the Simulink Library Browser and I had the Custom C/C++ Target Arduino Library will all its modules. Now when I simulate the model, I get the following error:

**Error in S-function 'myarduino_blink/Digital Output':
S-Function 'sfunar_digitalOutput' does not exist**

Kindly help me out, what could I have done wrong?

title: Issue with Embedded Coder Target for Arduino

Answers: 0


body:
I would like to make a makefile for compiling c programs for the arduino. I am somewhat familiar with make but have never used it with avr-gcc. What is the simplest way I could put the commands below in a makefile?

    $ avr-gcc -Os -DF_CPU=16000000UL -mmcu=atmega328p -c -o led.o led.c
    $ avr-gcc -mmcu=atmega328p led.o -o led
    $ avr-objcopy -O ihex -R .eeprom led led.hex
    $ avrdude -F -V -c arduino -p ATMEGA328P -P /dev/ttyACM0 -b 115200 -U flash:w:led.hex

title: Basic makefile for avr-gcc

Answers: 2

body:
It's no different to working with Make and any other form of GCC.  Just set your CC variable and CFLAGS variable accordingly and work as per normal.

For instance, I just knocked this one up:

    CC=avr-gcc
    OBJCOPY=avr-objcopy

    CFLAGS=-Os -DF_CPU=16000000UL -mmcu=atmega328p
    PORT=/dev/ttyACM0

    led.hex: led.elf
        ${OBJCOPY} -O ihex -R .eeprom led.elf led.hex

    led.elf: led.o
        ${CC} -o led.elf led.o

    install: led.hex
        avrdude -F -V -c arduino -p ATMEGA328P -P ${PORT} -b 115200 -U flash:w:led.hex

That's saying that any automatic C compilation will be done with avr-gcc and the flags specified in CFLAGS.  It will by default make the hex file using OBJCOPY, which is set to the avr one, which relies on the file led.elf - so to get that file it runs the led.elf target, which links the object file led.o with the default libraries using whatever was set in CC. To do that it needs led.o, and it makes that automatically using the program specified in CC and the flags in CFLAGS.  You can then optionally to `make install` which will run `avrdude` to install the hex file into the chip.

You can make it even more generic so you can copy it in to other projects and make the minimum changes necessary:

    BIN=led
    OBJS=led.o test.o

    CC=avr-gcc
    OBJCOPY=avr-objcopy
    CFLAGS=-Os -DF_CPU=16000000UL -mmcu=atmega328p
    PORT=/dev/ttyACM0

    ${BIN}.hex: ${BIN}.elf
        ${OBJCOPY} -O ihex -R .eeprom $< $@

    ${BIN}.elf: ${OBJS}
        ${CC} -o $@ $^

    install: ${BIN}.hex
        avrdude -F -V -c arduino -p ATMEGA328P -P ${PORT} -b 115200 -U flash:w:$<

    clean:
        rm -f ${BIN}.elf ${BIN}.hex ${OBJS}

That uses "automatic variables" and simple name replacement.  `BIN` contains the "base" of your binary files, `OBJS` contains the list of object files.  $@ is the name of the current target, $< is the name of the first prerequisite, and $^ is the list of all the prerequisites.  Just change `BIN` and `OBJS` to suit.  As a bonus I have thrown in `make clean` to remove the compiled files and just leave you with the source.

body:
The accepted answer is great as it has given me a valuable lesson in all kinds of debugging tools (avr-objdump -D has become a close friend). Namely, the line:

`${OBJCOPY} -O ihex -R .eeprom $< $@`

is missing the architecture flag and should read

${OBJCOPY} **-mmcu=atmega328p** -O ihex -R .eeprom $< $@

Without the -mmcu architecture flag, avr-gcc guesses we are compiling for 8515 architecture (definitely not) and it produces the .elf file without initial instructions for initializing, i.e. without instructions to call the "main" function etc.

This results in confusing behavior as any simple program (e.g. blink) with only the "main" function works perfectly, but if you define another function before or after the "main", it runs that function and never calls "main" or it restarts all the time etc.

I am also not a particular fan of avoiding the verification of correct MCU type and uploaded program, so I'd advocate not to use -F and -V and use -v instead.

So, the improved answer could be:

    PKG=led
    BIN=${PKG}
    OBJS=${PKG}.o
    MCU=atmega328p

    CC=avr-gcc
    OBJCOPY=avr-objcopy
    CFLAGS=-Os -DF_CPU=16000000UL -mmcu=${MCU} -Wall
    PORT=/dev/ttyACM0

    ${BIN}.hex: ${BIN}.elf
            ${OBJCOPY} -O ihex $< $@

    ${BIN}.elf: ${OBJS}
            ${CC} -mmcu=${MCU} -o $@ $^

    install: ${BIN}.hex
            avrdude -v -c arduino -p ${MCU} -P ${PORT} -b 115200 -U flash:w:$<

    clean:
            rm -f ${BIN}.elf ${BIN}.hex ${OBJS}


body:
**What is the best / simplest way to play audio files from an SD card?**

I'm currently working on a sound board, where each button plays a different sound. But I have yet to find the right combination of shields / hardware to do this efficiently.

Is there a shield that supports this directly (SD card -> speaker)? Note that I also need additional pinheads for my buttons to connect to. I think I will be using the Arduino Mega for that purpose.

title: How can I play audio from an SD card?

Answers: 2

body:
    #include <SD.h>                      // need to include the SD library
    //#define SD_ChipSelectPin 53  //example uses hardware SS pin 53 on Mega2560
    #define SD_ChipSelectPin 10  //using digital pin 4 on arduino nano 328
    #include <TMRpcm.h>           //  also need to include this library...

    TMRpcm tmrpcm;   // create an object for use in this sketch
    char mychar;

    void setup(){

      tmrpcm.speakerPin = 9; //11 on Mega, 9 on Uno, Nano, etc

      Serial.begin(9600);
      if (!SD.begin(SD_ChipSelectPin)) {  // see if the card is present and can      be initialized:
        Serial.println("SD fail");
        return;   // don't do anything more if not
         }
      tmrpcm.play("beware.wav"); //the sound file "music" will play each time the arduino powers up, or is reset
    }

    void loop(){

      if(Serial.available()){
        mychar = Serial.read();

        if(mychar == 'o'){ //send the letter p over the serial monitor to start playback
      tmrpcm.play("helpyou.wav");
    } else if(mychar == 'r'){ //send the letter p over the serial monitor to start playback
      tmrpcm.play("chortle.wav");
    } else if(mychar == 'q'){ //send the letter p over the serial monitor to start playback
      tmrpcm.play("helpyou.wav");
    } else if(mychar == 'p'){
      tmrpcm.play("beware.wav");
    }
    else if(mychar == 'w'){ //send the letter p over the serial monitor to start playback
      tmrpcm.play("impresiv.wav");
    }
    else if(mychar == 't'){ //send the letter p over the serial monitor to start playback
      tmrpcm.play("seekyoda.wav");
    }
    else if(mychar == 'y'){ //send the letter p over the serial monitor to start playback
      tmrpcm.play("sensefear.wav");
    }
    else if(mychar == 'u'){ //send the letter p over the serial monitor to start playback
      tmrpcm.play("strongami.wav");
    }
    else if(mychar == 'i'){ //send the letter p over the serial monitor to start playback
      tmrpcm.play("whyhere.wav");
    }
      }

    }

This code should be helpful. Make sure you have a SD card reader. You must also hookup the card reader:

3.3v goes to 3.3v on the Arduino UNO (for power)

GND goes to Ground on Arduino UNO

D0 goes to pin 12 on Arduino UNO

D1 goes to pin 11 on Arduino UNO

CLK goes to pin 13 on Arduino UNO

D3 goes to pin 10 on Arduino UNO

Lastly, download an arduino library so it can play audio files.

https://github.com/TMRh20/TMRpcm

body:
There are several audio products/shields.  Because you mention "speakers", the first one listed can come with an on-board amplifier to drive speakers directly.  Most shields just give line-out to drive a pre-amp.

* Adafruit Music maker shield plays MP3/WAV/OGG from microSD http://www.adafruit.com/products/1788
* Adafruit Wave shield plays WAV files on SD card http://www.adafruit.com/products/94
* SparkFun MP3 trigger board supports 256 tracks and a serial protocol for running individual tracks. https://www.sparkfun.com/products/11029
* SparkFun MP3 shield board plays MP3/WAV/OGG https://www.sparkfun.com/products/10628


body:
I'm writing code for a project with Arduino Yun. My project is quite simple: it takes a picture with a webcam and saves it in a PNG or JPEG file format. I've already installed the uvc driver for Arduino Yun and tested it with my webcam and the fswebcam application. The application saved pictures both in PNG and JPEG format successfully, so I went on and installed the C compiler, make and binutils for Arduino Yun and started to write my own application that would do the same thing (just taking a picture and saving it in PNG format). After writing the code to capture the pixels of the image, I decided to write them down in a PNG file format by using the libpng library available for Arduino Yun through luci web control panel. After installing the package, I included the png.h (using #include png.h) in my source code and wrote the code to write those pixels down in a simple PNG file (thanks to this tutorial: http://www.labbookpages.co.uk/software/imgProc/libPNG.html).
What's the problem? It just won't compile! I tried everything and all I got were "undefined reference to 'function name here'" errors. I thought that, maybe, libpng was buggy so I moved to libjpeg. No luck! I get the same errors over and over again. I really don't know what else I can do, I tried everything, it just seems that the Arduino Yun C compiler can't handle "external" libraries. I thank you in advance for any help you'll give me...

Here are the errors I get when I try to compile it using the libjpeg library:

    /tmp/ccdzMFgN.o: In function `salvaImmagineJPEG':
        ScattaFoto.c:(.text+0x1d9c): undefined reference to `jpeg_std_error'
        ScattaFoto.c:(.text+0x1da8): undefined reference to `jpeg_std_error'
        ScattaFoto.c:(.text+0x1dc8): undefined reference to `jpeg_CreateCompress'
        ScattaFoto.c:(.text+0x1dd4): undefined reference to `jpeg_CreateCompress'
        ScattaFoto.c:(.text+0x1dec): undefined reference to `jpeg_stdio_dest'
        ScattaFoto.c:(.text+0x1df8): undefined reference to `jpeg_stdio_dest'
        ScattaFoto.c:(.text+0x1e2c): undefined reference to `jpeg_set_defaults'
        ScattaFoto.c:(.text+0x1e38): undefined reference to `jpeg_set_defaults'
        ScattaFoto.c:(.text+0x1e54): undefined reference to `jpeg_set_quality'
        ScattaFoto.c:(.text+0x1e60): undefined reference to `jpeg_set_quality'
        ScattaFoto.c:(.text+0x1e78): undefined reference to `jpeg_start_compress'
        ScattaFoto.c:(.text+0x1e84): undefined reference to `jpeg_start_compress'
        ScattaFoto.c:(.text+0x1ed8): undefined reference to `jpeg_write_scanlines'
        ScattaFoto.c:(.text+0x1ee4): undefined reference to `jpeg_write_scanlines'
        ScattaFoto.c:(.text+0x1f10): undefined reference to `jpeg_finish_compress'
        ScattaFoto.c:(.text+0x1f1c): undefined reference to `jpeg_finish_compress'
        collect2: ld returned 1 exit status

title: Arduino Yun doesn't link any library

Answers: 1

body:
It's not the compiler, it's the libpng package (and other libraries too).  It only contains the runtime shared library (`.so`) files.  You can't use it for development.

I haven't yet found if it's possible to directly install a full development package or not - normally development for OpenWRT is done outside the low-powered chip using a cross-compiler environment on a PC.


body:
Background:

My goal is to use sdFat library, more precisely AnalogBinLogger example.

I want to log data from changing analog pins for example, I want to log from pin 0 to pin 3 for 5 minutes and then from pin 4 to pin 6 for another 5 mins and then from pin 7 to pin 9 for another 5 mins. that is going to be continuously which means I am going to get rid of the part where you have to enter "r" to start logging.

Regarding the time, I managed to figure it out, I am just using the value of the variable count, if my sampling rate is 1000 samples/sec for example then 5 minutes will be 1000*60*5 and the change will be done in this line:

    if (Serial.available()) {
      // Stop ISR calls.
      adcStop();

to

    if (count >1000*60*5) {
      // Stop ISR calls.
      adcStop();

and this worked fine.

My problem is with the changing pins:

    const uint8_t PIN_LIST[] = {1};

I changed this line to

    uint8_t PIN_LIST[3] = {};

First I removed the word `const`, because it's not going to be constant anymore, and I just declared an empty array, and second I am changing the pins in the loop.

Here is the loop after I got rid of doing the serial input:

    void loop(void) {
    int i;
    for (i=0;i<=12;i+3)
    {
      PIN_LIST[] = {i,i+1,i+2};
      logData();
      Serial.println("done");
     }}

The problem is I get this error :

 1. AnalogBinLogger.ino: In function 'void loop()':
 2. AnalogBinLogger:808: error: expected primary-expression before ']'
    token
 3. AnalogBinLogger:808: error: expected primary-expression before '{'
    token
 4. AnalogBinLogger:808: error: expected `;' before '{' token

The line 808 is:

    PIN_LIST[] = {i,i+1,i+2};

So this is the only error, any help please?

The code is so long (800+ lines) if this information is not enough and you need me to explain a part then just tell me.

title: changing analog pins data logging using sdFat library

Answers: 1

body:
in case someone has the same problem
it seems like after you initialize an array this way

uint8_t PIN_LIST[3] = {};

you won't be able to assign all the values at once:

PIN_LIST[] = {i,i+1,i+2};
instead you assign each individual value

 - PIN_LIST[0] = i;
 - PIN_LIST[1] = i+1;
 - PIN_LIST[2] = i+2;

and now it worked : )


body:
I am using Arduino Uno, and MPU6050(3 axis imu sensors), not gate,  and L298 dc motor drive.

My algorithm is very easy.
Receive an angle how the balancing robot is tilt.
Decision speed of motors by using the angle.
For example, when robot is tilt n degrees forth or back, robot will go forth or back with speed proportional n.

My code is similar to the following code.
Sorry, it is difficult to type on my phone. TT
<!-- language-all: lang-cpp -->

    Angle = getComplementaryAngle();

    Speed = pidCompute(abs(Angle));
    // Speed range: 0 to 255

    if (Angle > 0.4) {

      DigitalWrite(dirA, HIGH);

      DigitalWrite(dirB, HIGH);

      analogWrite(enA, Speed);

      analogWrite(enB, Speed);

    }

    else if (Angle < -0.4) {

      DigitalWrite(dirA, LOW);

      DigitalWrite(dirB, LOW);

      analogWrite(enA, Speed);

      analogWrite(enB, Speed);

    }

    else {

      analogWrite(enA, 0);

      analogWrite(enB, 0);

    }

I don't know why left motor's speed is different from right motor's one.
I checked the voltage of motor pin.
Both pins' voltage are same as 11V.
I think pwm is wrong.

When Arduino makes two pwm output, it causes some problems?

title: DC Motor speed control by using pwm

Answers: 0


body:
I'm trying to convert the project [here][1] to an Arduino Nano.

I scaled the waveforms from 12 bit to 8 bit values. I replaced the `analogReadResolution` and `analogWriteResolution` calls with `pinMode(10, OUTPUT)` and `pinMode(11, OUTPUT)` and changed the two `analogWrite` calls to write to pins 10 and 11. Otherwise the program is unchanged.

My thinking (and this is where my poor electronics skills come into play) is that I just need a simple low pass filter to convert the PWM into the appropriate waveform (which, at startup, ought to be a sine wave on both pins). According to the article, the frequency generator tops out at 170Hz. I figure the PWM signal is going to be significantly higher than that, so I use R=3.3K and C = .1uF for my RC filter which ought to give me a -3dB at about 480Hz, but what I'm seeing on my scope is a mess. Not a stable signal at all.

This is the waveform I'm seeing on my scope:

![OscopeImage][3]

Can someone educate me?

Update: BTW, this is the initial waveform which ought to be a sine wave.

  [1]: http://www.arduino.cc/en/Tutorial/DueSimpleWaveformGenerator
  [3]: https://i.stack.imgur.com/RK99A.jpg

title: Function generator with Arduino Nano

Answers: 2

body:
The PWMs on pins 10 and 11 of the Arduino Nano run at 488 Hz. That's what you are seeing on the scope. The code you are using was meant for an Arduino Due, which has real digital-to-analog converters.

**Edit**: You can tune the PWM to run as high as `F_CPU/256` by
reconfiguring the timers 1 and 2 to “fast PWM” mode, instead of phase
correct PWM, and setting their prescalers to 1 instead of 64. This
should raise the PWM frequency to 62.5 kHz, given that the Nano has
a 16 MHz clock.

The following code should do exactly this. You can put it somewhere
inside your `setup()`. **Warning**: I have not tested this code. This
will change the PWM frequency on pins 10 and 11, but also on pins 3 and
9, which share the same timers. It will probably break the `tone()`
Arduino function.

<!-- language: lang-c -->

    // Set PWM frequency to 62.5 kHz on pins 3, 9, 10 and 11.
    TCCR1A = 1<<WGM10;
    TCCR1B = 1<<WGM12 | 1<<CS10;
    TCCR2A = 1<<WGM21 | 1<<WGM20;
    TCCR2B = 1<<CS20;

body: What you're proposing can work, but the PWM frequency needs to be *much* higher than the frequency you're trying to generate. If you look at the PCMAudio sample you'll see that it tunes the PCM frequency almost as high as it will go.


body:
I have a MacBook Pro running OS X Yosemite (10.10.3). I connected my Arduino UNO R3 to my computer for the first time after the Yosemite upgrade - it worked fine before this!

When I opened the Arduino IDE I selected Tools > Board > "Arduino UNO", but when I try to choose a Serial Port the only options are:

    /dev/tty.Bluetooth-Incoming-Port
    /dev/cu.Bluetooth-Incoming-Port
    /dev/tty.Bluetooth-Modem
    /dev/cu.Bluetooth-Modem

I have followed several tutorials and threads on how to 'fix' this issue, all to no avail:

I've installed the latest version of the FTDI drivers (even though, from what I recall the UNO doesn't even need them): FTDIUSBSerialDriver_v2_3.dmg

Downgraded to a prev. version of the FTDI driver hoping that would clear it up: /Volumes/FTDIUSBSerialDriver_v2_2_18

I followed a tutorial of how to remove the existing Apple drivers and removed the kext files, etc...

Tried connecting arduino to both USB ports.

Tried various cables, including the one that a I used before the Yosemite upgrade.

Tried installing updated Silabs drivers:
https://arduino.stackexchange.com/questions/3324/arduino-compatibles-serial-port-not-showing-mac-osx/3328#3328

Walked through the entire Arduino Mac OSX guide:
http://www.arduino.cc/en/guide/macOSX

After looking into the system info of my Macbook Pro, I can see the USB Controller is Broadcom based, in case that helps. I searched for Broadcom USB drivers but got hits for Silabs one instead.

Under my Tools > Port menu.. I can see these options:
![enter image description here][1]
clicking the Serial Ports option doesn't do anything.

Running `ls -1 /dev/tty.*` or `ls -l /dev/tty.usb*` from terminal gives me:

    /dev/tty.Bluetooth-Incoming-Port
    /dev/tty.Bluetooth-Modem

The Board does NOT show up under system networking (as it has for others), so it's not recognized as an incorrect device.

I'm at a complete loss. The board powers up... but I cannot connect to it.

SIDE NOTE: This is a legit Uno R3, not a clone.

  [1]: https://i.stack.imgur.com/MOvDD.png

title: Mac OSX Yosemite no serial ports showing for Uno R3

Answers: 11

body: This exact same thing happen to me on my mac running the same operating system. I had to restart this system a few times to get it to work. I restarted it with the arduino plugged in; and that worked rather than my previous attempts when i rebooted then plugged in.

body: The cable that shipped with my Arduino Uno worked for power but not data transmission so the /dev/tty.usbmodem was not showing up in the Tools --> Port menu. After I switched to a different cable, the /dev/tty.usbmodem port showed up and it worked beautifully.

body:
Yosemite 10.9 (and OS X 10.10 and newer) requires a signed USB driver kext (kernel extension).  You can find one on the FTDI web site here: http://www.ftdichip.com/Drivers/VCP.htm
Use version 2.3 for 64-bit OS X 10.9 or later.  Install and reboot.

Plug in your Arduino, and the Terminal command:

> /usr/sbin/kextstat | grep FTDI

will tell you if the FTDI VCP driver actually loaded.

Also a /dev/tty.usbserial-xxxxxxxx entry should appear in your /dev directory.

If not, the Mac USB port isn't talking to your Arduino.  So it's no use trying the Arduino IDE application.

Also make sure your USB cable isn't for power only, but fully connected.

body:
Stumbled across this. It worked for Mac OS X Yosemite 10.10.5

install the CH340 driver
Run the command in Terminal:
sudo nvram boot-args="kext-dev-mode=1"
Reboot

However, I installed:
MAC system：www.wch.cn/downfile/178

so YMMV

a user here:
http://forum.makeblock.cc/t/mac-os-x-yosemite-arduino-1-0-6-doesnt-recognize-makeblock-orion/728

found the solution, there:
http://forum.arduino.cc/index.php?topic=261375.15

so kudos - to all that sweated out the driver, uninstall, install, and activation...

Ted

body: In my case, there was some kind of incompatibility with the ESP8266 connected to the Nano board. As soon as I removed it the Serial Port appeared again.

body:
This site fixed the problem for me:

http://kiguino.moos.io/2014/12/31/how-to-use-arduino-nano-mini-pro-with-CH340G-on-mac-osx-yosemite.html

...somebody else has made an alternative to the ftdi drivers, and this website show you how to install them correctly.

body:
Probably, you have Chinese Uno analog which works on **CH340** USB-to-serial chip, so you need to install driver for it.

Steps to fix:

 1. Install the [CH340 driver](http://www.wch.cn/download/CH341SER_MAC_ZIP.html)
 2. Run the command in Terminal: `sudo nvram boot-args="kext-dev-mode=1"` (disable kext signing introduced in Mac OS X 10.9 Yosemite)
 3. Reboot

Also you're right [according to Uno and FDTI](https://www.arduino.cc/en/Main/ArduinoBoardUno):

> **Differences with other boards**
>
> The Uno differs from all preceding boards in that it **does not** use the FTDI USB-to-serial driver chip. Instead, it features the Atmega16U2 (Atmega8U2 up to version R2) programmed as a USB-to-serial converter.

body:
This fixed the problem for me:

http://blog.sengotta.net/signed-mac-os-driver-for-winchiphead-ch340-serial-bridge/

... and the [direct link](http://blog.sengotta.net/wp-content/uploads/2015/11/CH34x_Install.zip) to download.

**EDIT**: I have one of the cheap clones with a CH340 USB chip. So this might not solve *your* problem, but could be beneficial to others.

body:
Check this video [https://www.youtube.com/watch?v=0zuRukW7o0A][1]

- Reboot and press CMD+R immediately after reboot to enter in Recovery Mode
- Open Terminal from Recovery mode
- Run the command csrutil enable --without kext
- Reboot
- Install driver

  [1]: https://www.youtube.com/watch?v=0zuRukW7o0A

body:
First, check the USB cable - I had the same problem. If you have checked it, try the [HoodLoader2][1]:

I am using it and it works with Arduino Leonardo.

  [1]: https://github.com/NicoHood/Hoodloader2

body:
I have an osepp r3, seemingly an accurate clone. Computer is Mac os10.10.5.

A lot of sites claimed that the mac osx.* does not require FTDI drivers, but.....

After an awkward, google searching beginning, where the board only accepted a new sketch after being physically unplugged and replugged, I downloaded the latest FTDI driver, installed, and RESTARTED the mac. Now, joy and peace reigns. No side-effects with other mac functions, thankfully. Hope this helps.


body:
I'm working on a project that needs to use USB to pass serial messages between Arduinos (I can't use I2C or SPI for a few reasons – I especially need USB's support for hot-swapping and address allocation). So far I have the USB Host Shield set up on one Arduino Uno, connected to the standard USB port on another. It appears to be working, as can be seen when I run the board_qc:

<img src="https://i.stack.imgur.com/fALe7.png" width="300">

The 'slave' Arduino is just running the following code:

    void loop() {
      Serial.println("Hello");
      delay(1000);
    }

On the master, I create a USB object from the USB Host library (https://github.com/felis/USB_Host_Shield_2.0).

    USB Usb;

    void setup() {
        Serial.begin(115200);
        Usb.Init();
    }

    void loop() {
        if (Usb.getUsbTaskState() == USB_STATE_RUNNING)
        {
            Usb.ForEachUsbDevice(&PrintAllData);
        }
    }

    void PrintAllData(UsbDevice *pdev)
    {
        UsbDeviceAddress adr;
        adr.devAddress = pdev->address.devAddress;
        Serial.println(adr.devAddress, HEX);

        uint8_t msg = 0;
        uint16_t len = 0;
        uint8_t rcode = Usb.inTransfer(adr.devAddress, pdev->epinfo->epAddr, &len, msg);

        if (rcode && rcode != hrNAK) {
         Serial.print(F("\r\nData rcv: "));
         Serial.print(rcode, HEX);
       } else if (len > 0) {
         Serial.print(F("\r\nData Packet: "));
         Serial.print(msg[0]);
       }
    }

I'm not getting any data through though. Does anyone have any suggestions? Or know of any helpful sample code?

title: Communication between Arduinos using USB Host Shield

Answers: 1

body:
Have you tried this lib's documentation? It looks like just doing `init()` and then checking the task state is not enough.

Looking [at the source code][1] makes me think you might want to add a call to the main task/state machine, e.g. add a call to `Usb.Task();` to your loop, before your `if` statement.

  [1]: https://github.com/felis/USB_Host_Shield_2.0/blob/master/Usb.cpp


body:
I'm having trouble figuring this out. I'm using this popular shield: https://www.sparkfun.com/products/12761

There is a breadboard area in the middle of the shield. But what confuses me is the lack of lines (order). On normal breadboards you can tell which row would be at the same voltage. If I wanted to put something on this prototyping area, how would I connect it? For example an LED, which would have a resistor attached to the positive side going to 5V and the negative side going to ground?

title: How do I use the prototyping area on a SparkFun MicroSD Card shield?

Answers: 1

body: This type of board, "pad per hole", has no pre-made interconnects. If you use thin enough wire sometimes you can push two pieces of wire into the same hole before you solder, say a resistor lead and another wire to connect to the next component. You can also solder an interconnect wire to the protruding leg of a DIP chip. You can make a buss for ground or 5v by assigning a whole row for that purpose, on the top side wire everything that needs to connect to that buss, and on the bottom side solder a straight piece of bare wire to all those wire ends in that row.


body:
I have an old RC helicopter controller, but not the helicopter.  I recently purchased an Arduino Uno and would like to do something with LEDs(beside the on-board one built-in). Can I use an LED from the controller, that is already soldered in, cut it free and plug into my breadboard.

*Side Note*

   I have no experience in soldering and don't own a soldering iron.

title: Reusing LED from RC helicopter controller

Answers: 3

body: Yes, you can. For convenience, cut a bit shorter the lead on the side of the package where the flat part is so that you can identify the leads easier.

body:
Yes you can. Make sure you have a resistor in series with your led. It is much, much better to guess and use the wrong resistor, than not to put a resistor in at all. I use http://led.linear1.org/1led.wiz to calculate my resistor. Your source voltage will be 5v. Each thing you have to fill has help on what value you're likely to want to put here.

It doesn't matter which side of the led you put the resistor.

If you can cut the led out, it should be fine, so long as you have long enough legs to go into the breadboard.

body:
Ignacio's drawing shows you how to connect a LED. If you don't have any soldering tools you can use a **solderless breadboard**. [This small one](https://www.adafruit.com/products/65) from Adafruit is ideal for small circuits:

![enter image description here][1]

(They exist in all sizes from very small to very large). The holes in each 5-hole row are all internally connected.

The problem with cutting the LED from the board may be that the remaining wire length is too short to fit in the breadboard. (You'll need at least something like 6 mm.) LEDs are a nice way to start with electronics, since you need minimal part count to make something visible. If you can't cannibalize the LED from the controller, just buy one from your local electronics shop. They're dirt cheap.

  [1]: https://i.stack.imgur.com/Cdd2f.jpg


body:
I am building a door lock that we will use at a local MakerSpace-club in my city, and we had this idea about building a fingerprint lock with parts compatible with Arduino.

What we are aiming to do is create a database that holds all our customers and their associated information. Fingerprint data being one of them.

So my question is: Is it possible to have a fingerprint sensor **store and compare fingerprint data** with an **external source** such as a **MySQL database**, instead of using the on-board memory?

So basically: When a customer puts his finger on the sensor, the Arduino board grabs the fingerprint data and queries our database for a match through its WiFi shield. If match is found: Log entry and unlock the door.

*Google is not helping me out here.*

title: Fingerprint sensor with external memory source

Answers: 1

body:
Yes, all you need is a computer or another device that grabs the data via wifi and store it in a database.

You can simply send requests from arduino to computer and the PC does the search and returns the info back.

If you use XBees for communication, just install some serial communication with your preferred language and start sending and receiving data. The database will be accessed through that high level program and data will flow via XBees.


body: I'm making a project with MQTT Arduino, but on publish messages i read that it's not possible to publish with qos 1 and 2? It is true? If is not, how can i put qos on publish messages?

title: MQTT Arduino add quality of service

Answers: 1

body:
What MQTT client are you using?

Paraphrased from the [MQTT spec][1]  http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718099

> The MQTT protocol provides three qualities of service for delivering
> messages between clients and servers: "at most once", QOS0; "at least
> once" QOS1; and "exactly once" QOS2. For QOS 1&2: The message must be
> stored locally at the publisher, until the publisher receives
> confirmation that the message has been delivered to the receiver.
> However, for QOS0 there is no storage requirement.

The problem with the Arduino is that there is no large quantity of storage available. If the client is disconnected from the broker while using a QOS of 1 or 2 the client must store the messages until a connection is reestablished and the message transfers are acknowledged. On an Arduino there is no guarantee all the messages can be saved. Consider a sensor node collecting 16-bits (int value) every second. Then supposed the broker goes down over the weekend and a repair person isn’t paid to work on the weekend. That’s two days’ worth of data or 172800 readings or about 1/3 MB (without overhead). The Arduino does not have that much storage.

  [1]: http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718099 "MQTT spec"


body:
The title pretty much says it all:

What would be the most obvious way to setup the Arduino (shields?), the Sketch (libraries?) and PC (webserver, ajax, plain html?) so that I get the following system working:

 1. I open some page in a browser. The page has some labels/fields/values;
 2. I power up Arduino, which is connected to some sensors (or even potentiometers);
 3. The sensor values display keep being constantly updated in the page, with a sensible refresh rate (the fastest as possible, as to control some browser-based game for example);

The fundamental idea here is to use the Browser, and not some other GUI toolkit, or Processing, or the command line.

title: Using Browser window to display sensor values in realtime

Answers: 3

body:
Your question actually exists out of multiple questions...

 **1. How to connect arduino to network/internet.**

I would suggest using a [cheap WIFI module][1] or [Ethernet module][2]

 **2. How to send values from arduino over ethernet.**

The fastest would be using a direct connection (TCP/IP or UDP?)

 **3. How to receive values from arduino over ethernet on a PC.**

The problem with this would (I think) be that a webserver usually does not enable a direct TCP/IP connection, but instead would use HTML to transfer data/webpages. But I'm not a web-developer at all. I would create a dedicated program in processing/c++/python or something similiar.

  [1]: https://www.sparkfun.com/products/13252
  [2]: http://www.mouser.com/ProductDetail/WIZnet/WIZ550io/?qs=sGAEpiMZZMs64UhKbFbsce4VNQuqbcmAbUaU//iSHPWsh1gbPl3iTA==

body:
The most obvious way? Not what is the best way? It is a subjective question. The most obvious way would be to do it in a way you know how to. I am sure there are at least 20 ways to do this.

The way I know, and that I would do it is write a PC service that establishes serial communications with the Arduino, transfers data using JSON, and presents a web server I could connect TCP to.  Knowing C# and using existing code I have, it would take less than 15 minutes.

body:
I guess there are a number of ways to tackle the problem. Using the Ethernet shield is probably the most intuitive option, but this isn't something I have explored in too much detail - I would usually opt for other micros at this stage and I am confident you will get an answer from someone else detailing this.

To get the most out of the Arduino and leverage what the Arduino is good at, I would probably make a C# console application or Windows service which communicates with the Arduino over serial, and use the 'System.Web.Http.SelfHost' assembly to make the data available through a RESTful web service which a html page could use [JQuery][1] to poll for information. It would be pretty easy to extend this to push the data to the page using [SignalR][2].

The fundamental drawback of this architecture is that your device isn't serving the website, so these must be hosted somewhere else, or run from flat files. Also a PC must be attached to facilitate the data transfer over serial and provide the web service.

To get started you will want to familiarise yourself with c# and the SelfHost module, and WebApi 2.0 if you aren't already, this is all covered [here][3], and of course you will need [Visual Studio Community][4] edition or greater to start creating projects.

Next, write a [Windows Service][5] or [Console Application][6] which implements an object model holding your data, and updates this periodically with the [Arduino via serial][7].

The Self Host module is pretty incredible in that it allows you to add a web interface to any .Net application very easily, and directly manipulate your model. The tutorial linked above is very easy to follow, and can easily be adapted.

For testing and development purposes, I would highly recommend [Postman][8], which can be used to test and trigger your API endpoints. It's a comprehensive and well polished tool specifically for this job.

In terms of the network logistics, I would then use JQuery to make periodic posts to the self-host service in the same fashion that Postman would. You can use the function call backs to trigger successive queries on completion to maximise the data refresh rate without causing excessive consumption. A time interval would be another option you could consider between requests, and is discussed in [this][9] article on polling.

The typical Ajax request structure would look something like this:

    $.ajax({
        url: 'yourApiMethodAddress',
        type: 'get',
        error: function (jqXHR, status, ex) {
            /* Something went wrong. Maybe you could stop
               the update process and show a message and
               a retry button. */
            console.log("Error: " + status);
            console.log(ex);
        },
    }).done(function (data) {
        // Update page with information stored in 'data'. View console for hints
        console.log(data);
    });

I would recommend using [Twitter Bootstrap][10] in your webpage file to pretty things up and maintain readability. Don't forget to include the javascript and css files for both Bootstrap and JQuery in your html document (if used).

In summary, I would recommend implementing an application which runs on a computer attached via USB/Serial to the Arduino, with the .Net Self Host module utilised to provide a RESTful API. This API can then be polled from a html page using javascript and JQuery to obtain the information and update the page.

I hope this information helps, and as there a lot of moving parts I didn't provide many code examples for simplicity sake. If you find this useful and would like more information adding, mention it in the comments and I will update my answer.

  [1]: https://jquery.com/
  [2]: http://signalr.net/
  [3]: http://www.asp.net/web-api/overview/older-versions/self-host-a-web-api
  [4]: https://www.visualstudio.com/en-us/products/visual-studio-community-vs.aspx
  [5]: https://msdn.microsoft.com/en-us/library/zt39148a(v=vs.110).aspx
  [6]: https://msdn.microsoft.com/en-us/library/0wc2kk78(v=vs.90).aspx
  [7]: http://playground.arduino.cc/Interfacing/Csharp
  [8]: https://www.getpostman.com/
  [9]: http://techoctave.com/c7/posts/60-simple-long-polling-example-with-javascript-and-jquery
  [10]: http://getbootstrap.com/


body:
Im using Spark fun pro micro:https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide/hardware-overview-pro-micro

I am controlling a servo motor which reads its data from a pot connected to A0, and then writes to the servo on D9.

A speaker is connected to A5. Im using tone()

If I comment out the servo part of it, the tone() works out just fine and vise versa..
The error message I get is "multiple definition of `__vector_32'"

Got a clue??!
Thanks!

title: Running a servo and tone() won't compile? "multiple definition of `__vector_32'"?

Answers: 3

body:
The libraries are not compatible with each other, welcome to Arduino.

I dont use either library, and usually avoid libraries altogether because of things like this. I will assume you want a solution, not a clue.

The quickest route is to pick one of the libraries, and globally modify __vector_32 to something like __vector_32x.

That probably is not the best solution but the quickest. The best solution would be to understand how it is used in both libraries, and modify them to work together. In the end it might be as simple as wrapping it with some #ifdef, but that requires understanding it enough to get to that conclusion, and it will take some time.  Maybe someone else already has.

body:
The problem you're seeing arises when two codes (e.g. libraries) try to use the same interrupt.

If you look at the source code of the two libraries, you'll find that they both make use of a number of ISRs (interrupt service routines): `Tone.cpp` uses

    ISR(TIMERn_COMPA_vect) {...}

for n = 0..5, while `Servo.cpp` uses

    ISR(TIMERn_COMPA_vect) {...}

for n = 1, 3, 4, 5.

Now what happens when you compile this code is that they both libraries generate identical symbols (the `__vector_32` part) which then clash when the compiled code is linked to give the final binary you'd upload to your Arduino.

There is no simple way around this because the interrupt handlers need to be  registered at certain fixed positions in flash memory and there can only be exactly one interrupt handler for each of these slots (these slots are simply entries in a look-up table with the addresses of the interrupt handlers in flash, cf. Table 9-1 in the [datasheet][1]).

Now to solve this problem you would need to find a way to either merge the interrupt handlers of the two libraries (not so easy I guess), or make them use different interrupts (without looking further into what options the pro micro offers, the code suggests that there are several TIMER interrupts which could be assigned one to the Servo, one to the Tone, *if* that is supported by the hardware).

In any case you'll not get around modifying the libraries (or writing your own code for one functionality or the other).

  [1]: http://www.atmel.com/Images/Atmel-7766-8-bit-AVR-ATmega16U4-32U4_Datasheet.pdf

body:
The link you provided shows a board built around the ATmega32U4.
On this chip, “\_\_vector\_32” is the low-level name of an ISR
(Interrupt Service Routine) named “TIMER3\_COMPA\_vect”. Your problem
comes from having two libraries trying to define an ISR for the same
interrupt, which is generated by the timer 3 of the chip. Merging
the ISRs is actually unlikely to work, because since each library
configures the timer in its own way, the timing of the interrupts will
be wrong for at least one of the libraries. You really have to use
different timers.

On my copy of Tone.cpp I can read:

<!-- language-all: lang-c++ -->

    #elif defined(__AVR_ATmega32U4__)

    #define AVAILABLE_TONE_PINS 1
    #define USE_TIMER3

    const uint8_t PROGMEM tone_pin_to_timer_PGM[] = { 3 /*, 1 */ };
    static uint8_t tone_pins[AVAILABLE_TONE_PINS] = { 255 /*, 255 */ };

which shows that the code is configured to use timer 3 on this
particular chip. In Servo.h I have:

    #elif defined(__AVR_ATmega32U4__)
    #define _useTimer1
    typedef enum { _timer1, _Nbr_16timers } timer16_Sequence_t ;

which shows it should use timer 1, and not conflict with Tone.cpp.

It seems we have different versions of Servo.h. Mine is from Arduino
1.0.5. You may try to fix the problem by modifying the relevant section
of either file (just after `#elif defined(__AVR_ATmega32U4__)`) and
have them use different timers.

**Edit**: It appears this issue has already been fixed... on June 2012!
See this diff: [Avoid TIMER3 conflict with Servo and
tone()](https://github.com/arduino/Arduino/commit/f60f17f79ae383a948a9cc4baa8bd0983fad6465)
on the Arduino GitHub repository. The simplest fix in your case may be
to just upgrade your Arduino software. You could also manually apply
that (really small) diff to your current copy.


body:
Anyways cutting to the chase I am pretty good at C++ as I have been doing it for over 6 months pretty much 1-2 hours each day and I am looking for cool things to use my knowledge on ,I have heard of the Arduino's but the problem is I don't know my arse from my elbow when it comes to electrical engineering and all that so I have a couple of questions.
1. Do I need to have a background in engineering to use an Arduino.
2. Is there any cheap alternatives to the quite costly starter kit.

title: Arduino Uno questions

Answers: 5

body:
1) You do not have to have engineering background. You only need to know basics such as what a resistor is, what a transistor is, how an led works etc. (Of course the answer depends on what you want to do. For instance, if you want to work on a robotic project then yes, you need a little knowledge.)

2) Shopping questions are not answered here, but since you are asking something about "cost" then I have two answers. You can find cheaper solutions, but I, personally, always support original products for two reasons. First, you need to support the people who serves your work. Second is that original products are generally more reliable.

body: First question, no. Tons of tutorials for a from scratch beginner online. Second question, Google Arduino clones.

body:
If you are the "hacker" type (i.e. you are good at self-learning and you like to explore things) even if you are an absolute newbie I advice *against* those starter kits. They usually contain lots of overpriced parts, which you can get much more cheaply ordering directly to digikey, mouser or the like for your country (or maybe at your local shop).

On the other hand I strongly recommend buying an original Arduino board (for beginners an [Arduino UNO](http://www.arduino.cc/en/Main/ArduinoBoardUno) is optimal, IMO, and comes at a reasonable price around 20-25EUR). This because the quality is guaranteed and you risk less problems. There are really good clones out there, but also tons of crappy ones, so I'll leave them to when you get more experience. Nothing is more frustrating while learning that wasting hours to debug a supposedly idiotproof project only to discover that *it was not your fault*, but the board's!!!

Note: if you go for an Arduino UNO choose the version with a socketed plastic DIP package MCU (that big, long chip with two parallel rows of pins), instead of the SMT version, using an MCU packaged as a tiny plastic square. The version with the socket may come handy if you accidentally fry the MCU: a new one will cost you less than 4EUR and it's easily replaceable (it is not soldered on the board). The SMT, on the other hand, is a PITA to replace and you'd need special hardware to do that. Moreover, the socketed version can be used as a "poor man's" programmer for ATMega328 MCUs. You program it on the board and then place it on an external circuit.

If you are an absolute beginner at EE, you can find lots of beginner tutorials on the Internet. Concentrate on key basic aspects. Most electronic projects can be handled with less math than you expect. You absolutely need to know Kirchhoff's laws and Ohm's law and a couple of related formulas if you want to begin *learning* electronics, but nothing more fancy. The rest can be learned on the way. Keep in mind that there are people out there that know much less than that and that are able to put together an electronics project successfully only by following "instructables" found on the Internet (really hardcore tinkerers! :-)

BTW, one thing you may find interesting, given your C++ background, is that what they call the "Arduino language" is really true C++! The Arduino environment ["enhances" the source program](http://www.arduino.cc/en/Hacking/BuildProcess) (the "sketch", as they call it) and inserts all the boilerplate code needed to configure the MCU and other low-level stuff a beginner would have hard time digesting. Then the source program so enhanced is fed to AVR-GCC, in its G++ incarnation, which is nothing more that GNU GCC configured as cross-compiler for AVR MCUs. You can even use templates and derived classes, if you dare :-) Of course they don't tell you, otherwise the poor Arduino beginner would be scared away :-D

Very advanced Arduino users can bypass the Arduino environment completely and write directly C++ code and use the board as a simple prototyping board for the MCU it is based upon (ATMega328P for the Arduino UNO), exploiting all the features of the MCU without all the abstraction layers which comprises the Arduino environment.

A note of caution: when I talk about C++ I mean what is technically known as a ***freestanding C++ implementation***, as opposed to a ***hosted implementation*** like on PC's. This means that the implementation doesn't need an OS to work, but also that it doesn't have all the standard libraries that you expect to find on a hosted implementation (sorry, no std::vector<string> or std::cout !!!). A freestanding implementation must only provide a very limited subset of the usual standard libraries (those that handle lower level stuff, like memory allocation), and normally relies on implementation-specific libraries to do other stuff. In particular with the Arduino environment and the underlying AVR-GCC comes the [AVR-LIBC library](http://www.nongnu.org/avr-libc/). But this is needed only when you do advanced stuff. The basic [Arduino library](http://www.arduino.cc/en/Reference/HomePage) will keep you busy for a nice amount of time until you reach such a level of expertise.

body:
> I don't know my arse from my elbow when it comes to electrical engineering and all that so I have a couple of questions. 1. Do I need to have a background in engineering to use an Arduino.

The answer to your first question: it depends on what you want to achieve, and how much time you are willing to spend stuck.

A bit of electrical/electronic background can help you a lot.  Basics such as Ohm's, Kirchhoff's.  Semiconductor devices (diodes, transistors, OpAmps).  It's very useful to understand what kinds of test&measurement equipment exists and how it can be used.

You can pursue C++ for 6 months 1-2 hours a day.  You can pursue electrical knowledge in the same way as well.  A solid book like "The Art of Electronics" will help you a lot (doesn't have to be the latest edition).

Then you can pursue more exciting things: sensors (for example).

body:
I am having loads of fun with Arduino from a background of programming with no electronics experience.  From simple "flash some LEDs" in the early days (back in Feb) through to making my own "games console" using a 32x32 LED matrix, FRAM memory chip, piezo buzzer and a home made controller for input.  I found that once I got started and browed various relevant sites, ideas started to flow.

I would suggest using straight C rather than C++, especially if you are working on one of the particularly low memory devices (such as the Uno).  I ran out of working RAM more times than I care to remember.

As for starter kits, if you search, you should be able to find cheap kits.  I got a pretty decent starter kit for around £20 but there were cheaper ones with a few less components.  Mine included (amongst other things) 30 LEDs, various IR and flame sensors, photo resistors, a 7 segment LED, a 4 digit 7 segment LED, an 8x8 LED matrix, a servo, a stepper motor, a stepper motor control board, a couple of breadboards and an Arduino Uno.


body:
I have 2 arduinos I made some code and I managed to send from the first to the second and from the second to the first with two different pairs of code. What I want to do is to send from the first to the second and from the second to the first with no code change. I added in my current code some monitoring commands but what I can see in my Serial monitor is that not all characters are passed thru. I attach something like my code below only more simplified because it is a big project.

1st arduino:

    radio.stopListening();
      for(int i=0; i<lnth; i++){
          chartosend=data.charAt(i);
          radio.write( &chartosend, sizeof(chartosend) );
      }
      radio.write(&endchar,1);
    radio.startListening();
      if(radio.available()){
        radio.read( &inchar, sizeof(inchar) );
        inradio+=inchar;
        //Serial.println(inchar);
      }

  2nd Arduino:

    radio.startListening();
      if(radio.available()){
        radio.read( &data, sizeof(data) );
        inradio+=data;
      }
    radio.stopListening();
      if(analogRead(0)>20){
         for(int i=0; i<6; i++){
          chartosend=pir1.charAt(i);
          radio.write( &chartosend, sizeof(chartosend) );
        }
        radio.write( &endchar, sizeof(endchar) );
      }
Where is the problem and how I could solve this?

title: Cannot receive and transmit at the same time

Answers: 1

body:
I dunno know about the radio interface you are using. But I can see something which will break your code for sure.

The sections, where you read data from the interface on both Arduinos are passed without a delay, interrupt, polling loop or something else.

Which means: your "read" code section is in no way synchronised with the write code section on the other arduino and vice versa. At the point when you call the function "radio.available()" (which probably tests if there's any data available at the receiver fifo) there is possibly one or any number of bytes available, but not necessary the whole transmission from the other arduino. You have to make sure — somehow — that the transmission is finished, before you can call it a day and go on with processing the received data.

To do this you have to

 1. synchronise the beginning and the end of your transmissions on both Arduinos
 2. poll the data on the respective receiver side, until you are satisfied
 3. or run into a timeout you have to apply in case there's a byte or more lost by chance.

I hope this gives you a little bit of orientation where to start.


body:
    void setup() {
      pinMode(13, OUTPUT);  // Red
      pinMode(14, OUTPUT);  // Yellow
      pinMode(15, OUTPUT);  // Green
    }

    void loop() {
      digitalWrite(13, HIGH);
      digitalWrite(14, LOW);
      digitalWrite(15, LOW);  // Stop
      delay(20000);           // Wait 20 seconds
      digitalWrite(13, HIGH);
      digitalWrite(14, HIGH);
      digitalWrite(15, LOW);  // Listen
      delay(20000);           // Wait 20 seconds
      digitalWrite(13, LOW);
      digitalWrite(14, LOW);
      digitalWrite(15, HIGH);  // Go
      delay(20000);            // Wait 20 seconds
    }

How good is this code and is there any error ?

title: Verify a code for Traffic Signal

Answers: 3

body:
I have a similar requirement, this gives you a little more flexibility , My traffic light code is controlled by a PIR outside my door , if the PIR detects an individual the lights turn to stop when the PIR clears the lights turn to green.

the code and hardware are still in the test phase.

#include <EasyTransfer.h>

int D_Status_Word = 0;
int Status_Word = 0; //sets all bits to  zero
int Light_Threshold = 150; //the light level that constitutes an unusual entry
int Active = 0;
int Passive = 100;
int Counter = 100;
int Green_Pin = 7;
int Amber_Pin = 8;
int Red_Pin = 9;
int Photocell_Pin = 1;     // the cell and 10K pulldown are connected to a0
int Photocell_Reading;
int Sensor_Frequency = 0;

struct SEND_DATA_STRUCTURE {
  //put your variable definitions here for the data you want to receive
  //THIS MUST BE EXACTLY THE SAME ON THE OTHER ARDUINO
  int Out_Word;
  int LDR_Level;
};

SEND_DATA_STRUCTURE My_Tx_Data;

//create an object for themessage
EasyTransfer ETout;
int D_Sensor_Pin [] = {
  2, 3, 5, 6
};
// pin hallwaypir, 3 doorpir, 5 door sensor, 6 hallpir

void setup() {
  Serial.begin (9600);
  // put your setup code here, to run once:
  ETout.begin(details(My_Tx_Data), &Serial);
  for (int i = 0; i <= 3; i++)// read the two state sensors
  {
    pinMode(D_Sensor_Pin [i], INPUT);
  }
  pinMode(A1, INPUT);//set the analoge u ldr pin ot input mode
  pinMode (Green_Pin, OUTPUT);
  pinMode (Amber_Pin , OUTPUT);
  pinMode (Red_Pin , OUTPUT);
}

void loop() {
  Scan_Sensors();
  if (D_Status_Word != Status_Word)
  {
    Sensor_Frequency = Active; // high frequency sampling because a sensor has activated
    //send a data packet to the mega with mem card via serial.
    Send_Data_Packet();
  }
  if (bitRead (Status_Word, 1) != bitRead (D_Status_Word, 1))
  {
    if ((D_Status_Word, 1) == 1)
    {
      Traffic_Light_Stop();
    }
    else
    {
      Traffic_Light_Go();
    }
  }
  Status_Word = D_Status_Word;

  delay(Sensor_Frequency);// 1000= waits for a second
}

void Scan_Sensors()
{
  byte readings = 0;
  Photocell_Reading  = 0;
  for (int i = 0; i <= 3; i++)// read the two state sensors
  {
    bitWrite(readings, i, digitalRead(D_Sensor_Pin [i] ));
  }
  //test to see if any sensors have trivggered (readings>0)
  if (readings > 0)
  { // a 2 state sensor has triggered, reset the Counter to 100
    Counter = 100;
  }

  //read threshold sensors
  Photocell_Reading  = analogRead(Photocell_Pin);
  {
    bitSet(readings, 4); // 4 becaus there are 4 2 state sensors (0 to 3)
    //we write 1 because thelight is below the threshold
    Serial.print ("photocell Reading = ");
    Serial.println(Photocell_Reading);
  }
  D_Status_Word = readings;
  Counter -= 1; //decrement the Counter
  if (Counter <= 0)
  { //the Counter has counted 100 scans since a 2state has triggered
    //rest freqenvcy to Passive
    Sensor_Frequency = Passive;

  }
}
void Send_Data_Packet()
{
  My_Tx_Data.Out_Word = D_Status_Word;
  My_Tx_Data.LDR_Level = Photocell_Reading;
  Serial.print ("photocell Reading = ");
  Serial.println(Photocell_Reading);
  Serial.print ("status word = ");
  Serial.println(D_Status_Word);
  ETout.sendData();
}

void Traffic_Light_Stop()
{
  //lights turn from green to yellow to red
  digitalWrite (Green_Pin, LOW);
  digitalWrite (Amber_Pin, HIGH);
  digitalWrite (Red_Pin, LOW);
  delay(750);
  digitalWrite (Green_Pin, LOW);
  digitalWrite (Amber_Pin, LOW);
  digitalWrite (Red_Pin, HIGH);
}

void Traffic_Light_Go()
{
  //lights turn red to red and yellow to green
  digitalWrite (Green_Pin, LOW);
  digitalWrite (Amber_Pin, HIGH);
  digitalWrite (Red_Pin, HIGH);
  delay(750);
  digitalWrite (Green_Pin, HIGH);
  digitalWrite (Amber_Pin, LOW);
  digitalWrite (Red_Pin, LOW);

}

body:
There is nothing wrong with your code. But it could use some cleaning to make it efficient.

The code at the moment will be 'deaf' to any user inputs for twenty seconds between light changes.

This can be fixed by using a timer interrupt and changing the lights every 20 seconds and listen for other inputs or do other things. You can use the [arduino timer library][1], this is well documented and you should be able to find examples of its use. Basically you would monitor a variable until it reaches a point and then trigger the lights.

The other option would be to use the `millis()` and every 20 seconds change a light, but do stuff between those 20s. This can be done like this:

    unsigned long previousMillis;  //hold the previous time
    unsigned long currentMillis;   // hold the current time

    long threshold = 20000;
    int count = 0;

    int pins[] = {13, 14, 15};

    //setup code stuff

    //put the following at the top of loop()

    currentMillis = millis();

    if(currentMillis - previousMillis > threshold){

     previousMillis = currentMillis;

     for(int i = 0; i < 3; i++){
     digitalWrite(pins[i], LOW);  //turn off all

        }

     if(count > 2) count = 0;

     digitalWrite(pins[count], HIGH);

     count++;
    }

  [1]: http://playground.arduino.cc/Code/Timer1

body:
There is nothing wrong with the code that I can see although you do have some redundant statements:
When you go to "Listen" you set the red and green pins high and low respectively, but they are already high and low from the previous state.  Not a big issue, being verbose adds clarity so there is some argument for leaving it as is.

I would consider using #define macros to number the ports and set the delay times.  This adds readability and also means you can make changes easily without having to search through the code and match up appropriate instances of the port number that you want to change, for example:

    #define RED_PIN 13
    #define DELAY_BETWEEN_CHANGES 20000
    ...
    digitalWrite(RED_PIN, HIGH);
    delay(DELAY_BETWEEN_CHANGES);

This also means that you can get rid of comments in your code as it becomes pretty self explanatory.  I personally believe that comments are bad.  If you write code and put a comment explaining what it does, when you have to modify the code you also have to modify the comment.  Make the code understandable in the first place, no need for comments.

Final point (not related to code): What happens after "Go"?  I'm from the UK so we have another phase after Go.  It reminds me of an old driving test joke:
Instructor: What is the sequence of traffic lights?
Student: Red, red and amber, green.
Instructor: What comes after green?
Student: How would I know?  I've always gone by then!


body:
I am using this real-time-clock module to keep track of the time for a project:
http://www.dfrobot.com/wiki/index.php/Real_Time_Clock_Module_(DS1307)_V1.1_(SKU:DFR0151)

I have hooked up the respective pins correctly to the Arduino.

Below is the code I'm using. This first one is the code used to set the time on the module. It writes the initial time you specify to the RTC module.

    #include "Wire.h"
    #define DS1307_ADDRESS 0x68
    byte zero = 0x00;         //workaround for issue #527

    void setup(){
      Wire.begin();
      Serial.begin(9600);
      setDateTime();         //MUST CONFIGURE IN FUNCTION
    }

    void loop(){
      printDate();
      delay(1000);
    }

    void setDateTime(){          //Set the time to a minute or two ahead. After upload has completed, simply press the reset button to start the time while watching another clock.
      byte second = 0;     //0-59
      byte minute = 56;     //0-59
      byte hour = 13;     //0-23
      byte monthDay = 26;     //1-31
      byte month = 5;     //1-12
      byte year = 15;     //0-99
      Wire.beginTransmission(DS1307_ADDRESS);
      Wire.write(zero);     //stop Oscillator
      Wire.write(decToBcd(second));
      Wire.write(decToBcd(minute));
      Wire.write(decToBcd(hour));
      Wire.write(decToBcd(monthDay));
      Wire.write(decToBcd(month));
      Wire.write(decToBcd(year));
      Wire.write(zero);       //start
      Wire.endTransmission();
    }

    byte decToBcd(byte val){
    return ((val/10*16)+(val));        //Convert normal decimal numbers to binary coded decimal
    }

    byte bcdToDec(byte val)  {
      return ((val/16*10)+(val));        //Convert binary coded decimal to normal decimal numbers
    }

    void printDate(){
      Wire.beginTransmission(DS1307_ADDRESS);        // Reset the register pointer
      Wire.write(zero);
      Wire.endTransmission();
      Wire.requestFrom(DS1307_ADDRESS, 7);
      int second = bcdToDec(Wire.read());
      int minute = bcdToDec(Wire.read());
      int hour = bcdToDec(Wire.read() & 0b111111);     //24 hour time
      int monthDay = bcdToDec(Wire.read());
      int month = bcdToDec(Wire.read());
      int year = bcdToDec(Wire.read());
      Serial.print(month);        //print the date, EG: 3/1/11 23:59:59
      Serial.print("/");
      Serial.print(monthDay);
      Serial.print("/");
      Serial.print(year);
      Serial.print(" ");
      Serial.print(hour);
      Serial.print(":");
      Serial.print(minute);
      Serial.print(":");
      Serial.println(second);
    }

    //http://projectsfromtech.blogspot.com/2013/06/arduino-rtc-tinyrtc-v1-with-arduino.html

And this next block reads the time from the RTC module. It has an onboard battery, so it keeps time even when disconnected from the Arduino.

    #include "Wire.h"
    #define DS1307_ADDRESS 0x68

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

    void loop(){
      printDate();
      delay(1000);
    }

    byte bcdToDec(byte val){
      return ((val/16*10)+(val));          //Convert binary coded decimal to normal decimal numbers
    }

    void printDate(){
      Wire.beginTransmission(DS1307_ADDRESS);          // Reset the register pointer
      byte zero = 0x00;
      Wire.write(zero);
      Wire.endTransmission();
      Wire.requestFrom(DS1307_ADDRESS, 7);
      int second = bcdToDec(Wire.read());
      int minute = bcdToDec(Wire.read());
      int hour = bcdToDec(Wire.read() & 0b111111);     //24 hour time
      int monthDay = bcdToDec(Wire.read());
      int month = bcdToDec(Wire.read());
      int year = bcdToDec(Wire.read());
      Serial.print(month);          //print the date, EG: 3/1/11 23:59:59
      Serial.print("/");
      Serial.print(monthDay);
      Serial.print("/");
      Serial.print("20");
      Serial.print(year);
      Serial.print(" ");
      Serial.print(hour);
      Serial.print(":");
      Serial.print(minute);
      Serial.print(":");
      Serial.println(second);
    }

    //http://projectsfromtech.blogspot.com/2013/06/arduino-rtc-tinyrtc-v1-with-arduino.html

The weird thing is, when I open the serial monitor after I upload the getTime sketch (the second one), every thing works except that the dayOfMonth only shows the last digit. For example, if the day was the 23rd, it would only print 3. Or if it was 31, it prints 1. I've gone through the code, but can't find anything that I think would cause this. Any tips?

To get started, I followed this tutorial: http://projectsfromtech.blogspot.com/2013/06/arduino-rtc-tinyrtc-v1-with-arduino.html

title: Cannot print the first number of the date with RTC module

Answers: 1

body:
You forgot

<!-- language-all: lang-c++ -->

    int weekDay = bcdToDec(Wire.read()); //0-6 -> Sunday - Saturday

just before reading `monthDay`. Even though you may not be interested in
this piece of data, the RTC chip has no way of knowing that, and it will
always send the date and time in the same format. You can replace that
line by

    Wire.read(); // discard day of week

if you want to make clear that you are discarding this information.

Ah, BTW, `decToBcd()` and `bcdToDec()` are ill-named: they convert
between BCD and _binary_, not _decimal_.


body:
I'm making USART support for SAM3x8e based Arduino Due board.
I looked into arduino source code, exactly

    arduino-1.5.7/hardware/arduino/sam/variants/arduino_due_x/variant.cpp

and see that for Serial0 UART component is used, for Serial1 USART0 is used, for Serial2 - USART1 and for Serail3 - USART3. The USART2 is not even mentioned.

1. Why is this done that way?
2. I would like to realize what those comonents (USARTx & UART) are? Is UART is the subset of one of USARTs?
3. What is relation between USARTn & UART components and arduino board's TXn/RXn pins? Exactly, what pins are those component mapped to?

Thanx.

title: Adrudio Due: How do MCU components USARTx & UART relate to board pins TXn/RXn?

Answers: 0


body: I am trying to make a mini project with attiny84 and I searched the web so I can make an arduino on breadboard. What I saw on the internet is that they didnt use crystal. Is it mandatory if I want to use 1 pwm pin and the SPI interface on the attiny84?

title: Is crystal mandatory on attiny84?

Answers: 1

body: Only if you need crystal accuracy. If the internal RC oscillator is accurate enough then feel free to use it instead.


body:
My Due is interfaces with a DAC which I need to update with freq 1MHz. The nice solution seems to be a timer interrupt. I found a thread here called "Arduino Due - creating an 8Mhz clock signal". I tried the following code to see if I can get 4MHz on P41. No luck. Any help will be greatly appreciated. Thanks.

    volatile boolean l = false;

    void TC6_Handler()
    {
     TC_GetStatus(TC2, 0);
     digitalWrite(41, l = !l);
    }

    void startTimer(Tc *tc, uint32_t channel, IRQn_Type irq) {
     pmc_set_writeprotect(false);
     pmc_enable_periph_clk((uint32_t)irq);

     TC_Configure(tc, channel,
     TC_CMR_WAVE |
     TC_CMR_WAVSEL_UP_RC |
     TC_CMR_TCCLKS_TIMER_CLOCK1|
     TC_CMR_ACPA_TOGGLE );  // RC compare TOGGLES TIOA);

     TC_SetRA(tc, channel, 1); //50% high, 50% low
     TC_SetRC(tc, channel, 1);

     PIO_Configure(PIOC,
     PIO_PERIPH_B,
     PIO_PC25B_TIOA6,
     PIO_DEFAULT);

 TC_Start(tc, channel);

    }

    void setup(){
 pinMode(41,OUTPUT);
 startTimer(TC2, 0, TC6_IRQn);
    }

    void loop(){
    }

title: Arduino DUE Interrupt 1MHz

Answers: 4

body:
I'm not 100% certain without my Due in front of me to test this, but as far as I can see, you are configuring your clock to run at 42MHz with "TC_CMR_TCCLKS_TIMER_CLOCK1" and are getting the timer to trigger when the count is "1" with "TC_SetRC(tc, channel, 1);", which would give you 42MHz, not 4MHz.

Since the clock timer still increments during the TC6_Handler() function, I'm guessing that the interrupt triggers a second time before it has exited the function the first time causing a hang.

Try changing your code to "TC_SetRC(tc, channel, 42000000 / 4000000);" to see if that works.  Your interrupt will still be triggered every 10 ticks of the timer which will only give you 20 ticks of the CPU clock to do your work and exit.  I suspect this may still be too little time to exit before the next interrupt is triggered.  If you still don't get the result you want, try reducing the frequency considerably to see if your timer is actually getting configured correctly.  I don't think you can get exactly 4MHz as the Due timer frequencies are not divisible by 4000000, unless my brain is a little fuzzy this morning and I'm missing something obvious...

If you do need to optimise the code inside your handler so it can run faster, let me know and I'll post some ideas when I can get near my Due and my source code for reference.

You could always check out this link that I used when I needed to understand how to set up a timer for my own projects:
http://2manyprojects.net/timer-interrupts
Should that link go dead before you have a chance to read up, this is the example source from that page I modified for my own purposes:

    // These are the clock frequencies available to the timers /2,/8,/32,/128
    // 84Mhz/2 = 42.000 MHz
    // 84Mhz/8 = 10.500 MHz
    // 84Mhz/32 = 2.625 MHz
    // 84Mhz/128 = 656.250 KHz
    //
    // 42Mhz/44.1Khz = 952.38
    // 10.5Mhz/44.1Khz = 238.09
    // 2.625Hmz/44.1Khz = 59.5
    // 656Khz/44.1Khz = 14.88 // 131200 / 656000 = .2 (.2 seconds)

    // 84Mhz/44.1Khz = 1904 instructions per tick
    const int led_pin = 13;
    int state = false;
    int interruptCtr = 1;
    int S = 0;

    void setup()
    {
      pinMode(led_pin, OUTPUT);
      /* turn on the timer clock in the power management controller */
      pmc_set_writeprotect(false);   // disable write protection for pmc registers
      pmc_enable_periph_clk(ID_TC7);  // enable peripheral clock TC7

      /* we want wavesel 01 with RC */
      TC_Configure(/* clock */TC2,/* channel */1, TC_CMR_WAVE | TC_CMR_WAVSEL_UP_RC | TC_CMR_TCCLKS_TIMER_CLOCK4);
      TC_SetRC(TC2, 1, 131200);
      TC_Start(TC2, 1);

      // enable timer interrupts on the timer
      TC2->TC_CHANNEL[1].TC_IER=TC_IER_CPCS;   // IER = interrupt enable register
      TC2->TC_CHANNEL[1].TC_IDR=~TC_IER_CPCS;  // IDR = interrupt disable register

      /* Enable the interrupt in the nested vector interrupt controller */
      /* TC4_IRQn where 4 is the timer number * timer channels (3) + the channel number (=(1*3)+1) for timer1 channel1 */
      NVIC_EnableIRQ(TC7_IRQn);
    }

    void loop()
    {
      // do nothing timer interrupts will handle the blinking;
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // INTERRUPT HANDLERS
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    void TC7_Handler()
    {
      // We need to get the status to clear it and allow the interrupt to fire again
      TC_GetStatus(TC2, 1);
      state = !state;
      digitalWrite(led_pin, state);

      if( interruptCtr++ >= 6 )
        {
         interruptCtr = 1;
         S = !S; // are we flashing S or O
         if( S ) // set time till next interrupt
            TC_SetRC(TC2, 1, 131200); // 131200 / 656000 = .2 seconds
         else
            TC_SetRC(TC2, 1, 656000); // 656000/ 656000 = 1 second
        }
    }

body:
When I'm working with timers on my Due I always keep my code low level so my solution for your problem would be:

    // These are the clock frequencies available to the timers /2,/8,/32,/128
    // 84Mhz/2 = 42.000 MHz
    // 84Mhz/8 = 10.500 MHz
    // 84Mhz/32 = 2.625 MHz
    // 84Mhz/128 = 656.250 KHz
    //
    // 42Mhz/44.1Khz = 952.38
    // 10.5Mhz/44.1Khz = 238.09
    // 2.625Hmz/44.1Khz = 59.5
    // 656Khz/44.1Khz = 14.88 // 131200 / 656000 = .2 (.2 seconds)

    #define SPEED(x) 42 * x

    // 84Mhz/44.1Khz = 1904 instructions per tick
    const int led_pin = 13;  //PB27
    int interruptCtr = 1;
    int S = 0;

    void setup()
    {

        pmc_set_writeprotect(false);       // disable write protection for pmc registers /**always the first thing to do*/

        // Enable pin 13 with direct port manipulation
        REG_PIOB_PER = 1<<27;
        REG_PIOB_OER = 1<<27;
        REG_PIOB_OWER = 1<<27;

        /* turn on the timer clock in the power management controller */
        pmc_enable_periph_clk(ID_TC0);     // enable peripheral clock TC0

        //Enable interrupt in NVIC before starting interrupt
        NVIC_EnableIRQ(TC0_IRQn);

        //Wavesel on rising edge with timer clock1 (42MHz)
        REG_TC0_CMR0 = TC_CMR_WAVSEL_UP_RC | TC_CMR_TCCLKS_TIMER_CLOCK1;

        //Enabel RC compare interrupt
        REG_TC0_IER0 = TC_IER_CPCS;

        //Set the timer register c
        REG_TC0_RC0 = SPEED(200000);  //SPEED() converts us to clock ticks

        //Start timer
        REG_TC0_CCR0 = TC_CCR_SWTRG | TC_CCR_CLKEN;
    }

    void loop()
    {
      // do nothing timer interrupts will handle the blinking;
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // INTERRUPT HANDLERS
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    void TC0_Handler()
    {
      // We need to get the status to clear it and allow the interrupt to fire again
      REG_TC0_SR0;

      //get curretn pin state (REG_PIOB_ODSR & PIO_PB27) and invert it. AND this result with the pin bit to only set pin 27 to high/low
      REG_PIOB_ODSR = (~(REG_PIOB_ODSR & PIO_PB27)) & PIO_PB27;

      if( interruptCtr++ >= 6 )
      {
        interruptCtr = 1;
        S = !S; // are we flashing S or O
        if( S ) // set time till next interrupt
          REG_TC0_RC0 = SPEED(200000); //0.2 seconds
        else
          REG_TC0_RC0 = SPEED(1000000); //1 second
        }
    }

With this code you should be able to increase the switching frequency to theoretically 42MHz. But due to the time the interrupt needs to run it will be reduced to something about 10MHz or less but even this is much higher than your 334KHz.

body:
This works

    int unsigned A[2500];
    int unsigned S;
    void setup()
    {
      Serial.begin(9600);
      //pinMode(30, OUTPUT);
      REG_PIOB_OWER = 0xFFFFFFFF;     // Enable PORT B
      REG_PIOB_OER =  0xFFFFFFFF;     // Set PORT B as output port
      REG_PIOD_OWER = 0xFFFFFFFF;     // Enable PORT D
      REG_PIOD_OER =  0xFFFFFFFF;     // Set PORT D as output port
      REG_PIOC_OWER = 0xFFFFFFFF;     // Enable PORT C
      REG_PIOC_OER =  0xFFFFFFFF;     // Set PORT C as output port
      /* turn on the timer clock in the power management controller */
      pmc_set_writeprotect(false);     // disable write protection for pmc registers
      pmc_enable_periph_clk(ID_TC7);   // enable peripheral clock TC7

      /* we want wavesel 01 with RC */
      TC_Configure(/* clock */TC2,/* channel */1, TC_CMR_WAVE | TC_CMR_WAVSEL_UP_RC | TC_CMR_TCCLKS_TIMER_CLOCK1);
      TC_SetRC(TC2, 1, 42);// 1 MHz
      TC_Start(TC2, 1);

      // enable timer interrupts on the timer
      TC2->TC_CHANNEL[1].TC_IER=TC_IER_CPCS;   // IER = interrupt enable register
      TC2->TC_CHANNEL[1].TC_IDR=~TC_IER_CPCS;  // IDR = interrupt disable register

      /* Enable the interrupt in the nested vector interrupt controller */
      /* TC4_IRQn where 4 is the timer number * timer channels (3) + the channel number (=(1*3)+1) for timer1 channel1 */
      //NVIC_EnableIRQ(TC7_IRQn);
    }

    void loop()
    {
    int unsigned MSBs = 0;
    int unsigned LSBs = 0;
    int unsigned C = 0;
    int unsigned B = 0;
    int unsigned i = 0;
    //int unsigned long B1 = 0;
    //int unsigned B2 = 0;
    int unsigned MSBMask = B11111111;
    MSBMask << 8;

     //Serial.println(base, DEC);
    //delay(100);
     //Serial.println(ratio, DEC);
    //delay(100);
    for(i=0; i<2500; i++)
    {
      //C = 20000/2*sin(2*PI*(90000/0.0025*i+10000)*i);
      C = 20000*sin(2*PI*i);
     // A[i] = sin(2*PI*(10+90/25*i)*1/1000);
       //A[1] = sin(2*PI*(10+90/25*i)*1/1000);

      MSBs = C >> 8;
      LSBs = C & MSBMask;
       //Serial.println(C, BIN);
      //Serial.println(MSBs, BIN);
     // Serial.println(LSBs, BIN);
    MSBs = MSBs << 12;
    LSBs = LSBs << 1;
    B = MSBs+LSBs;
    A[i] = B;
     //Serial.println(B, BIN);
     //Serial.println(A[i], BIN);
    //delay(100);
    }

    NVIC_EnableIRQ(TC7_IRQn);
    while(1){}
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // INTERRUPT HANDLERS
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    void TC7_Handler()
    {
     TC_GetStatus(TC2, 1);// We need to get the status to clear it and allow the interrupt to fire again
      //int i=0;
      REG_PIOD_CODR = 0x1 << 9;// clear pin 30 on due
     // REG_PIOD_CODR = 0x1 << 10;// clear pin 32 on due

    REG_PIOC_ODSR = A[S];//set outout pins to array entry

    REG_PIOD_SODR = 0x1 << 9;// set pin 30 on due, commanding DAC to take commended Analog output,
       S++;
       if(S>2500){S=0;}

    }

body:
> I need to update with freq 1MHz. ...No luck.

no kidding.

think about interrupt overhead. and how much it takes away the processing power if you interrupt at 1 million times a second.

think DMA if available on your chip. If not, think a faster chip or compromise on your 1Mhz expectation.