body: I would like to use larger numbers than an unsigned long long in Arduino. Is that possible?

title: Can I work with larger numbers than an unsigned long long in Arduino?

Answers: 1

body:
There are many ways to use numbers bigger than an `unsigned long` on Arduino. The right one depends on the application.

**Floats and Doubles**
`float`s and `double`s types on Arduino can hold exact integers up  `2^53`. That is a very large number. They are built into the Arduino compiler.

**uint64_t**
The `uint64_t` type can hold exact integers up to `2^64`. That is a very large number. This type is built into the Arduino compiler, but note that some Arduino library functions do not have versions for this type so may need to down-convert for printing and serializing and stuff like that.

**BigNumber (or bc)**
The `BigNumber` type can represent exact numbers (integer or otherwise) limited only by available memory- but certainly hundreds of digits long on Arduino. These are extremely big numbers. This type is not built into the Arduino, but there is a nice Arduino library version available...

https://github.com/nickgammon/BigNumber

Again, this type is not supprted by the Arduino built-in library functions so  you will need to either down-convert or find `BigNumber` compatible functions for things like printing and serializing.


body: I am trying to communicate with ethernet shield. When I enter the IP in Chrome the job is done (simply an LED turns off and on with IP/$1 and IP/$2) but with Safari it is not. Any idea what the difference is?

title: Control the ethernet shield with Chrome and Safari

Answers: 1

body: I had the same problem. I forgot to complete the `client.println` with a newline (`\n`).


body:
Basically I want one LED to flash 5 times in the same amount of time it takes another LED to flash 4 times. This is what I have, but they are flashing independently and I need them to flash simultaneously.

<!-- language: c -->

    //Making a 5/4 Polyrhythm with 2 LEDs
    const int LED13 = 13;
    const int LED7 = 7;
    int i = 5;

    void setup() {
       pinMode(LED13, OUTPUT);
       pinMode(LED7, OUTPUT);
    }

    void loop() {

      for(i=0; i<5; i++)
      {
         digitalWrite (LED13, HIGH);
         delay(500);
         digitalWrite (LED13, LOW);
         delay(800);
      }

      for(i=0; i<4; i++)
      {
         digitalWrite (LED7, HIGH);
         delay(500);
         digitalWrite (LED7, LOW);
         delay(1000);
      }
   }

title: How to make 2 LEDs flash in a 5/4 Polyrhythm?

Answers: 2

body:
See https://arduino.stackexchange.com/a/17929/6628 with code like:

    const int onTime = 500;
    const int measureTime = (int) (60*1000/10);  // 10 BPM, or 1500*4ms/measure
    const int off4 = measureTime/4 - onTime;  // take care these don't go negative
    const int off5 = measureTime/5 - onTime;  //
    unsigned long next5;
    unsigned long next4;

    ...
    loop(){
      unsigned long now;
      now=millis();
      ...
      if(next5 < now) {
         if digitalRead(LED13) { next5 = now+off5;   digitalWrite(LED13,LOW );}
         else                  { next5 = now+onTime; digitalWrite(LED13,HIGH);}
      }
      if(next4 < now) {
         if digitalRead(LED7)  { next4 = now+off4;    digitalWrite(LED7,LOW );}
         else                  { next4 = now+onTime ; digitalWrite(LED7,HIGH);}
      }

    }

body:
I generally calculate whether the led must be on or off, based on the current time.

    //Making a 5/4 Polyrythm with 2 LEDs
    const int LED13 = 13;
    const int LED7 = 7;
    int i = 5;

    void setup() {
       pinMode(LED13, OUTPUT);
       pinMode(LED7, OUTPUT);
    }

    void loop() {
        // led 13 flashes 5 times per interval of 6 seconds. So the led is on/off for 600ms ( 6000/(2*5) )
        // led  7 flashes 4 times per interval of 6 seconds. So the led is on/off for 750ms ( 6000/(2*4) )
        bool led13on = (millis()/600)%2!=0; // count the number of 600ms intevals have passed, and see if this number if odd or even. odd means led must be on, even means the led must be on
        bool led7on  = (millis()/750)%2!=0;
        digitalWrite (LED13, led13on);
        digitalWrite (LED7, led7on);
        delay(10);
    }


body:
Trying to get avr-objdump to generate a listing that interleaves the assembly with the source code. I've tried a bunch of debugging arguments in different configurations but I can't seem to get it. The best I could do was getting it to interleave the object with line numbers from the assembly (avr-objdump -lS spi.o)

[Original Makefile][1]

Here's my current Makefile:

    PREFIX=avr-
    CC=${PREFIX}gcc
    OBJCOPY=${PREFIX}objcopy

    BIN=knightrider
    MCU=attiny85
    OBJS=../src/tinySPI.o src/knightrider.o

    PROG?=atmelice_isp
    PORT?=usb

    CFLAGS=-g -mmcu=${MCU} -ffunction-sections -fdata-sections
    LDFLAGS=-mmcu=${MCU} -Wl,--gc-sections

    ${BIN}.hex: ${BIN}.elf
     @mkdir -p bin
     ${OBJCOPY} -O ihex -R .eeprom build/$< bin/$@

    ${BIN}.elf: ${OBJS}
     @mkdir -p build
     ${CC} ${LDFLAGS} -o build/$@ $?

    install: ${BIN}.hex
     avrdude -c ${PROG} -P ${PORT} -p ${MCU} -U flash:w:${BIN}.hex:i -qq

    clean:
     rm -f build/*
     rm -f bin/*

    fuses:
     avrdude -c ${PROG} -P ${PORT} -p ${MCU} -U lfuse:w:0x62:m -U hfuse:w:0xDF:m -U efuse:w:0xFF:i -qq

What would I need to change in order to run avr-objdump and get an interleaved listing of an .o and its corresponding .c (e.g. spi.o and spi.c)?

  [1]: https://github.com/AshlynBlack/tinySPI/blob/c0748ee5fe1d5b85813ac7b4628bb84014d4a0d4/examples/Makefile

title: Interleave Assembly and Source for avr-objdump

Answers: 1

body:
First make sure you add `-g` to all your compilation commands.

Then you can run `avr-objdump -S build/spi.elf` (for instance).

Also I see you're missing the MCU definition in your link command. Without that it won't link in the proper C startup routines and your program will most probably not run.

Here is a makefile I use:

    PREFIX=avr-
    CC=${PREFIX}gcc
    CXX=${PREFIX}g++
    LD=${PREFIX}ld
    AS=${PREFIX}as
    OBJCOPY=${PREFIX}objcopy
    OBJDUMP=${PREFIX}objdump

    BIN=blink
    MCU=atmega328p
    OBJS=blink.o

    CFLAGS=-g -mmcu=${MCU} -ffunction-sections -fdata-sections
    CXXFLAGS=-g -mmcu=${MCU} -ffunction-sections -fdata-sections -fno-exceptions
    LDFLAGS=-mmcu=${MCU} -Wl,--gc-sections

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

    ${BIN}.elf: ${OBJS}
     ${CC} ${LDFLAGS} -o $@ $?
     ${OBJDUMP} -S $@ > ${BIN}.dis

    install: ${BIN}.hex
     avrdude -C ./avrdude.conf -c usbasp -p ${MCU} -U flash:w:${BIN}.hex
     -qq

    clean:
     rm -f *.o *.elf *.hex

    fuses:
     avrdude  -c usbasp -p ${MCU} -C avrdude.conf -U lfuse:w:0xff:m -U h
    fuse:w:0xd6:m -U efuse:w:0x05:m -qq


body:
I am trying to create an array of structs that contain pairs of Strings and Callbacks the problem I am having is assigning the callback function. I have the following code:

    #define UI_ROUTINE_ITEMS 10

    struct MenuItem{
     String label;
     typedef void (*callback)();
    };

    class MenuSystem{
       MenuItem routineMenu[UI_ROUTINE_ITEMS];

       MenuSystem(){
          routineMenu[0] = {"Test", &Test::TestCallback};
       }
    }

    class Test{
       void TestCallback(){
          Serial.println("Callback called");
       }
    }

When I try to compile this I get:

    error: no match for 'operator=' (operand types are 'MenuItem' and '<brace-enclosed initializer list>')

I know this is a Syntax issue I just can not figure out how this should be done. I have looked at several examples but I can't figure out how to do this with Classes without using free/malloc, what am I doing wrong?

----------
**EDIT**

----------

I finally got this working, the problem was that the function that I was trying to call was not static and the declaration in the structure was not quite right. Below is the corrected example:

    #define UI_ROUTINE_ITEMS 10

    #include <Arduino.h>

    struct MenuItem{
        String label;
        void (*callback)(void);
    };

    class MenuSystem{
       MenuItem routineMenu[UI_ROUTINE_ITEMS];

       MenuSystem(){
          routineMenu[0] = {"Test", &Test::TestCallback};
       }
    }

    class Test{
       public static void TestCallback(){
          Serial.println("Callback called");
       }
    }

title: Array of Strings and Callbacks

Answers: 4

body:
Several issue with this code. First, use public/protected/private for classes. Second, use a const char* instead of String or even better str_P. It is the usage of String that is giving the compile error. Third, the Test::TestCallback function reference is not possible. It is a member function. To correct that either have an instance or define the callback function as static.

You could define an abstract MenuItem class with the string and a virtual member function. A Menu class would hold a collection of MenuItems. All the static data should be put in program memory.

There is a [Menu][1] system in Cosa. Please see the [example sketch][2]. This implementation follows the [MVC][3] design pattern.

Cheers!

  [1]: https://github.com/mikaelpatel/Cosa/blob/master/libraries/Menu/Menu.hh
  [2]: https://github.com/mikaelpatel/Cosa/blob/master/libraries/LCD/CosaLCDmenu/CosaLCDmenu.ino
  [3]: https://en.wikipedia.org/wiki/Model–view–controller

body:
Your system works in pure C too:

    typedef struct _MenuItem
    {
        const char *label; // or String if you like
        void (*callback)();
    } MenuItem;

    void testCallback()
    {
        Serial.println("testCallback() Called");
    }

    MenuItem menu_system[10];
    void setup()
    {
        menu_system[0].label    = "Test";
        menu_system[0].callback = testCallback;

        ... # more menu definitions with callbacks
    }

    void loop()
    {
        unsigned int user_menu_selection;

        ... # some menu code, user selection in <user_menu_selection>

        menu_system[user_menu_selection].callback();  // TODO: error checking
    }

It might be a good idea to store any static Menu Strings into [PROGMEM][1].

  [1]: https://www.arduino.cc/en/Reference/PROGMEM

body:
A pointer to a member instance function **is** possible:

    void (Some_class::*Some_fnc_ptr)();

And in order to call different classes than just "Test" you'd have to play some games with templates and probably virtual functions.  It would get pretty involved, but doable.

body:
I know that you've resolved your dilemma, but I just wanted to show you a trick: personally, I _**hate**_ the pointer-to-function mechanism that everyone uses, when there's a perfectly good alternative.

Here's a function that takes an `int` and returns a `char`:

    char SomeFn(int i);

Here's a `typedef` describing that function as a type:

    typedef char Fn(int i);

Looks pretty similar, huh? What's the point? Now that you've got a type, you can use that instead:

    void SetCallback(Fn *fn);

`SetCallback` takes as a parameter a pointer to a function of type `Fn`. The `*` is necessary, and (to me) makes more sense than trying to barrel the pointer-ness inside the type itself - which is what leads to the parenthesis overload. You can call it like this:

    SetCallback(&SomeFn);

What could be easier? If `SomeFn` was a `static` member of a class, you could just as easily use that:

    SetCallback(&Class::SomeFn);


body:
Is it allowed to have battery and USB connected to the Trinket(3.3V) at the same time?

I am using the battery to also power other components, so always disconnecting power, hooking USB to re-program and vice-versa is quite time consuming (and I fear to ruin the connectors).

title: Trinket: Battery + USB at the same time?

Answers: 1

body:
From https://learn.adafruit.com/system/assets/assets/000/010/773/original/adafruit_products_trinket3.png?1378223258 it looks OK -- there are blocking diodes D3 and D2 that prevent backfeeding either the battery or the USB +5.

If you are worried, or want to monitor battery-only performance, you could make a special USB cable with the +5 red wire disconnected, and rely on the in-circuit battery to power the device, while still using the USB data lines.  See https://www.pjrc.com/teensy/external_power.html Option 2 for an example of the cable surgery.


body:
I'm trying to find a way I can toggle the 5V pin to turn on/off. I want the voltage to pass to another wire at a certain point. It should be off and then when something happens, the 5V should turn on.

How can I do this?

title: Is there any way I can turn off the 5V pin?

Answers: 4

body:
There isn't programmatic control of the 5V pin, it is hard wired to the USB or the output of the Vin Voltage regulator.

You might try something from https://arduino.stackexchange.com/questions/403/how-can-higher-current-devices-motors-solenoids-lights-etc-be-controlled-b to control the low side of the external device.  If you need high-side control, maybe an opto-isolator would be a good solution.

body: You don't really want to do that. The 5V pin is on the power bus of your Arduino board. If it *were* possible to turn it off, the entire Arduino would shut down.

body:
If I'm understanding you correctly, you want a 5 V output that is under programatic control. Do you know how much power you want to pull from the pin?

If the demand is fairly low, you could use one of the digital pins directly – they will supply about 40 mA on an "official" Arduino.

If you need more power, then you could use the pin to switch an external device such as a transistor or a relay.

body:
For energy-efficient switching (along with relatively high-current capability), I recommend using a *Darlington* transistor connected to one of the output pins (digital for on/off, analogue for variable). Then you would just call  pinMode(A0, OUTPUT); followed by digitalWrite(A0, HIGH); Here is a sketch I made demonstrating what I mean:
[![enter image description here][1]][1]

Note that a normal transistor would draw more current from the Arduino's pin, which could be bad for the Arduino, and which would waste energy.

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


body:
In arduino's official page about ShiftOut https://www.arduino.cc/en/Tutorial/ShiftOut, a drawing with two 74HC595 powered by the arduino board, is displayed.

Since the resistors are 220Ω, the total current should be 5/220x16 = 0.36A which exceeds the maximum total current of 0.20A for the arduino device.

So, could someone turn on simultaneously 16 LEDs using two shift registers without damaging the device?

Thank you

title: max current while using a shift register

Answers: 1

body:
0.20A is *not* the maximum current for an Arduino device.  0.20A is the maximum current for *the chip that is on the Arduino*.  Thus it is only relevant to devices that are *directly* connected to the Arduino's IO pins (that connect direct to the chip).

The shift registers take their own power from the +5V pin, which is limited to between 500mA and 800mA depending on how you power your board.  Each shift register has its own power limits that are completely separate to the Arduino's main chip's power limits.


body:
I am using [Trinket Pro 5V][1] to run a simple i/o code. The input from the piezo vibration sensor is read by the Trinket and Translated into a servo position.
It works fine powered through a USB connection, however as soon as I try to power it using a 9V battery (plugged into the Bat+ and G terminals), the code stops running and the red light on the Trinket starts to blink.

Is the power source not sufficient - 9V?

Has anyone faced a similar problem?

  [1]: http://www.adafruit.com/product/2000

title: Trinket Pro 5V red light flashing when battery attached

Answers: 1

body:
Please consider reading the ["https://learn.adafruit.com/trinket-gemma-servo-control/wiring"][1] tutorial.

It says

> It is suggested you use an external wall or battery supply and not
> power the servo via the regulator. servos can draw up to 500mA and the
> Trinket regulator can only source 150 milliamps (USB power generally
> 500 milliamps).

No matter what power supply you hook to the "Bat+" battery pin, if you hook the servo power to the "5V" pin on the trinket, the trinket's on-board 5V regulator will temporarily collapse under the load of the servo, which typically causes the system to reset over and over again.

Instead, please hook the servo power directly to the battery.
Alas, a typical partially-drained 9V battery has enough internal resistance that the battery's voltage will temporarily collapse under the load of the servo, which typically causes the system to reset over and over again.

Instead, use a better power source.

Many people, even when they intend to eventually run their system on batteries, start out using a wall-wart power supply, so they don't have to keep wondering "Is this glitch because of a bug in my software, or is the battery just going dead?".

The ["Adafruit 16-Channel Servo Driver with Arduino"][2] tutorial says:

> Good power choices are:
>
> * [5v 2A switching power supply][3]
> * [5v 10A switching power supply][4]
> * [4xAA Battery Holder][5] - 6v with Alkaline cells.  4.8v with NiMH rechargeable cells.
> * 4.8 or 6v Rechargeable RC battery packs from a hobby store.

You might also want to look at other [Battery holders][7] that hold lots of AA batteries in a convenient package.

Related:
["How to get high current from 9 volt batteries"][8]
and
["What is the max current I could draw from a 9V battery?"][9].

  [1]: http://learn.adafruit.com/trinket-gemma-servo-control/wiring
  [2]: http://learn.adafruit.com/16-channel-pwm-servo-driver/hooking-it-up
  [3]: http://www.adafruit.com/products/276
  [4]: http://www.adafruit.com/products/658
  [5]: http://www.adafruit.com/products/830
  [6]: http://www.adafruit.com/products/449
  [7]: http://www.adafruit.com/category/135
  [8]: https://electronics.stackexchange.com/questions/73169/how-to-get-high-current-from-9-volt-batteries
  [9]: http://forum.arduino.cc/index.php?topic=132106.0


body:
Following this tutorial:

http://www.instructables.com/id/Complete-newbie-step-by-step-3D-printer-with-all-p/?ALLSTEPS

I connected DVD stepper motor to RAMPS 1.4 on arduino with Marlin software with this settings:

<!-- language: c -->

     //#define DEFAULT_AXIS_STEPS_PER_UNIT   {80,80,4000,500}  // default steps per unit for Ultimaker

     #define DEFAULT_AXIS_STEPS_PER_UNIT {215.12,215.12,8034.69,196.52}

     // #define DEFAULT_MAX_FEEDRATE          {300, 300, 5, 25}    // (mm/sec)

     #define DEFAULT_MAX_FEEDRATE {100, 100, 2, 25}

     // #define DEFAULT_MAX_ACCELERATION      {3000,3000,100,10000}    // X, Y, Z, E maximum start speed for accelerated moves. E default values are good for Skeinforge 40+, for older versions raise them a lot.

     #define DEFAULT_MAX_ACCELERATION {200,200,50,5000}

     #define DEFAULT_ACCELERATION          100    // X, Y, Z and E acceleration in mm/s^2 for printing moves

     #define DEFAULT_RETRACT_ACCELERATION  100    // E acceleration in mm/s^2 for retracts

     #define DEFAULT_TRAVEL_ACCELERATION   100    // X, Y, Z acceleration in mm/s^2 for travel (non printing) moves

I put a [video at vid.me](https://vid.me/vd6Q) (hopefully with sound) showing stepper behaviour when I press +1mm,-1mm,-1mm,-1mm,-1mm,-1mm,-1mm,+1mm,+1mm,+1mm,+1mm  on Pronterface software.

title: Weird stepper motor behaviour on RAMPS in arduino

Answers: 1

body:
The video you show shows movement of far more than 1mm.  This indicates that the steps per unit is far different than you are configuring the Marlin software for.  With a +/-1mm and 212 steps per mm, there should have been 212 steps sent to your stepper.

Recalculate your steps/mm values and slow down the feed rate to get something reliable.

For experimenting, in Pronterface, set the feedrate of 10mm/sec (600mm/min) or 1mm/sec (60mm/min) to slow things down so you can hear or count the steps with your ear, then choose smaller steps, like +0.1mm and see if you get the planned displacement.  If, at a really slow speed, you don't get the corresponding movement, then your steps/mm need adjustment to match your system.

Eyeballing it, I'd say the called-for 1mm or 212 steps is moving the stage about 10mm, so you would need numbers more like this for the x and y axes:

    #define DEFAULT_AXIS_STEPS_PER_UNIT {21 ,21 ,8034.69,196.52}


body:
I was looking for some easy tutorial on bidirectional communication via ESP8266 connected to Arduino UNO. I want to send and receive strings from and to JQuery based website.

However, I couldn't find any answers on this because most of them are about working directly with ESP. It's probably easy thing to setup but I'm totally new in working with network communication ;(

At this moment I know how to set AT for ESP as client and receive messages with pin number to toggle:

    AT+RST
    AT+CWMODE=1
    AT+CIPMUX=1
    AT+CWJAP="user","pswd"
    AT+CIPSERVER=1,80
    AT+CIPSTO=10

And JQuery for buttons (data is their ID) form one of tutorials:

    $(".led").click(function(){
        var p = $(this).attr('id');
        $.get("http://192.168.1.14:80/", {pin:p});
    });

Problem with this is whenever I send something the ESP gets the value and prints info but then it disconnects after 10 seconds (defined time) and when I hit the button again it reconnects and I can't do more (for example: send another value) during the time when it's connected.

Is it normal behavior? How to make it possible to send many messages when it's still connected to the port without waiting to reconnect? Can I make it in more "streaming" way? And how to make this bidirectional? Any advice on configuring the device will be helpful.

title: ESP8266 and Arduino bidirectional streaming from and to a website

Answers: 0


body:
I am building a CNC machine based on GRBL code on a uno. I also have found a script to read data on a N64 controller. I know there is not enough pins available to do both codes running on the same arduino, so I was wondering if I could have my GRBL arduino connected to a computer thru USB, and at the same time, have a second arduino reading data from the n64 joystick, create Gcode accordingly, and feed that Gcode to the GRBL arduino through the tx/rx pins of each of them.
I guess I'll have to put a on-off switch on the tx/rx wife to avoid "noise" when I actually send Gcode to the GRBL arduino from the computer.

Does this all make sense?

title: May I use both USB-serial and tx/rx pins at the same time?

Answers: 2

body:
The usb port and the tx/rx pins are one and the same thing. You can't use one thing for two jobs at the same time. So you will either have to implement some kind of multiplexing system (switches) or come up with a different way of doing things, maybe using the [SoftwareSerial][1] library or the [Wire Library][2] or investing in a better board with more than one serial port.

  [1]: https://www.arduino.cc/en/Reference/SoftwareSerial
  [2]: https://www.arduino.cc/en/Reference/Wire

body:
Low impedance circuits connected to the TX/RX pins would cause distortion in the serial signal and would interfere with communication.

A switch would help here. Alternately, you could use a Mega 2560 with more IOs, or if you are breadboarding it, use a 1284p chip.

You could also use SoftwareSerial to communicate with the other Arduino on another set of pins.


body:
I want to hook up an arduino to one of those generic RGB LED controllers, you see them everywhere, they are these little white boxes with power input and RGB strip plug and an IR LED lead. Is there a way to take to the IR + and - and connect them the arduino? Then spoof an IR signal to control the control module? I want to do it this way because I already own both the arduino and control module and that module handles the power for the LEDs. All I am hoping I have to do is send the controller the hex value for the IR command through the the arduino in order to control it. Here's a link to what the module looks like and the remote it comes

https://www.amazon.com/dp/B00ASHQQKI/ref=cm_sw_r_cp_awd_htMywb1W85962

title: How to interface with generic IR RGB LED controller?

Answers: 1

body:
The [IRRemote Library][1] is a good starting point, but you'll probably need a RAW mode.   I've got a couple IR controllers from different companies, and they use different codes for the same things.

  [1]: http://www.righto.com/2009/08/multi-protocol-infrared-remote-library.html


body:
I am currently working on a project on serial communication between RPi and Arduino. This is the code that I am using from RPi side, it's in C:

<!-- language: c -->

    int main()
    {
       //-------------------------
    //----- SETUP USART 0 -----
    //-------------------------
    //At bootup, pins 8 and 10 are already set to UART0_TXD, UART0_RXD (ie the alt0 function) respectively
    int Arduino= -1;

    //OPEN THE UART
    //The flags (defined in fcntl.h):
    // Access modes (use 1 of these):
    //  O_RDONLY - Open for reading only.
    //  O_RDWR - Open for reading and writing.
    //  O_WRONLY - Open for writing only.
    //
    // O_NDELAY / O_NONBLOCK (same function) - Enables nonblocking mode. When set read requests on the file can return immediately with a failure status
    //           if there is no input immediately available (instead of blocking). Likewise, write requests can also return
    //           immediately with a failure status if the output can't be written immediately.
    //
    // O_NOCTTY - When set and path identifies a terminal device, open() shall not cause the terminal device to become the controlling terminal for the process.
    Arduino = open("/dev/ttyAMA0", O_RDWR | O_NOCTTY | O_NDELAY);     //Open in non blocking read/write mode
    if (Arduino == -1)
    {
     //ERROR - CAN'T OPEN SERIAL PORT
        printf("Error - Unable to open UART.  Ensure it is not in use by another application\n");
    }

    //CONFIGURE THE UART
    //The flags (defined in /usr/include/termios.h - see http://pubs.opengroup.org/onlinepubs/007908799/xsh/termios.h.html):
    // Baud rate:- B1200, B2400, B4800, B9600, B19200, B38400, B57600, B115200, B230400, B460800, B500000, B576000, B921600, B1000000, B1152000, B1500000, B2000000, B2500000, B3000000, B3500000, B4000000
    // CSIZE:- CS5, CS6, CS7, CS8
    // CLOCAL - Ignore modem status lines
    // CREAD - Enable receiver
    // IGNPAR = Ignore characters with parity errors
    // ICRNL - Map CR to NL on input (Use for ASCII comms where you want to auto correct end of line characters - don't use for bianry comms!)
    // PARENB - Parity enable
    // PARODD - Odd parity (else even)
    struct termios options;
    tcgetattr(Arduino, &options);
    options.c_cflag = B9600 | CS8 | CLOCAL | CREAD;  //<Set baud rate
    options.c_iflag = IGNPAR;
    options.c_oflag = 0;
    options.c_lflag = 0;
    tcflush(Arduino, TCIFLUSH);
    tcsetattr(Arduino, TCSANOW, &options);

    //----- TX BYTES -----
    unsigned char tx_buffer[20];
    unsigned char *p_tx_buffer;
    int Angle=-20;
    int Speed=100;

    int Botschaft=Fusion(Crypt(Angle),Crypt(Speed));

    p_tx_buffer = &tx_buffer[0];
    *p_tx_buffer++ = Decompositer(Botschaft,1)+'0';
    *p_tx_buffer++ = Decompositer(Botschaft,2)+'0';
    *p_tx_buffer++ = Decompositer(Botschaft,3)+'0';
    *p_tx_buffer++ = Decompositer(Botschaft,4)+'0';
    *p_tx_buffer++ = Decompositer(Botschaft,5)+'0';
    *p_tx_buffer++ = Decompositer(Botschaft,6)+'0';

    if (Arduino != -1)
    {
    int count = write(Arduino, &tx_buffer[0], (p_tx_buffer - &tx_buffer[0]));  //Filestream, bytes to write, number of bytes to write
    if (count < 0)
    {
   printf("UART TX error\n");
    }
    }

 //----- CHECK FOR ANY RX BYTES -----
    if (Arduino != -1)
    {
    // Read up to 255 characters from the port if they are there
    unsigned char rx_buffer[256];
    int rx_length = read(Arduino, (void*)rx_buffer, 255);  //Filestream, buffer to store in, number of bytes to read (max)
    if (rx_length < 0)
    {
   //An error occured (will occur if there are no bytes)
    }
    else if (rx_length == 0)
    {
   //No data waiting
    }
    else
    {
   //Bytes received
   rx_buffer[rx_length] = '\0';
      printf("%i bytes read : %s\n", rx_length, rx_buffer);
      }
    }

    //----- CLOSE THE UART -----
    close(Arduino);
    }

    int Fusion(int Angle, int Speed)
    {
       int msg;
       msg=Angle*1000+Speed;
       return msg;
    }

    int Decompositer(int Num,int Place)
    {
       int Result[5];

       Result[0]=Num/100000;
       Result[1]=(Num-Result[0]*100000)/10000;
       Result[2]=(Num-Result[0]*100000-Result[1]*10000)/1000;
       Result[3]=(Num-Result[0]*100000-Result[1]*10000-Result[2]*1000)/100;
       Result[4]=(Num-Result[0]*100000-Result[1]*10000-Result[2]*1000-Result[3]*100)/10;
       Result[5]=(Num-Result[0]*100000-Result[1]*10000-Result[2]*1000-Result[3]*100-Result[4]*10);
       return Result[Place-1];
    }

    int Crypt(int Value)
    {
       int result;
       result = Value + 100;
       return result;
    }

And this is my code from the Arduino side:

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

    void loop(){
        if (Serial2.available())
        {
            int inByte = Serial2.read();
            Serial.write(inByte);
        }
        if (Serial.available())
        {
            int inByte = Serial.read();
            Serial2.write(inByte);
        }
    }

My purpose is to send a 6 digit number to my Arduino side, and be able to read them and then separate them into 2 different numbers...

The problem is I see only the first 2 digits and the rest are weird characters like `1‚þ`.

I really appreciate your help.

title: Serial Communication, Arduino and Rpi , C library

Answers: 0


body:
I currently have a project that is working on an AtMega2560 platform (heavily derived off the Arduino Mega). It mainly involves a GPS module and SD card.

Going forward I am looking to add a few more sensors (IMU etc.). I would like to a more powerful microcontroller -- for the high rate logging I need and also it seems best from a future scalability perspective.

I would like to start with using one of the ARM based uC platforms available out there, transition my software to it using a breadboard setup, and then eventually make a custom board.

So my QUESTION is:
Which would be an easier option from a migration/transition and community support point of view --- Teensy or Due? I currently use the SDFat and Adafruit GPS libraries, the SDFat being a major concern for migration.

Any other considerations/suggestions/advice will be appreciated.

Thank you.

title: Migrating from ATMega2560 to ARM based -- Teensy vs Due?

Answers: 1

body:
If compatability is what you are after I would say go for the Due. If good products are what you are after, go for the Teeensy. The Due, being a real Arduino, will have the best software support and forum community and thus the best chance of getting existing libraries to work with it. The Teensy, because the project really centers around one guy's brilliance, is highly dependant on that one person's time, and while he has done a stirling job with the Teeensy core, he is still only one guy and can only do so much. So it may be harder to get third party libraries working on it.

That said, the Due is not a nice board. The SAM3X chips are awful. Any chip that needs an erase button attached to it to get around the "possibility it won't be able to enter the bootloader" (which incidentally is hard coded in ROM and can NEVER be replaced or upgraded) is destined for the scrap heap IMHO.

There are of course other options as well. There are about a million and one ARM based Arduino-like boards out there with varying amounts of support, either from the chip manufacturer (such as the ST boards), or third party builders. Then of course there are other architectures that are in my biased opinion much better than the ARM ones - chips such as the MIPS based PIC32, used in the chipKIT family of boards. Those latter though don't yet have a port of the SdFat library yet, although it is something that is being actively worked on. There are even Sparc based boards out there that are worth a look.


body:
I am using [sevseg][1] and i can't get more than 8 digits to work.  I really need 15.  Does somebody know what I can do to get this?

Shown is the original example

This is using Gabriel Staples example in the sevseg library:

    #include <SevSeg.h>

    SevSeg sevseg; //Instantiate a seven segment controller object

    void setup()
    {
      byte numDigits = 4; //<<---I am wanting 15, but doesn't work after 8------
      byte digitPins[] = {2, 3, 4, 5}; //Digits: 1,2,3,4 <--put one resistor (ex: 220 Ohms, or 330 Ohms, etc, on each digit pin)
      byte segmentPins[] = {6, 7, 8, 9, 10, 11, 12, 13}; //Segments: A,B,C,D,E,F,G,Period

      sevseg.begin(COMMON_ANODE, numDigits, digitPins, segmentPins);
    // Note: 100 brightness simply corresponds to a delay of 2000us after lighting each segment. A brightness of 0
    // is a delay of 1us; it doesn't really affect brightness as much as it affects update rate (frequency).
    // Therefore, for a 4-digit 7-segment + pd, COMMON_ANODE display, the max update rate for a "brightness" of 100 is 1/(2000us*8) = 62.5Hz.
    // I am choosing a "brightness" of 10 because it increases the max update rate to approx. 1/(200us*8) = 625Hz.
    // This is preferable, as it decreases aliasing when recording the display with a video camera....I think.
      sevseg.setBrightness(10);
    }

    void loop()
    {
      //local vars
      static byte decPlace = 0;

      sevseg.setNumber(8888,decPlace);
      decPlace++;
      decPlace %= 4; //rollover back to 0 once variable gets to 4; To anyone wondering: the % is called the "modulo" operator; see here for explanation & example: https://www.arduino.cc/en/Reference/Modulo

      sevseg.refreshDisplay(); // Must run repeatedly; don't use blocking code (ex: delay()) in the loop() function or this won't work right
    }

[1]: https://github.com/DeanIsMe/SevSeg

Using the following code, I can't get the 3rd set of 5 numbers to display.  I have changed the sevseg.h file to 15, but that shouldn't matter:

    #include <SevSeg.h>

    SevSeg sevseg1;//Instantiate a seven segment controller object 1
    SevSeg sevseg2;//Instantiate a seven segment controller object 2
    SevSeg sevseg3;//Instantiate a seven segment controller object 3

    void setup()
    {

      Serial.begin(9600);

    byte segmentPins[] = {22, 23, 24, 25, 26, 27, 28, 34}; //Segments:     A,B,C,D,E,F,G,Period

      byte digitPins1[] = {29, 30, 31, 32, 33};
      sevseg1.begin(COMMON_CATHODE, sizeof(digitPins1), digitPins1,  segmentPins);
      sevseg1.setBrightness(10);

      byte digitPins2[] = {35, 36, 37, 38, 39};
      sevseg2.begin(COMMON_CATHODE, sizeof(digitPins2), digitPins2, segmentPins);
      sevseg2.setBrightness(10);

      byte digitPins3[] = {40, 41, 42, 43, 44};
      sevseg3.begin(COMMON_CATHODE, sizeof(digitPins2), digitPins3, segmentPins);
      sevseg3.setBrightness(10);

    }

    void loop()
    {

    static byte decPlace = 2;

      sevseg1.setNumber( 12345, decPlace );
      sevseg2.setNumber( 12345, decPlace );
      sevseg3.setNumber( 12345, decPlace );

      sevseg1.refreshDisplay();
      sevseg2.refreshDisplay();
      sevseg2.refreshDisplay();
    }

title: Using more than 8 digits using the sevseg library

Answers: 2

body:
You can change the pre-defined maximum number of digits at the top of the `SevSeg.h` header file to as many as 10, if you use `long` or `unsigned long` when you call `setNumber`.  It is defined [here](https://github.com/DeanIsMe/SevSeg/blob/master/SevSeg.h#L27), on line 27:

    #define MAXNUMDIGITS 8 //Increase this number to support larger displays

This the version referenced from the [Arduino Playground SevSeg](http://playground.arduino.cc/Main/SevenSegmentLibrary).  Be sure to use the same number in your modulo, too:

    void loop()
    {
      //local vars
      static byte decPlace = 0;

      sevseg.setNumber(8888,decPlace);
      decPlace++;
      decPlace %= 10; //rollover back to 0 once variable gets to 10

`decPlaces` is mostly useful for floating-point numbers: it specifies how many digits after the decimal point should be displayed.  For integer values, it specifies how many leading zeroes will be displayed.

However (as you discovered), you cannot call `setNumber` with anything larger than a `long`, so you are limited to 10 or fewer digits for `MAXNUMDIGITS`.  (There is no byte overflow -- it's just limited to the number of decimal digits in 232-1.)  This is a limit of one SevSeg instance.  You could have *two* instances of `SevSeg` like this:

    #include <SevSeg.h>
    SevSeg sevseg1;
    SevSeg sevseg2;

    void setup()
    {
      byte segmentPins[] = {6, 7, 8, 9, 10, 11, 12, 13}; //Segments: A,B,C,D,E,F,G,Period

      byte digitPins1[] = {2, 3, 4, 5, 22, 23, 24};
      sevseg1.begin(COMMON_ANODE, sizeof(digitPins1), digitPins1, segmentPins);
      sevseg1.setBrightness(10);

      byte digitPins2[] = {14,15,16,17,18,19,20,21};
      sevseg2.begin(COMMON_ANODE, sizeof(digitPins2), digitPins2, segmentPins);
      sevseg2.setBrightness(10);

      sevseg1.setNumber(  7654321UL, 7 );
      sevseg2.setNumber( 87654321UL, 8 );
    }

    void loop()
    {
      sevseg1.refreshDisplay();
      sevseg2.refreshDisplay();
    }

The first instance handles 7 digits, and the second instances handles 8 digits.  Note the use of "UL" to force and `unsigned long` call.

## Update 11-DEC-2015

>Using the following code, I can't get the 3rd set of 5 numbers to display. I have changed the sevseg.h file to 15, but that shouldn't matter:

First, the `MAXNUMDIGITS` is the maximum *per instance*, so you could set it to **5** to save some precious RAM.

Second, you have a copy and paste error:

    sevseg1.refreshDisplay();
    sevseg2.refreshDisplay();
    sevseg2.refreshDisplay();   <--  Oopsies!  :)

Third, I assume the `setNumber` calls are placeholders for what you're really going to use.  Since they always set the same value, they could be in `setup`.  In your final program, there must be some input that will be used to calculate a number to display with `setNumber`.

body:
Looking at the [sevseg README file on GitHub][1] I find this:

> If you wish to use more than 8 digits, increase MAXNUMDIGITS in SevSeg.h.

Have you done that? Seems like that might be the problem.

As @slash-dev said, be sure to also modify the `loop()` code as well:

    void loop()
    {
      //local vars
      static byte decPlace = 0;

      sevseg.setNumber(8888,decPlace);
      decPlace++;
      decPlace %= numDigits;

I think it makes more sense to use `numDigits` rather than a hard coded constant that you have to remember to change whenever you change the number of digits in your display. It would be worth checking the code for any other hard coded constants. If space is an issue, it might be worth checking to see if using a `#define` results in smaller code than using a variable – in any case do something to avoid needing to understand what "magic numbers" are doing. This is especially important when the same numeric value (e.g., 4) is being used for multiple reasons. Then it gets hard if you need to change the value as you have to understand the purpose behind each use.

[1]: https://github.com/DeanIsMe/SevSeg


body: I'm making a **speedometer using arduino**. I've made use of the interrupt pins to achieve the same. My problem is with the power source. I'm using a 12 V battery supply to power the arduino and I'm also **using the same battery to use a horn**. But, whenever I push the button to sound the horn, the IR sensor connected to the arduino is getting activated and I'm getting an **erroneous reading.** The only common thing between the arduino and the horn is the battery supply.

title: Erroneous sensor reading while connecting extra load

Answers: 1

body:
If the horn has a speaker coil or other magnetic actuator in it, then it will present an inductive load that may cause a voltage spike when you turn it off.  Or, if it's a buzzer, it may generate voltage spikes all during its operation.  Voltage spikes or other electrical noise are the most likely cause of the problem.

It also is possible that the horn draws enough current to drop your battery voltage so low that the Arduino or the sensors don't function reliably.

To find out which is the problem, take voltage readings with and without the horn in operation.  If you have an oscilloscope, look for spikes on system power.

Try isolating and/or buffering the Arduino's power.  If power glitches are the problem, that should fix the problem.  If the problem is electromagnetically radiated electrical noise, further isolation (eg shielding) may be needed.

To isolate the Arduino's power, either operate it from another battery (which is something you can do anyway, while diagnosing the problem) or add one diode into the Arduino's power lead and another into the horn's.  Connect an electrolytic capacitor, eg 100 to 1000 μF, from the Arduino's +V input to ground.  If necessary add ferrite beads around the power leads.

A capacitor across 12 V from the battery will buffer the power, but for more isolation and buffering you can add a buck converter which can manufacture eg +7V from a +12V input while remaining relatively impervious to spikes on the +12V.  Put the large electrolytic across the +7V if you use a buck converter.


body:
I am planning to buy a low cost and low weight laptop with an Atom Processor.

I only have cloned Arduinos - will the Arduino drivers and IDE work on laptops which come with Atom Processors?

title: Will Intel Atom Processor laptops support cloned a Arduino with CH340 driver?

Answers: 1

body:
The processor in your laptop is irrelevant. It is the operating system you should be thinking about, not the processor.

If the operating system has drivers for the CH340 chip, and Windows does, as you already know since you are using it already, then you already know that the answer is a big fat yes.

The only time you need to worry about if the processor will support something is when you are switching to a completely different archetecture such as ARM.


body:
So I purchased a 4 channel Relay which handles AC250V 10A ; DC30V 10A.
But am I able to connect this to replace a light switch so I can automate it?  My bedroom runs on 15 amps.

[![relay board][1]][1]

http://amazon.com/gp/product/B00VHVIBAM?psc=1&redirect=true&ref_=oh_aui_detailpage_o00_s00

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

title: Relay to Mains lightswitch

Answers: 1

body:
All mains electrical work should be performed by a fully qualified electrician.

Yes, this relay board will easily switch a light bulb.

A note on current: A single 100 Watt incandescent globe will only draw 0.83 Amps at 120V AC (0.416 Amps at 240V AC). The equation I used: I=P/V. You would start coming close to the maximum rating after 10 globes (although I advise staying well below the maximum).

You mention that your bedroom runs on 15 Amps, which I assume means that the mains runs through a 15 Amp circuit breaker (or fuse). This circuit breaker will trip if the total current to all devices after it exceeds 15 Amps.

A [similar question][1] was asked by Matthieu Napoli over on the Electrical Engineering Stack Exchange site. There are a number of high quality answers there that would be helpful for you. Worthiest to mention is [Cybergibbons answer][2] where he recommends using the [PowerSwitch Tail][3] as a very safe way of switching mains voltage. You don't need an electrician when using the PowerSwitch Tail providing the light you are controlling has the matching plugs.

  [1]: https://electronics.stackexchange.com/q/33312/104097
  [2]: https://electronics.stackexchange.com/a/33366/104097
  [3]: http://www.powerswitchtail.com/


body:
I'm new to Arduino and today I have a problem with this code:

    int led_1 = 10;
    int led_2 = 11;
    int led_3 = 12;
    int button = 3;
    int time = 0;
    byte val = 0;

    void setup() {
      // put your setup code here, to run once:
      pinMode(led_1, OUTPUT);
      pinMode(led_2, OUTPUT);
      pinMode(led_3, OUTPUT);
      pinMode(button, INPUT);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      val = digitalRead(button);

      if (val == HIGH){
        time = millis();
        while (digitalRead(button) == HIGH) {
          if (millis() - time < 1000) {digitalWrite(led_1, HIGH);}
          else if (millis() -time > 1000 && millis()-time <2000) {digitalWrite(led_2, HIGH);}
          else if (millis()-time >2000) {digitalWrite(led_3, HIGH);}
        }
      } else {
        time =0;
        digitalWrite(led_1, LOW);
        digitalWrite(led_2, LOW);
        digitalWrite(led_3, LOW);
        }
    }

The code should work like this: If I press the button less than one second, `led_1` will turn on. If I press it between one and two seconds, `led_2` will turn on; and if I press the button more than 2 seconds, `led_3` will turn on. If I don't press a button, the LEDs remain off. The `time` variable is used to take the time when I start to press the button and then the control `millis()- time` should give how long I press the button.

It works for a while, then after a random time (I think) if I push the button, only the `led_3` turns on. Why?

title: Issue with simple project

Answers: 2

body:
`time` should be an `unsigned int`.  As soon as `millis` reaches 32768, it will be stored as -32768 in `time`, and your comparisons will not work. This happens after 32.768 seconds.  Here's a short sketch to illustrate:

    int time = 0;

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

    void loop() {
        time = millis();
        if (time % 1000 == 0) {
          Serial.println( time );
          delay( 2 ); // let millis() increment
        }
    }

To see the difference, just change the first line to

    unsigned int time = 0;

Note how `time` rolls over to 0 after 65535 (well, only 65000 is printed).

I would recommend using unsigned constants by adding a "U" after the digits: `1000U`.  In your `if` statements, you must cast the `millis` to the same (smaller) type: `(unsigned int)millis()`.  Also, parentheses make the expression more clear:

          else if (((unsigned int)millis() - time > 1000U) && ((unsigned int)millis() - tempo < 2000U)) {digitalWrite(led_2, HIGH);}

body:
Your code seems inefficient and there is a `tempo` variable that doesn't appear elsewhere.

      if (val == HIGH) {
        time = millis();
        while (digitalRead(button) == HIGH) {
          int time0=millis();
          if (time0 - time < 1000) {
            digitalWrite(led_1, HIGH);
          } else if (time0 - time < 2000) {
            digitalWrite(led_2, HIGH);
          } else if (time0 - time > 2000) {
            digitalWrite(led_3, HIGH);
          }
        }
      }

Note that this code will turn on all LEDs, one by one. If you want to turn off the other, you'll have to had code for that in the tests.


body:
I'm completely new to using modules for the Arduino, so I'm sure some people have more knowledge about this topic than me.
Here's the thing, I want to stream audio over my home wifi, so I'm in need of some rather high-speed modules, I'm aiming for 1-1.5 mbps for some proper compressed audio, including the overhead.

I've looked online for some well known wifi modules, but the only one I've managed to find that is popular is the esp8266, and that thing is definitely not for streaming anything.

Before anyone asks, yes, it is critical for it to work over wifi.
Has anyone done something like this? What gets the best results?

title: Looking for help with WiFi modules

Answers: 1

body: I cant comment so I'm going to post as an answer.  Arduino is most likely not capable of running any sort of audio unless you have an mp3 shield to support it.  As far as the wifi module, I suggest using Ethernet shield as that will run a lot better compared to wifi module.


body:
I am from a mobile development background and very new to Arduino. I am trying to make an electronic cricket score board. The logic is simple.

**Score - 888 (3 Digits)** - I have implemented this logic using shift registers.  Three pin used from Arduino Uno and this is working fine.

**Overs - 88 (2 Digits)** - Need to find a best way to implement it

**Wickets - 8 (1 Digit)** - Need to find a best way to implement it

Now I need to add Wickets and Overs to the logic. I think there are two ways to do it.

1.  One is passing data from Score shift registers. I think this way is a bit complicated in logic level. But if this is a good way, then great.

2. The other is, connect to Arduino Uno pins directly rather than getting information from score shift registers.  There are only few pins.

***Please Note: I need to print this design in PCB***

This might be a basic question. But I would like to the know which way is efficient, and its advantages. If both are not, I would like to the know the best one.

title: Best way to implement score board logic using Arduino and Shift Registers?

Answers: 2

body:
You could use a 16x2 LCD to display the information; then you wouldn't need so many separate lines from the Arduino, the PCB would be simple and compact, etc.

However, if you need a big high-power display that is not multiplexed, you could use one 74HC595 per digit, assigning one bit per segment with 7-segment LED displays, with a driver transistor on each output.

The six '595s would be in series, which would use only two output lines from the Arduino: clock and data.

Another approach is to build your display from 84 or 126 WS2811 or WS2812B LEDs (2 or 3 per segment, and 7 segments times 6 digits).  About $10 to $15 on Ebay.  This would use one data pin from the Arduino to drive the whole display and would supply bright RGB light.

body:
There isn't really a *best* way (and such questions are usually discouraged as they can easily descend into argument).

Personally I would go for chaining all of the '595s together so you only ever use the 3 pins; it gives you the opportunity to use a smaller MCU like the ATtiny when you put it all on a board later which makes it (slightly) cheaper and (potentially) smaller.

From a software point of view, it doesn't make a huge amount of difference - doing it the way I have suggested means you send the 3 values out in the correct order every time one of them updates. Separating the 3 scores with their own dedicated pins means juggling which one needs to be updated each time. Neither option is particularly complicated and with this sort of application efficiency of code is mostly redundant because the entire MCU is dedicated to the (simple) task.


body:
I recently bought the LinkSprite color jpeg camera:
https://www.sparkfun.com/products/12804
And the Arduino Wireless SD Shield:
https://www.arduino.cc/en/Main/ArduinoWirelessShield

I was wondering how to connect the camera to the Arduino and how to have it take and save a picture to the sd card when a button is pressed.

title: Connecting and Programming LinkSprite Camera to Arduino

Answers: 1

body:
Connect the camera to a serial port (hardware or software serial depending on Arduino board). See further information on [wiki][1].

Control the camera and fetch the image over the serial connections (see commands) and write to the SD disc.

  [1]: http://linksprite.com/wiki/index.php5?title=JPEG_2M_Pixel_Color_Camera_Serial_Interface(TTL_level)


body:
Can anyone assist me with read/write to a SD shield. I am using a arduino along with a SD shield (POD  uSD) I am using a ultrasonic sensor to measure a distance, it has a safety factor in it. It also measures the time a measurement was taken, I now need to save the data from the serial monitor to a file and send that file to a SD card. I cannot seem to solve the saving a file part along with the SD shield

I have wrote my code but can seem to implement the shield along with my code, I want to store my data onto a file on the SD card. I've reviewed the example provided in the library's but it won't work for me

My code is;

<!-- language: c -->

    #define redled 10
    #define greenled 11
    #define echoPin 12
    #define trigPin 13

    unsigned long interval=60000; //interval = 60 seconds
    unsigned long previoustime=0;
    int minutes = 0; //global variables

    void setup() {
      Serial.begin (9600); //Set Baud rate to 9600 to match serial monitor
      pinMode(trigPin, OUTPUT);
      pinMode(echoPin, INPUT);
      pinMode(greenled, OUTPUT);
      pinMode(redled, OUTPUT);
    }

    void loop() {
     //-----------------------------------------------------------
      unsigned long currenttime = millis(); //counts time in milliseconds and puts it into current time
      if ((currenttime-previoustime) >= interval) { //When time is greater 60 seconds
        previoustime = currenttime; //Make the previous time equalled to the minute to take away in the next if statement        **Time since start section**
        minutes = minutes + 1; //Add 1 minute
      }
      unsigned long time = (currenttime-previoustime) / 1000; //converts the milliseconds to seconds
      //-----------------------------------------------------------
      long distance = ultra_sensor(); //call function that now returns the distance
      //-----------------------------------------------------------
      if (distance < 4) {            // If distance is less than 4cm
        digitalWrite(redled,HIGH);   // Turn on Red LED
        digitalWrite(greenled,LOW);  // Turn off Green LED
      }
      else {                          //If distance is greater than 4cm
        digitalWrite(redled,LOW);     // Turn off Red LED
        digitalWrite(greenled,HIGH);  // Turn on Green LED
      }
      //-----------------------------------------------------------
      if (distance >= 200 || distance <= 0){
        Serial.println("Out of range");
      }
      else {
        Serial.print(distance);
        Serial.print("cm");
        Serial.print(" after ");
        Serial.print(minutes);              //Printing distance and time to serial monitor
        Serial.print(" minutes ");
        Serial.print("and ");
        Serial.print(time);
        Serial.println(" seconds");
      }
      //-----------------------------------------------------------
      delay(2000); //Get reading every 2 seconds
    }

    long ultra_sensor() { //Ultrasonic sensor reading is now a function. More efficient
      digitalWrite(trigPin, LOW);  //Set Trigger to idle
      delayMicroseconds(2); //Wait 2 microseconds
      digitalWrite(trigPin, HIGH); //Set Trigger to high which sends out a wave
      delayMicroseconds(10); //Send the wave for 10 microseconds
      digitalWrite(trigPin, LOW); //Turn the trigger to idle
      long duration = pulseIn(echoPin, HIGH); //make duration the wave that echo recieves back
      long dis = (duration/2) / 29.1; //divide by 2 for going there and back.                         ***Speed of sound***
      return dis; //Send the distance to function call
    }

title: arduino SD card saving to file

Answers: 1

body: Looks like your sketch (pin usage) is in conflict with the SD shield (SPI pins). Try using other pins.


body:
here is what I got:

* teensy++ 2.0 with code below
* Glediator configured for Glediator_Protocol/Single_Pixels/HL_TL/RGB/B_1000000
* led matrix with the PL9823 leds (80 of them)

I first off have to set the code to 160 on the teensy just to get it to                     at least make the leds change. even when i have it set to that OR the 80 leds, it does not show what is on screen (see video below). I have no clue what to try next.

Code

    #include "FastLED.h"
    #define NUM_LEDS 160
    const int dataline = PIN_B4;
    CRGB leds[NUM_LEDS];

    void setup()
    {
        digitalWrite(6,LOW);
        Serial.begin(1000000);
        LEDS.addLeds<WS2812B, dataline>(leds, NUM_LEDS);
        for (int p=0;p< NUM_LEDS;p++)
        {
            leds[p] = CRGB::Black;
            FastLED.show();
        }
    }

    int serialReadBlocking()
    {
        while (!Serial.available())
        {
        }
        return Serial.read();
    }

    void loop()
    {
        while (serialReadBlocking() != 1)
        {
        }
        for (long i=0; i < NUM_LEDS; i++)
        {
            leds[i].r = serialReadBlocking();
            leds[i].g = serialReadBlocking();
            leds[i].b = serialReadBlocking();
        }
        FastLED.show();
    }

https://www.youtube.com/watch?v=H6OuMWKtbmo

title: glediator + PL9823 (WS2812B) + teensy = fail?

Answers: 1

body:
G'day Guy, What you're building there looks nice. Do you have a circuit diagram you can share? Regarding the code, I've never played with `FastLED.h` but is the `serialReadBlocking` how it deals with the input data? Not that it's wrong, just not what I was expecting.

Two things to look at:

 1. Your serial baud rate is a bit odd, 1 million neat. Is that intended? I wouldn't think so. Most common is 9600, I have run projects at 19,200 for giggles, but I doubt that you have it correct there.

 1. I see your project you are using multi coloured LEDs with 3+1 pins which in actual fact means you have 240 LEDs (are the last 80 segments/colours all lighting?). If your PC sending the serial stream is expecting 80x single colour LEDs (80 individual LEDS) but you've got 80x tri-colour LEDs (80x3=240 LEDs) you probably aren't lighting them all up. (I only mention this point because I noticed your PC appeared to be sending only one colour, but that could have just been the moment I saw in the video).

edit: I meant to include this link for the teensy serial baud rate info: https://www.pjrc.com/teensy/td_uart.html


body:
Scenario: I would like to monitor my closet's door as I highly suspect a family member is opening and using my items without permission. To respect privacy and also because my closet is nowhere near a power mains, I don't need video nor audio recording. I also do not need indicator lights etc because I intend to turn it on when I go to work and check the logs on the SD card when I return home. A typical day would require the device to run for 12 hours minimally.

Aim: Is it possible for Arduino to achieve the following,

1. Run on batteries for at least 1 month

2. Detect motion

3. Logging the detection motion onto a text file in a SD card

Or do I have to look elsewhere for this functionality?

Current understanding: I am aware Arduino can run on batteries though I've never been able to get it to last more than 3 hours. Probably has to do with me not using the low power mode or something and that my batteries were being stepped up. I also know that Arduino has some PIR motion sensors though I don't quite remember how power hungry these sensors are. I have NEVER tried logging onto an SD card using Arduino. This sums up my experience with Arduino.

Any advice would be much appreciated. Thank you.

title: Low power + Logging motion detection

Answers: 4

body:
It is possible to modify an Arduino Pro Mini (clone or original) to less than 1 mA and give at least a month on standard batteries (1000 mAh). Basically you need to remove the Power indicator LED and use low power mode in the sketch.

You could start simple by just lighting a LED when motion is detected and add the SD log later.

There are several techniques to detect motion. Advanced accelerometers such as [ADXL345][1] but also simple [wire sensing][2]. The standby power requirements for these have a large variation.

  [1]: http://www.analog.com/en/products/mems/mems-accelerometers/adxl345.html
  [2]: http://www.interlogix.com/intrusion/category/wired-sensing

body:
For low-power, just some tips (link references)

https://github.com/petervojtek/diy/wiki/Arduino-with-Very-Low-Power-Consumption

claim the below results,

    LED off, without the JeeLib library: 6.7 mA
    LED on, without the JeeLib library: 8.8 mA
    LED off, with the JeeLib library: 43 uA (!)
    LED on, with the JeeLib library: 2.2mA

https://github.com/petervojtek/diy/wiki/Arduino-with-Very-Low-Power-Consumption

Detailed step by step tutorial.

For sensing PIR will depend on exact components; using SMD low-leakage components will do the trick but cost would increase. There are very-low-power RTC on the market and maybe SD logging will be more difficult as can consume up to 200 mA per reading/writing operations.

body: The PIR sensors are actually pretty cheap: http://www.ebay.com/itm/like/171338717482?ul_noapp=true&chn=ps&lpid=82

body:
You would be better off with a bare ATmega chip than an Arduino - you want to eliminate extraneous circuitry like a USB converter, regulators with quiescent current draw, and any resistors pulling signals against their usual state.  Fortunately the ATmega chip has a fairly wide voltage range, especially at 8 MHz or below, so you can use something like 3 cells, alkaline or rechargeable, over most of their range.

An SDcard is neither necessary, nor a good idea.  If your circuit won't be discovered you can probably hold the data in static ram while the ATmega sleeps; if not, the quantity of data would probably not exceed the on-chip EEprom and would certainly not exceed that of a 4 megabyte SPI flash. Either of these will be far more robust (and low power) in a battery powered situation than an SD card.  They will also be simpler to support in software.  Either an SPI flash or an SDcard will probably have a narrower supply range the the ATmega and require a regulator - you may be able to enable that only when you need to access the memory.

Your main power consumption win however will be sensors.  If you can use a contact sensor - either a direct switch, or a magnetic reed one, that will result in the lowest power consumption.  Your next option might well be an accelerometer chip, specifically if you choose one which can run in a micropower mode and fire a wakeup interrupt to the MCU when it detects that a door it is mounted on is being opened.  Anything with light is likely to have much higher power consumption and could well be impractical, unless you figure out how to operate it in short bursts with a lengthy inactive time in between.


body:
I have the following script which checks if the user has pressed the numbers "770" or "769" continuously in the remote. The script works fine and displays all numbers. When I press the buttons "770" or "769" continuously the function powerOff() is called and I get no serial input.

    /*
     * IRremote: IRrecvDemo - demonstrates receiving IR codes with IRrecv
     * An IR detector/demodulator must be connected to the input RECV_PIN.
     * Version 0.1 July, 2009
     * Copyright 2009 Ken Shirriff
     * http://arcfn.com
     */

    #include <IRremote.h>

    int RECV_PIN = 11;

    IRrecv irrecv(RECV_PIN);

    IRsend irsend;

    decode_results results;

    int intValue;
    String strValue;
    String str3;

    void setup()
    {
      Serial.begin(9600);
      irrecv.enableIRIn(); // Start the receiver
    }

    void loop() {
      if (irrecv.decode(&results)) {
        intValue = results.value;

        Serial.print("Integer value : ");
        Serial.println(intValue);

        strValue = String(intValue);
        Serial.print("String str : ");
        Serial.println(strValue);

        Serial.print("Length : ");
        Serial.print(strValue.length());
        Serial.println();

        if(strValue.length() <= 1){
          str3 += strValue;
          Serial.println(str3);
           // Receive the next value
       }

        delay(200);
        irrecv.resume();
      }
      //Serial.println(str3);
      if(str3.endsWith("770")){
        powerOff();
        str3 = "";
      }
      else if(str3.endsWith("769")){
        powerOff();
        str3 = "";
      }

      else{}
      //powerOff();
    }

    void powerOff(){
        irsend.sendRC6( 0xC0000C, 24);
        irrecv.resume(); // Receive the next value
    }

title: Script stops functioning after calling irsend() function in irlibrary!

Answers: 1

body: Apparently you should be calling `irrecv.enableIRIn()` after sending, not `irrecv.resume()`. Sorry for suggesting the wrong thing on IRC before :-)


body:
I'm using minIMU-9 https://www.pololu.com/product/1268 and I want to read pitch, roll and yaw angles. I applied this library https://github.com/pololu/minimu-9-ahrs-arduino but there is a slope when sensor is not moving or vibrating. How can i fix or compensate this. The y axis is angle in degree and x axis is time in seconds

Pitch

[![Pitch][1]][1]

Roll

[![Roll][2]][2]

Yaw

[![Yaw][3]][3]

  [1]: https://i.stack.imgur.com/Us5BU.png
  [2]: https://i.stack.imgur.com/9oRC2.png
  [3]: https://i.stack.imgur.com/dzEgx.png

title: minIMU 9 and Arduino reading Gyro angle

Answers: 1

body:
I suppose "at desktop readings" means you have your sensor resting on the desktop so you where looking for a constant output value over the time. Well, there are some mechanical limitations about gyroscope's accuracy, resolution and external factor like temperature that make noisy or non-sense readings.

What you are obtaining from this library is a calculated orientation that carries or accumulate an error over time. Basically there is not a perfect algorithm to calculate orientation as at MEM's scale electrons still moving due to temperature and other radiations.

Solution depends on your application scenario: if your sensor will be most the time quite, maybe just mathematical compensate with inverted slope (about 4-5 degrees per minute) and look for more rapid changes to determine movement. If your application will be on constant move maybe it is not required any compensation. Trade off must be considered if both scenarios will take place on your application. Anyway, reading measures on your actual application will give you more clue on how to handle this.

Below the L3GD20's mechanical characteristics

[![Gyro's mechanical characteristics][1]][1]

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


body: is there any way I can run an MG2639 GPS Cellular Shield (the one SparkFun makes) on an Arduino Uno for GPS tracking purposes? It seems whether I use New or AltSoftSerial, the unit just can’t read what’s streaming in through from the GPS on the 115200 baud rate, which the shield is hard-wired to.

title: MG2639 & Arduino Uno not GPS-ing?

Answers: 1

body:
Try sending a command that sets the GPS baud rate to something a little lower:

    altss.write( F("$PMTK251,38400*27\r\n") );
    altss.end();
    altss.begin( 38400 ); // change to match above command

Are you sure you're having trouble *reading*, because there are many other things you may be doing in your sketch that cause input buffer *overflow*.  Please post your code and some sample output for us to examine.  It may be failing for a different reason.

For example, you may just be losing data because you're trying to do too many things in `loop()`.  Please take a look [here](https://github.com/SlashDevin/NeoGPS/blob/master/doc/Troubleshooting.md#trying-to-do-too-many-things).

To solve this kind of problem, I have posted a modified version of `AltSoftSerial` on github, [here](https://github.com/SlashDevin/NeoICSerial), that let you process GPS data in the background (i.e., during interrupts).  When coupled with [NeoGPS](https://github.com/SlashDevin/NeoGPS), it can save you quite a bit of program space, RAM and execution time.  There is an interrupt-driven example [here](https://github.com/SlashDevin/NeoGPS/blob/master/examples/NMEA_isr/NMEA_isr.ino).  Just change which include is uncommented on lines 30-31:

    #else
      // Only one serial port is available, uncomment one of the following:
      #include <NeoICSerial.h>
      //#include <NeoSWSerial.h>
    #endif
    #include "GPSport.h"

...and the baud rate below, on line 140:

      // Start the UART for the GPS device
      gps_port.attachInterrupt( GPSisr );
      gps_port.begin( 115200 );
    }


body: I have a home automation project and am looking to use multiple current sensors (ACS712) for multiple appliances. I just need to know whether current is present or not instead of the current value. Is it possible, that I connect the ACS712 sensor to the digital input of Arduino, and get HIGH or LOW via `digitalRead()` function. If not, please suggest an alternative to detect ac current is present or not with digital input i.e. HIGH or LOW that can be read via the `digitalRead()` function.

title: Can you connect ACS712 sensor to digital input of Arduino?

Answers: 4

body: Use a comparator for an adjustable threshold and feed the output into the arduino digital pin.

body:
Considering an ATMEGA with a 5V VCC we have:

    LOW  = < 0.3*VCC = 0,3*5V = 1.5 V
    HIGH = > 0.5*VCC = 0,5*5V = 2.5 V

You can connect directly to the Arduino if the output of your sensor is higher than 2.5 volts whether current is present or below 1.5 volts if not. This would translate to HIGH or LOW output from `digitalRead()` function respectively.

You need to recalculate this values for the 3 volt version of Arduino, probably in this case is better the comparator solution to ensure up to 3 volts max logic level.

Example circuit as follow, just need to set voltage divider to desired threshold (note this is for 5v case),

[![Comparator][1]][1]

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

body: It seems like you could do this with a transistor (if "faking" a digital signal from the ACS712 doesn't work). A simple circuit where the VIOUT of the ACS712 drives the base of a switching transistor connected to a digital pin on the Arduino with an internal pull up might do the trick (assuming that the ACS712 give you a voltage on VIOUT that is proportional to the current).

body:
The Arduino/AVR (for instance [ATmega328p, chap. 22][1]) has an analog comparator (D6/AIN0, D7/AIN1 or any analog pin). This could be used with the correct reference voltage.

Cheers!

  [1]: http://www.atmel.com/images/doc8161.pdf


body:
Is there a high-quality (32 bit/96,000 kbps) digitizer for Arduino?

Does anybody know where I can find the best options for this?

title: Where can I get a high-quality ADC (audio digitizer) for Arduino?

Answers: 2

body:
You are going to need a bigger board.

(96000000 samples/second) * (32 bits / sample) ~= [3 Gigabits/second][1]

A poor little Arduino Uno only runs at 20MHz and can process 8 bits bytes at a time, so even if it could somehow read and store a byte every cycle, it would still be orders of magnitude too slow for your purposes.

While I guess is might be possible to build a shield with an ultra high speed ADC and on board memory to directly store the captures samples to, you probably would bother making it since the Arduino would struggle to do anything useful with the captured data even after the fact.

The highest quality audio recording shield for Arduino I've seen is a modified [Wav Shield][2] that can record 8-bit mono files at 44,100 samples per second using the [waverp library][3].

  [1]: http://www.wolframalpha.com/input/?i=(96000000 sample/second) * (32 bits / sample)
  [2]: http://www.adafruit.com/products/94?&main_page=product_info&cPath=17_21&products_id=94
  [3]: https://blog.adafruit.com/2009/07/07/waverp-an-arduino-library-for-recording-and-playing-wave-files-on-the-adafruit-wave-shield/

body:
 think 96000kps was most likely a typo. 96ksps or 96000sps is more likely since the title specifies audio. Still a little too much for an Arduino though. You need a chip with I2S and a CODEC chip.

I am working on a project at the moment interfacing a PIC32 to a CODEC for CD quality audio reproduction. The codec I am using (PCM1774) is DAC only, but you can get CODECs in many combinations of ADC and DAC with different numbers of channels in each.

I2S is very similar to SPI but needs some extra facilities that not all chips can provide. Things like:

* High speed flexible base clock at (for example) 256x the sample frequency
* Left/Right framing clock derived from base clock
* DMA for smooth transfer of data

I don't know what offerings Atmel have, but for PIC32 you need one of the more modern chips, such as the PIC32MX1xx/2xx family, PIC32MX470, or for high end work the 200MHz PIC32MZ chips.

The MX1xx/2xx and MZ chips are available in a Arduino-like system called chipKIT which might suit your needs better than small Atmel chips.

The Arduino Due might also be able to do I2C but I won't be able to help you with that since I have relegated my Due to the bittom of my junk pile.


body:
I am trying to figure out how to get 2 Arduinos to talk back and forth from one another using cheap simple RF modules. I have a total of 4 RF modules (2 receiver and 2 transmitter) and 2 Arduinos. I need Arduino A to send about 3 variables to Arduino B, and I need Arduino B to send 1 variable back to Arduino A.

When I attempted 2 way communication, I programmed Arduino A to broadcast constantly, while having Arduino B trade off between receiving once, then sending once on every other loop. This resulted in Arduino B also only broadcasting, and was not receiving any signal from Arduino A.

My other attempt was to have Arduino B send for about 250 ms, then receive for 250 ms, and repeat. This worked as long as Arduino A was only broadcasting, but as soon as I had Arduino A doing the same thing, the clock on each seemed to be slightly off and there would be periods where both Arduinos were sending, or where both were trying to receive, so it was also very unreliable.

Is there a reliable way to do two way communication with this kind of hardware, or would I need transceivers to do this kind of project?

title: 2 way RF with Virtual Wire / 315 / 433 MHz

Answers: 2

body:
If the RF Modules you are mentioning are the ones I am thinking of they do seem to be very special bits of kit.  I have tried Bluetooth you can get cheap HM05 modules (Might be the wrong number you want the one that can be the master or slave).  These were a bit better but don't have the range.
My personal fav at the moment would be a ESP8266, no I have never hooked one up to an Arduino, but it can be done fairly easily.  You should get 100m range (in ideal circumstances) and you can get aerials to boost that.  You can also set one up as a repeater between two wifi segments.

Whatever you decide you might want to change your code slightly so that one Arduino sends a time signal and the other doesn't send its data until its turn.  Or give them GPS receivers and pull the time from there.

body:
With VirtualWire, an Arduino can only send, or only receive. It can't do both at once. It is basically like software serial, but with Manchester encoding of the message.

Write your code for the sender to send once, and then listen for a response.
If no response after some interval, try sending again, and then go back to listening.
Perhaps try one more time.

Write your code for the receiver to always be listening, and not reply until a message is received.
Add some code to indicate when a good message is received as an aid to debugging.

You should be able to connect Tx to Rx and Rx to Tx (and Gnds) between the two Arduinos and get the sequence to work back and forth, and then connect the RF modules and have them work as well.

I think the encoding done by Virtual wire adds 37 bytes to the message, which the library takes care of, so the end result is only the data that was sent.

You might also try the RadioHead library, of which VirtualWire is one part now.


body:
 1. is it dangerous for arduino the below circuit because GND pin is common with -12V battery pole?
 1. is it dangerous for lots of 5v circuit to be grounded on -12v battery pole?
 1. in case i don't connect GND arduino pin with -12v , does arduino works?
 1. in case that 1,2 question is dangerous for arduino,does it safe if a connect a diode at P1 mark?

[![enter image description here][1]][1]

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

title: Supply arduino through Vin pin with a battery

Answers: 1

body:
Voltages, being a *potential difference* are always measured relative to another voltage.  Normally that reference voltage is referred to as *ground*, though may not always be.

The + and - on the battery refers to the *polarity of the battery* not the *polarity of the voltage*.

For instance, *relative to the - terminal* the positive terminal is 12 volts higher, or +12V.  *Relative to the + terminal* the negative terminal is 12V lower, so -12V.

When one of your battery terminals is connected to a point in your circuit nominated as ground (the - terminal of your battery in this case) then your battery voltage at the + terminal is measured relative to ground, which we say is 0V.  So the + terminal is 12V higher than the - terminal, and the - terminal is 0V, so therefore the + terminal must be 12V *with respect to ground*.  The - terminal, since it is connected to ground is at the same voltage as ground, so it is 0V *with respect to ground*.

If you were to connect the + terminal of a battery to ground instead, then the - terminal would be 12V *lower* than ground, so would be -12V *with respect to ground*.  The + terminal would be 0V *with respect to ground*.


body:
At first, I tried to make whole code for an RC car and remote controller, but I realized that it's difficult for me since I have few ideas about C++. So, I changed a few things like turning on the LEDs with switches and servomotors with potentiometer. Here are my code.

**Remote controller**

    #include <SoftwareSerial.h>

    SoftwareSerial BTSerial(2,3);
    int sw1=13;
    int sw2=12;

    void setup() {
      BTSerial.begin(9600);
      Serial.begin(9600);
      pinMode(sw1, INPUT_PULLUP);
      pinMode(sw2, INPUT_PULLUP);
    }

    void loop() {
      int a = analogRead(A0);
      int map_a=map(a,0,1023,0,255);
      int state1=digitalRead(sw1);
      int state2=digitalRead(sw2);

      BTSerial.print('S');
      BTSerial.print(map_a);
      BTSerial.print(',');
      BTSerial.print(state1);
      BTSerial.print(',');
      BTSerial.print(state2);
      BTSerial.print('E');
      delay(100);
    }

< RC CAR >

    #include <SoftwareSerial.h>

    SoftwareSerial BTSerial(2,3);

    byte buffer[255];
    int bufferPosition;

    void setup() {
     BTSerial.begin(9600);
     Serial.begin(9600);
     bufferPosition=0;

    }

    void loop() {
      {
        if(BTSerial.available()>0){
        unsigned char data = (unsigned char)BTSerial.read();
        buffer[bufferPosition++]=data;
        Serial.println(data);
        delay(100);
        }
    }
    }

When I checked the result from `Serial.println(data)` from RC car code,
it was trash...

Can you instruct me what's wrong with this code?

title: I'd like to make RC car and remote controller via bluetooth (HC06)

Answers: 1

body:
There are some fundamental problems in the code - `bufferPosition` never stops increasing (until it reaches 32768) and so `buffer` will overflow. However, neither of these two problems are causing the 'trash', as you are outputting the result of reading the serial, not anything from the buffer.

The problem lies in the casting of the result from `BTSerial.read()` to `unsigned char`.

`Serial.print()` does not like this. Actually it doesn't care, but it won't give you what you expect. It just prints out the value stored - so 'a', which is 97, will come out as '97' on the serial monitor. `Serial.print()` only outputs ASCII characters when you give it a `char` or `char[]`.


body:
The command line that my toolchain ([CLion][1] + [PlatformIO][2]) uses to program my Arduino (Uno) includes includes

    avrdude ... -c arduino ...

but [the documentation][3] for this programmer simply reads

> -c programmer-id
>          ...
>         arduino           Arduino
>          ...

What does the `arduino` programmer do. Does it just correspond to using the bootloader?

  [1]: https://www.jetbrains.com/clion/
  [2]: http://platformio.org/#!/
  [3]: http://www.nongnu.org/avrdude/user-manual/avrdude_4.html

title: What does the 'arduino' avrdude programmer do?

Answers: 1

body:
Yes, the -c option specifies the methods of interacting with the device's loader.

The source code of the arduino programmer is http://svn.savannah.nongnu.org/viewvc/trunk/avrdude/arduino.c?root=avrdude&view=markup

Specifically, '-c arduino' chooses the client side code tailored to the bootloader in the Arduino Uno.  Looking at the code in the above link, it tweaks the DTR and RTS lines to get the Ardunino into an stk500 compatible mode, and then invokes the stk500 protocol.


body:
Please help me find a way to do it.

I have looked at the following for sending data [Arduino to MySql][1]

  [1]: http://www.instructables.com/id/PART-1-Send-Arduino-data-to-the-Web-PHP-MySQL-D3js/

But can't seem to find visa-versa.

title: I would like to retrieve data from a MySQL database using PHP using HTTP requests, on my Arduino

Answers: 2

body:
There are two things you have to set up for this:
1. Retrieving/parsing websites from your Arduino.
2. Making a dynamic website using PHP (and MySql).

- Try to set up your Arduino as a [WebClient][1], check if you can retrieve a website like google.com or [a minimalistic website][2].
- Try to get your arduino to interpret a string or retrieve values from that website. (I.E: retrieve the day/time from the HTTP message)

IF your arduino can retrieve webpages, you're halfway there (somewhat). And your project is running out of the scope of this arduino.stackexchange.

Now you're going to have to [create a dynamic website][3]. You can let PHP reach for values from your MySql database (you should just use a text file first) and display them on your site (in HTML).
Your Arduino can now poll your website, to get the HTML content and parse it to the values.

  [1]: https://www.arduino.cc/en/Tutorial/WebClient
  [2]: http://www.minimalsites.com/
  [3]: https://www.google.nl/webhp?sourceid=chrome-instant&ion=1&espv=2&es_th=1&ie=UTF-8#q=dynamic website php mysql&es_th=1

body:
You could develop a REST based service, to make Arduino consume web service using the [aRest][1] library.

Following is a tutorial of how to use the aRest API with Arduino: [A REST API for Arduino & the CC3000 WiFi Chip][2].

  [1]: https://github.com/marcoschwartz/aREST
  [2]: https://learn.adafruit.com/a-rest-api-for-arduino-and-the-cc3000-wifi-chip?view=all


body:
I am currently working on a photo-transistor like this:
http://www.ebay.com/itm/10pcs-ITR8307-S18-TR8-Optical-Switches-Reflective-Phototransistor-Output-/381374566327?hash=item58cbb20fb7:g:lgoAAOSwr81UQ7KG

It very nicely allows me to identify colors white, green and black. The problem I am having is that the Arduino is powered with batteries so the readings for those colors change as voltage in the batteries reduces.

I tried to make the reading proportional to the voltage in the system, but this still gives different values, I guess the readings change non-linearly as voltage changes.

I wonder what will be the solution to this problem: Specifically, how to make the reading of an IR sensor the same for the same color at different voltages?

This is the code I am using so far:

    void setup() {
    // initialize serial communication at 9600 bits per second:
    Serial.begin(9600);
    }

    void loop() {
    // read the input from the IR sensor on pin A0:
    float sensorValue = analogRead(A0);
    // read the voltage in the system by connecting pin A1 to Vcc, with the same resistor value used in the IR sensor:
    float Vref = analogRead(A1);

    // adjust reading value to voltage in system:
    float AdjustedReading = sensorValue/Vref;

    Serial.println(AdjustedReading);
    delay(100);
    }

title: IR sensor readings at different voltages

Answers: 1

body:
It sounds to me like your system works, but you have trouble if your voltage drops.

First of all here's 2 tips that might solve your problem.

1. instead of just making 1 reading do 10 and take an average - this reduces noise.

2. the voltage reference is allready based on the voltage that powers the system so with your adjusted reading you try to accomplish something which has already happened an therefore has the opposite effect and actually increase the error.

see http://tronixstuff.com/2013/12/12/arduino-tutorials-chapter-22-aref-pin/ for a very good explanation.

3. Add a RC filter to removes random fluctuations in the signal from you photoresistor

see https://electronics.stackexchange.com/questions/17754/where-to-place-a-capacitor-to-smoothen-ir-sensor-reading for a short description and the calculated example.

If however it is correct, and your readings of colors don't follow a linear scale, you would have to deduce that actual curve and apply it in the code - but that might not be easy.

So it would be much more easy to remove that variable by ensuring that the voltage is constant. Most Arduino boards have an 5V onboard voltage regulator that will keep the voltage exactly at 5 Volt when connected to battery via the **power Jack!**

*(USB bypasses this regulator and have a little voltage drop so it is sligthly lower than 5V, and more very prone to fluctations if coming from a AC source affecting your analog read considerably)*

The battery connected onboard voltage regulator however requires a higher input to do the regulation so the battery needs to supply atleast 6.2V or higher, in your case you would have to use a voltage source of less than 6.2V if this is the source of your problems.

*(the voltage regulator on original arduino boards needs voltage of 1.2V higher than the needed output - clones might differ and require upto 2v more than the needed output)*

hope this can help solve the issue

Mikael


body:
I want to make a clone of those radar enforcement signs that look like this:
[![enter image description here][1]][1]

I bought a Hot Wheels Radar gun that can send an analog signal to determine speed.  See this thread:  <http://forum.arduino.cc/index.php?topic=145063.msg1889312#msg1889312>

From FreqPeriod's documentation, it has the following comment in the code:

`connect pin 5,6,7 to input circuit`

Question is -- how do I wire up the radar gun analog signal wire to the arduino to successfully use FreqPeriod?

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

title: Using a Hot Wheels Radar Gun with FreqPeriod library

Answers: 0


body:
What is the easiest way to mount DS1307 to ethernet shield?

I tried to do this:
https://learn.adafruit.com/ds1307-real-time-clock-breakout-board-kit/wiring-it-up

but my program just freezes when I try to read data from RTC. Is there any other ways to do it?

Code looks like this:

    const int RTCpin2 = 2;
    const int RTCpin3 = 3;

    void setup() {
        pinMode(RTCpin2, OUTPUT);
        pinMode(RTCpin3, OUTPUT);

        analogWrite(RTCpin2, LOW);
        analogWrite(RTCpin3, HIGH);
    }

    void loop() {
         // process RTC time
    }

title: connecting RTC DS1307 to ethernet shield

Answers: 1

body:
I assume that snippet of code is supposed to provide the +5Vand GND for powering the RTC module.  Well, there's two fundamental flaws with it:

1. Pins 2 and 3 are the DIGITAL pins, not the analog pins. Instead you want to be using pins A2 and A3.
2. analogWrite controls the PWM output on pins that support PWM. HIGH is 1, so analogWrite will be providing a 1/255 duty cycle PWM signal on that pin.

So to fix it:

1. Use pins A2 and A3 instead of 2 and 3
2. Use digitalWrite() instead of analogWrite().


body:
Well I've just started learning the concept of multithreading with C++ and immediately a bunch of questions came to mind about the possibility of using multithreading with microcontrollers in general and Arduino specifically.

So, is it possible to use multithreading on any type of Arduino boards?

title: Multithreading with Arduino

Answers: 4

body:
The really quick answer is "maybe" – it depends on what you mean by "Arduino" and what you mean by "thread." The answer is likely to be different for the AVR based Arduinos (Uno et al.) vs. the ARM based Arduinos (Due et al.) – I would expect there to be much better hardware support for "real" threads on the ARM processors. Another question you'd want to answer is "why threads?" Do you want the abstraction to help you organize your code? Or do you actually need "real" threads?

Before there was hardware thread support (e.g., the mid-80s) there are user thread implementations, it seems possible that they might be adaptable to run even on an AVR. I would expect it to be something of a project.

There is a threads package called [Protothreads][3] which may be interesting. The description says "Protothreads are extremely lightweight stalkless threads designed for severely memory constrained systems." I found [another question asking about simple usage][4] of Protothreads, so it seems that you may find some other users of the package.

You may also find some useful information in this Stack Exchange [question on threads][1], a quick search for "C user threads" found [this implementation][2] on the first page – and I'm sure there are many more.

A search on "Arduino threads" found several more interesting looking links:

* https://arduino.stackexchange.com/questions/286/how-can-i-create-multiple-running-threads
* [Arduino Thread package on GitHub](https://github.com/ivanseidel/ArduinoThread)
* http://www.kwartzlab.ca/2010/09/arduino-multi-threading-librar/
* http://forums.trossenrobotics.com/showthread.php?5923-Multithreading-(Parallel-loops)-on-an-Arduino

If you just want threads, a small and inexpensive board, and I/O pins it might be worth considering a Raspberry Pi – Linux has thread support.

[1]: https://stackoverflow.com/questions/9145321/implementing-a-user-level-threads-package
[2]: http://homepage.cs.uiowa.edu/~jones/opsys/threads
[3]: http://dunkels.com/adam/pt
[4]: https://arduino.stackexchange.com/questions/12411/arduino-protothreads-by-example

body:
In [Cosa][1] you can find the following support for concurrent programming:

 1. [Events][2], interface interrupt service routines
 2. [Jobs][3], delayed, [periodic][4] or [alarm][5] functions with us, ms and seconds level timers (Watchdog, RTT or RTC).
 3. [FSM][6], object-state function
 4. [ProtoThreads][7], object-state pointer
 5. [Threads][8], Semaphores, etc, multiple stacks
 6. [UML][9] Capsules and Connectors, dependency driven programming

There are plenty examples on how to use these. A good starting point is the [Blink][10] sketches. There is even a [multi-threading Blink][11] example with a thread that does the LED on/off and a controller thread that periodically changes the blink period. The thread stack size is only 64 bytes and it runs even on an ATtiny.

With all the AVR internal hardware modules (such as SPI, TWI, UART, etc) there is plenty of opportunities for concurrency.

A [Scheduler][12] library for the Arduino core is also available. This is a port of the Cosa Threads. Please see github for further details.

Cheers!

  [1]: https://github.com/mikaelpatel/Cosa
  [2]: https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/Event.hh
  [3]: https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/Job.hh
  [4]: https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/Periodic.hh
  [5]: https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/Alarm.hh
  [6]: https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/FSM.hh
  [7]: https://github.com/mikaelpatel/Cosa/blob/master/libraries/ProtoThread/ProtoThread.hh
  [8]: https://github.com/mikaelpatel/Cosa/blob/master/libraries/Nucleo/Thread.hh
  [9]: https://github.com/mikaelpatel/Cosa-UML
  [10]: https://github.com/mikaelpatel/Cosa/tree/master/examples/Blink
  [11]: https://github.com/mikaelpatel/Cosa/blob/master/examples/Blink/CosaBlinkThread/CosaBlinkThread.ino
  [12]: https://github.com/mikaelpatel/Arduino-Scheduler

body:
There's one Arduino-like product that certainly could enable multi-threading, as it is multi-core: the [Shield Buddy TC275][1].

[![Core setup and loop functions][2]][2]

So basically you have three `setup()` functions, and three `loop()` functions. True multi-threading.

  [1]: https://www.rs-online.com/designspark/bringing-multicore-to-the-arduino-world-with-shieldbuddy-tc275
  [2]: https://i.stack.imgur.com/RUu3B.jpg

body:
I use [Atomthreads][1] on Atmega128, it is very lightweight with minimum overhead. Have task scheduler, mutex, semaphores and queue. Code is portable but might require some configuration to use with Arduino IDE (I use Atmel Studio). I primarily use task scheduler, never had problems. Just checked, the development is still active.

  [1]: https://www.google.mn/url?sa=t&source=web&rct=j&url=http://atomthreads.com/&ved=0ahUKEwizhomMgsrRAhXMHZQKHV74DcAQFggYMAA&usg=AFQjCNGsxGMmrzZ5XhSCrSidilYeNhcdwg&sig2=EUhC4i0J711ypa5OhK2o7g


body: I'd like to buy new resistors for breadboarding with my Arduino Uno. There are 0.25W, 0.4W, 0.6W, 1W, 2W, 3W, 5W, 10W resistors in the shop. What is the most suitable for this operation?

title: What is the minimum wattage of resistors for breadboarding with Arduino Uno?

Answers: 3

body: The smaller the better for the most part. On 1/4 or 1/8 W resistors the leads size is small enough to work well in bread boards. Rarely do you need to dissipate large amounts of power so 1/8 is a good size for logic, maybe 1/4-1/2 for power supply areas.  See Majenko's answer for the heavy math, mostly applicable in power supply areas as he points out.

body:
The answer is: It depends what you want to use them for.

You need a wattage that is higher than the power it will dissipate. What that power is depends on what you are doing with them.  There are standard formulae that tell you the power in any given situation.

For instance, if you know the current and the resistance you can use:  P=I²×R. If you know the voltage across the resistor it's P=V²÷R.

Take as an example the common resistor for an LED.  Assume a 2V LED and a 220 ohm resistor. With a 5V total voltage the voltage across the resistor would be 5-2=3V. So the power would be (3²)/220 = 9/220 = 0.041W so you could quite happily use a 0.125w (⅛w) resistor for that job.

To be honest though most common Arduino jobs can be accommodated by ⅛W or ¼W resistors.  ¼W is better for breadboarding since the leads are fatter than ⅛W, but ⅛W can take two leads at once direct into an Arduino's headers. Also if you fold the leads in half and squash them with pliers they fit better.

body:
Go with 1/4 Watt resistors but be prepared to use 1/2 Watts if the leads don't press down cleanly into the breadboard which is what I think you are asking about. If you need anything in the higher wattage range and you are working with an Arduino, then you are doing it wrong. An Arduino could not smoke a 1/4 watt if it tried.

I have fought for years with our purchasing agent over this at the college I work for. He buys 1/8th watt resistor in bulk, but fails to heed the advice that you cannot use these on standard classroom breadboard without bending the leads at best and failing to even make a good connection at worst. You need reliable connections and 1/8th and smaller are useless on breadboards. Just my two cents from years and years of experience.


body: I just uploaded a sketch of a song to my Arduino and it works well.  Could I just take the chip out and hook up speakers to it and a power source to play the song? and just get another chip and put it in the Arduino.

title: Taking off the chip from Arduino

Answers: 2

body:
Yes and no.

To elaborate, the sketch you downloaded to the chip has been flashed to internal non-volatile memory. So if you were to move it to *another* Arduino board or other device with the appropriate support hardware, then it should work just fine.

However, if you're intending to directly hook-up speakers to it and a power source, then I highly doubt it's going to work. You really need some support hardware for the chip (such as an external clock - though I think the Atmega328 has an internal clock, decoupling capacitors, amplifiers for the spearkers, etc.).

body:
Easy part first: You CAN put another chip on arduino PROVIDED that chip already has a bootloader on it. If it's a raw chip, burn the bootloader on it first. [This guide will help](http://www.arduino.cc/en/Tutorial/ArduinoToBreadboard).

You CAN connect the programmed chip to speaker PROVIDED you add the minimal circuit components required for an arduino to run. These include - a 16 MHz crystal, two 22 pf capacitors and a 10K resistor. Use the schematic in the bootloader guide. That will work.

Besides this, you will require a 5V power source. You can alternatively use 3xAA cells (4.5V will work perfectly). Alternatively use a wall adapter of 7V or higher and use a linear regulator (7805) to generate a perfect 5V supply for your arduino. You will need this pin mapping diagram to connect the speaker to arduino once you take it out from the board:

[![enter image description here][1]][1]

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


body: I downloaded the Processing language and ran the "Hello World" program to test it. The message appears in the Serial console but not on the Processing console. It prints "null" only. I am using the code supplied by Sparkfun. Other people have had this problem. I am looking for clear explanation and solution.

title: Why won't processing not communicate with Arduino uno?

Answers: 1

body:
I apologize for presenting a vague question. I was unable to successfully run the simple code to learn "serial communication" presented by Sparkfun on: https://learn.sparkfun.com/tutorials/connecting-arduino-to-processing.

Step 1. Run Arduino to produce "Hello, World" on the Serial Port.
Step 2. Run Progressing 3.0.1 to produce "Hello, World" on its console.

The code from the website are copied and pasted onto my iMac running El Capitan. I received an error message for Step 2 stating the "port is busy."

Once I closed the Arduino (Step 1) and compiled and ran Step 2, it worked!

Several other people found different solutions. My solution is simple. Run one program at a time.