message:
Modbus slave data into word

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

I have simple code. The library downloaded from [github:smarmengol/Modbus-Master-Slave-for-Arduino][1].

I wanted to store floating point. In the code blow, I type casted to integer value. As I know `uint16_t au16data[30];` is integer

    #include <avr/wdt.h>
    #include"glob.h"

    #define ID   1
    int8_t state = 0;
    Modbus slave(ID, 0, 0);
    unsigned long tempus;
    // data array for modbus network sharing
    uint16_t au16data[30];

    void Take_Reading()
    {
      for(row=0;row<9;row++)
      {
      int k=(8*array[row][0]+4*array[row][1]+2*array[row][2]+1*array[row][3]);
        digitalWrite(Enablepin,array[row][0]);
        digitalWrite(SO_enable,array[row][1]);
        digitalWrite(S1_enable,array[row][2]);
        digitalWrite(S2_enable,array[row][3]);
       //delay(100);
        Sensor_Value0=analogRead(A0);
        Sensor_Value1=analogRead(A5);
       Mux1_array[row]=(Sensor_Value0 * ARDUINO_ANALOG_SCALING);
       Mux2_array[row]=(Sensor_Value1 * ARDUINO_ANALOG_SCALING);

       Current_Value1[row]=  (Mux1_array[row]*40)-98;
       Current_Value2[row]=  (Mux2_array[row]*40)-98;

      }
    }

    void setup()
    {
         wdt_enable(WDTO_8S);
       slave.begin( 9600 );
      tempus = millis() + 100;
      pinMode(3,OUTPUT);
      pinMode(SO_enable, OUTPUT) ;// pin can enable/disable using digital IO 7 of arduino
      pinMode(S1_enable, OUTPUT) ;// pin can enable/disable using digital IO 6 of arduino
      pinMode(S2_enable, OUTPUT) ;// pin can enable/disable using digital IO 5 of arduino
      pinMode(Enablepin, OUTPUT) ;// pin can enable/disable using digital IO 4 of arduino
      pinMode(A0, INPUT) ;
      pinMode(A5, INPUT) ;

    //  Serial.begin(9600);
    }

    void loop()
    {
      digitalWrite(3,HIGH);
    // wdt_reset();
     Take_Reading();
     state = slave.poll( au16data,30 );
      if (state > 4) {
        tempus = millis() + 50;
        digitalWrite(13, HIGH);
      }
      if (millis() > tempus) digitalWrite(13, LOW );

    Modbus_call();

    }

    void Modbus_call()
    {

    /*reading of coil where i can succefully read value*/
      au16data[0]=(int)Current_Value1[0];
      au16data[1]=(int)Current_Value1[1];
      au16data[2]=(int)Current_Value1[2];
      au16data[3]=(int)Current_Value1[3];
      au16data[4]=(int)Current_Value1[4];
      au16data[5]=(int)Current_Value1[5];
      au16data[6]=(int)Current_Value1[6];
      au16data[7]=(int)Current_Value1[7];
      au16data[8]=(int)Current_Value1[8];
      au16data[9]=(int)Current_Value2[0];
      au16data[10]=(int)Current_Value2[1];
      au16data[11]=(int)Current_Value2[2];
      au16data[12]=(int)Current_Value2[3];
      au16data[16]=(int)Current_Value2[4];
       au16data[17]=(int)Current_Value2[5];
       au16data[18]=(int)Current_Value2[6];
       au16data[19]=(int)Current_Value2[7];
     uint16_t calcCRC( au16data[15]);
         au16data[13] = slave.getInCnt();
      au16data[14] = slave.getOutCnt();
      au16data[15] = slave.getErrCnt();

     }

Conversion method as below.

    CS=30.10
    Int_CS=int(CS)
    FLOAT_CS=(Int_CS-CS)*100

How to store the `Int_CS` & `FLOAT_CS` values in `au16data[0]`??

---

I have change code accordingly.

[![Output file][2]][2]

But I get zero. After some time its values don't even show

    #include <avr/wdt.h>
    #include"glob.h"

    #define ID   1
    int8_t state = 0;
    Modbus slave(ID, 0, 0);
    unsigned long tempus;
    // data array for modbus network sharing
    uint16_t au16data[5];
    float auFloatData[30];
    void Take_Reading()
    {
      for(row=0;row<9;row++)
      {
      int k=(8*array[row][0]+4*array[row][1]+2*array[row][2]+1*array[row][3]);
        digitalWrite(Enablepin,array[row][0]);
        digitalWrite(SO_enable,array[row][1]);
        digitalWrite(S1_enable,array[row][2]);
        digitalWrite(S2_enable,array[row][3]);
       //delay(100);
        Sensor_Value0=analogRead(A0);
        Sensor_Value1=analogRead(A5);
       Mux1_array[row]=(Sensor_Value0 * ARDUINO_ANALOG_SCALING);
       Mux2_array[row]=(Sensor_Value1 * ARDUINO_ANALOG_SCALING);

       Current_Value1[row]=  (Mux1_array[row]*40)-98;
       Current_Value2[row]=  (Mux2_array[row]*40)-98;

      }
    }

    void setup()
    {
         wdt_enable(WDTO_8S);
       slave.begin( 9600 );
      tempus = millis() + 100;
      pinMode(3,OUTPUT);
      pinMode(SO_enable, OUTPUT) ;// pin can enable/disable using digital IO 7 of arduino
      pinMode(S1_enable, OUTPUT) ;// pin can enable/disable using digital IO 6 of arduino
      pinMode(S2_enable, OUTPUT) ;// pin can enable/disable using digital IO 5 of arduino
      pinMode(Enablepin, OUTPUT) ;// pin can enable/disable using digital IO 4 of arduino
      pinMode(A0, INPUT) ;
      pinMode(A5, INPUT) ;

    //  Serial.begin(9600);
    }

    void loop()
    {
      digitalWrite(3,HIGH);
    // wdt_reset();
     Take_Reading();
     state = slave.poll( au16data,5 );
      if (state > 4) {
        tempus = millis() + 50;
        digitalWrite(13, HIGH);
      }
      if (millis() > tempus) digitalWrite(13, LOW );

    Modbus_call();

    }

    void Modbus_call()
    {

    /*reading of coil where i can succefully read value*/
      auFloatData[20]=Current_Value1[0];
      auFloatData[21]=Current_Value1[1];
      auFloatData[22]=Current_Value1[3];
      auFloatData[4]=Current_Value1[4];
      auFloatData[5]=Current_Value1[5];
      auFloatData[6]=Current_Value1[6];
      auFloatData[7]=Current_Value1[7];
      auFloatData[8]=Current_Value1[8];
      auFloatData[9]=Current_Value2[0];
      auFloatData[10]=Current_Value2[1];
      auFloatData[11]=Current_Value2[2];
      auFloatData[12]=Current_Value2[3];
      auFloatData[16]=Current_Value2[4];
       auFloatData[17]=Current_Value2[5];
       auFloatData[18]=Current_Value2[6];
       auFloatData[19]=Current_Value2[7];
    uint16_t calcCRC( au16data[3]);
         au16data[1] = slave.getInCnt();
      au16data[2] = slave.getOutCnt();
      au16data[3] = slave.getErrCnt();

     }

  [1]: https://github.com/smarmengol/Modbus-Master-Slave-for-Arduino
  [2]: https://i.stack.imgur.com/Nd4WO.jpg

body:
1. Sizes

[Integer Types (int, long and long long)][1]

Size of Boolean type is 1 byte(s)

Number of bits in a character: 8
Size of character types is 1 byte
Signed char min: -128 max: 127
Unsigned char min: 0 max: 255
Default char is unsigned

Size of short int types is 2 bytes
Signed short min: -32768 max: 32767
Unsigned short min: 0 max: 65535

Size of int types is 4 bytes
Signed int min: -2147483648 max: 2147483647
Unsigned int min: 0 max: 4294967295

Size of long int types is 4 bytes
Signed long min: -2147483648 max: 2147483647
Unsigned long min: 0 max: 4294967295

Size of long long types is 8 bytes
Signed long long min: -9223372036854775808 max: 9223372036854775807
Unsigned long long min: 0 max: 18446744073709551615
Note that int and long are the same size and if you want a 64 bit integer then you need to use long long (or unsigned long long).

2. What do you want to achieve with

.

    CS=30.10 // 30.10
    Int_CS=int(CS) // 30
    FLOAT_CS = (Int_CS-CS)*100 //-10.00 because 30 - 30.10 = -0.1 and -0.1 * 100 = -10.00

CS is already float, why you want to convert it to int and back to float? If value of int is higher than 255 you have to save it in 2 bytes(highByte and lowByte), float is 32bit(4bytes) value.

I think you have to do like this:

    float CS = 30.10;
    au16data[0]= (int)(CS*100);//3010.00 > 3010

And for better way use :

    float auFloatData[30]; //
    ...
    auFloatData[0]=Current_Value1[0];

  [1]: http://developer.mbed.org/users/mbed714/notebook/integer-types-int-long-and-long-long/


sender: user

message:
Debouncing results in no reaction at all

Update:

I changed the code to this, but it does not work either.

`if ((millis() - lastDebounceTime) > debounceDelay) {

       if (button) {
     //DEBOUNCING

         if (!button_prev && button) {

          int e = input[j];`

I am trying to debounce a button and integrated this code http://arduino.cc/en/Tutorial/Debounce into my sketch.
The result is, that there is no reaction to the button at all.
I can't figure out the mistake, but maybe someone else sees what I overlook.

Circuit
![enter image description here][1]

Parts marked with `//DEBOUNCING` are only for the purpose of it, parts marked `//DEBOUNCE relevant` are necessary for the code to run as well when there is no debouncing.

    void setup() {

      Serial.begin(9600);

      //setting button pin as input and LOW

      pinMode(8, INPUT);
      digitalWrite(8, LOW); //DEBOUNCE relevant

      //setting input pins as output

      int act_pin[6] = {A0, A1, A2, A3, A4};

      int k = 0;

      for (k = 0; k < 5; k++) {

          pinMode(act_pin[k], OUTPUT);

        }

      //setting state pins as output

      int z_pin[5] = {2, 3, 4, 5};

      int a = 0;

      for (a = 0; a < 4; a++) {

          pinMode(z_pin[a], OUTPUT);

       }

      //setting output pins as output

      int out_pin[6] = {9, 10, 11};

      int b = 0;

      for (b = 0; b < 3; b++) {

          pinMode(out_pin[b], OUTPUT);

       }

      //setting input

      for(k = 0; k < 5; k++) {

          randomSeed(analogRead(5));

          int i = random(2);

          if(i == 1){

             digitalWrite(act_pin[k], HIGH);

             input[k] = 1;

             Serial.print(input[k]);

          }

           else{

             digitalWrite(act_pin[k], LOW);

             input[k] = 0;

             Serial.print(input[k]);

          }

        }

       //setting initial situation

       digitalWrite(2, LOW);
       digitalWrite(3, HIGH);
       digitalWrite(4, LOW);
       digitalWrite(5, LOW);

       }

    //DEBOUNCING

    long lastDebounceTime = 0;  // the last time the button pin was toggled
    long debounceDelay = 50;    // the debounce time; increase if the output flickers
    int buttonState;

    //DEBOUNCING

    boolean button_prev = 0;

    boolean button = 0;

    int j = 0; //value shows current lamp being processed

    //setting initial state

    char z[4] = "z_0";

    void loop() {

        button_prev = button;

        button = digitalRead(8); //DEBOUNCE relevant

        // DEBOUNCING
        if (button != button_prev) {

        lastDebounceTime = millis();

        }

        if ((millis() - lastDebounceTime) > debounceDelay) {

           if (button != button_prev) {
         //DEBOUNCING

             if (!button_prev && button) {

              int e = input[j];

               //provides a nice output
                Serial.println(" ");
                Serial.print("Current lamp being processed:");
                Serial.println(j);
                Serial.println(" ");
                Serial.print("Current input:");
                Serial.println(e);

                 delta(e, z);

                Serial.print("State outside function:");
                Serial.println(z);

                lamda(e, z);

                 j = (j+1) % 5;

          }

        }

       }
    }

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

sender: assistant

body: It's difficult to tell without seeing your circuit, but it looks like there could be a mix up between pin 12 and pin 8.  Can see that you initialize the pinMode for pin 12 in setup, but it isn't used in the loop.  You didn't initialize pin 8 (not completely necessary) in setup, but it is used in the loop.  If you don't feel this is relevant, please provide some more detail.


body:
If the button has stopped bouncing then (button_prev == button) and the inner if (button != button_prev)  will fail. Basically you're trying to ensure the button is steady but then you're checking that it changed.

Try this:

        if ((millis() - lastDebounceTime) > debounceDelay) {

           if (button) {     // Check the button is still pressed
           ... code...
    }


body: You've probably fixed this already but pin 8 is always grounded, regardless of the button state.  Pin 8 should be connected between the button and the pull-down resistor.


message:
Over-the-air upgrades?

I'd like to be able to upgrade software on an arduino without physically touching the device or stringing a cable. Can it be done?

Will pick wireless protocol that makes that easiest.

body:
It's possible to write a bootloader running in RAM (or even in Flash, maybe in a special boot block - depends on the microcontroller).

This bootloader has to be able to establish the wireless communication, understand the protocol and to erase/write Flash memory.

There are basically two approaches for software upgrading:

1. The bootloader looks at startup for a "software upgrade" command. If it is received, it waits for the programming sequence. If it is not received, it starts the application.

2. The application is able to receive such a command and gives control to the bootloader then.

What protocol you choose is almost irrelevant. Just make sure that there are enough resources for keeping it in RAM/Flash.
On an Arduino Due - for instance - there are more than enough resources for any such implementation.


body:
The best and easiest solution I've found is to use the Bluefruit EZ-Link from Adafruit.  They have a module you plug into the Serial/Power/reset pins ([link here][1]) or a shield for the uno ([link here][2]).  They've also got a great description and how-to guide ([link here][3]) that is pretty good.  It basically appears as a serial bluetooth link in the arduino IDE and you program it like normal.  It has the added benefit of being of use not only for programming, but also for sending and receiving data.

  [1]: http://www.adafruit.com/product/1588
  [2]: http://www.adafruit.com/products/1628
  [3]: https://learn.adafruit.com/introducing-bluefruit-ez-link/arduino-programming


body:
The [Arduino Yun][1] can be remotely reflashed (either via wifi or network cable): you'll have to select its IP address under the "Tools > Boards" menu of the Arduino IDE and then press the upload button as usual.

  [1]: http://arduino.cc/en/Main/ArduinoBoardYun?from=Products.ArduinoYUN


body: Yes, it can be done. Lowpowerlab.com has Moteino which can be programmed OTA.


body:
Spark.io boards are also very nice for OTA programmable Arduino-like devices. I have one and have found it to be fairly easy to work with.

https://www.spark.io/


body:
We have implemented remote updates on a Arduino Pro Mini (ATMega328P) by putting a "boot" command into the normal firmware. How it works is:

 - The host sends the command "boot" to the remote Arduino.
 - The Arduino jumps to the boot loader (program address 0x3C00 for the Pro Mini)
 - The host sends the new firmware over the link using avrdude (AVR109 protocol)

This doesn't require a new boot loader or hardware. It is not a good solution for commercial devices though, as if the uploaded firmware is corrupted the board will not be able to be put into boot loader mode without a hard reset.

Some wireless comms devices, such as XBees, have GPIO that can be toggled remotely. Connecting this to the Arduino reset pin will allow the board to be reset into the boot loader instead.


message:
How can I pair a Bluetooth dongle on arduino Yun (openwrt-yun)?

On my Arduino Yun (openwrt-yun, updated to latest version), I have a bluetooth dongle in the usb port; I have installed bluez-libs and bluez-utils (and python-bluez).  They show up as version 5.13.  hciconfig and hcitool work properly.  There does not seem to be any utility installed to pair with a device, nor can I figure out how to get pairing to work by editing config files.

I can find the device with hciconfig and hcitool, but rfcomm can't connect without the pin.  If I try the same sequence on my Linux laptop after pairing with the gui, rfcomm is able to connect, so I know the device is working properly (JY-MCU HC-06 on another Arduino).

All the recommendations I can find on the web indicate I should be able to use simple-agent or bluez-simple-agent, but they are not installed with these packages (there is no bluez-tools package for this distro).  If I manually copy the python script for the agent to the device and run it, it fails, saying that org.bluez can't be found with dbus.  There is no bluetoothd running, and no init script for any bluetooth demon.  None of the bt* tools are available.

I also found a description of how to set a pin code in /var/lib/bluetooth/[bt-addr]/pincodes (where bt-addr is my dongle address) containing a line of the form:

[device-addr]  [pincode]

but this seems to have no effect.

I have also tried settings in /etc/bluetooth/main.conf and /etc/bluetooth/rfcomm.conf, but I think they may only be for incoming connections.

Any help would be greatly appreciated.

body:
It takes me some time to make it work :

1) update drivers

    opkg update

    opkg install kmod-bluetooth bluez-libs bluez-utils

2) add configuration files in directory /etc/bluetooth

    root@Arduino:~# cat /etc/bluetooth/hcid.conf

    options {
      autoinit yes;
      security auto;
      pairing multi;
      passkey "0000";
       }
    device {
      name "OpenWrt";
      class 0x000100;
      lm accept,master;
      lp rswitch,hold,sniff,park;
      }

    root@Arduino:~# cat /etc/bluetooth/rfcomm.conf

    rfcomm0{
     bind yes;
     device 00:1B:C1:02:B0:F5;
     channel 1;
     comment "Holux M-1000";
     }

3) Reboot the card

4) test if all is OK

    hciconfig

5) put the interface up

    hciconfig hci0 up

6) Search for devices

    hcitool scan

7) Look for Serial Port capability on the devices

    sdptool search SP

8) bind the serial dev

    rfcomm -i hci0 connect /dev/rfcomm0 00:1B:C1:02:B0:F5

9) see the information comming from the device (bluetooth GPS in my case)

    cat /dev/rfcomm0


message:
How to display tilt sensor data on an LCD?

I'd like for a 16x2 LCD monitor from [Sparkfun][1] to display sensor data from a 4-directional tilt sensor from [Parallax][2]. The Arduino board is a Duemillanove. The board will run and power both programs and modules, but the serial monitor displaying the tilt sensor data will not relay the info to the LCD display. Any suggestions?

  [1]: https://www.sparkfun.com/products/9394
  [2]: http://learn.parallax.com/KickStart/28036

Here are the two pieces of code I am trying to get to work together—they are both from Arduino:

For the tilt:

    void setup() {
       Serial.begin(9600);
    }
    void loop() {
       Serial.print("Photo 1: ");
       Serial.print(digitalRead(6), DEC); // Display Out 1 value
       Serial.print("; ");
       Serial.print("Photo 2: ");
       Serial.println(digitalRead(7), DEC); // Display Out 2 value
       delay(250); // Wiat 1/4 second
    }

For the LCD:

    #include <SoftwareSerial.h> // Attach the serial display's RX line to digital pin 2
    SoftwareSerial mySerial(3,2); // pin 2 = TX, pin 3 = RX (unused)
    void setup() {
      mySerial.begin(9600); // set up serial port for 9600 baud
      delay(500); // wait for display to boot up
    }
    void loop() {
      mySerial.write(254); // move cursor to beginning of first line
      mySerial.write(128);
      mySerial.write(" "); // clear display
      mySerial.write(" ");
      mySerial.write(254); // move cursor to beginning of first line
      mySerial.write(128);
      mySerial.write("movement recorded");
      while(1); //
      wait forever
    }

Update:

I'm still tinkering with the suggested program from @Ariser shown below, but keep getting a compile error:

tilt_lcd_ase.cpp: In function ‘void loop()’:
tilt_lcd_ase.cpp:24:43: error: expected ‘)’ before ‘;’ token
tilt_lcd_ase.cpp:25:43: error: expected ‘)’ before ‘;’ token

I've done some research and one person had a similar problem, but it was within #include not void loop. The search continues, but if anyone has a suggestion please chime in. The liquid crystal library is also turning up similar errors but it needs a closer look.

body:
The serial monitor cannot relay data from different peripheral unit in an arduino system.

I think you have certain misconception of the hard and software. Your USB connection to the microcontroller on the arduino is just a trunk for a asynchronous serial transmission. In the past this was done via a RS-232 interface.

So, what is it, that you see in your serial monitor? That's just a bunch of characters sent by the microcontroller on your arduino. This data is sent from the microcontroller, because some piece of software fills the fifo of its serial interface. In fact, such commands are executed, when you call the method "Serial.print()". Data gets then sent to your PC, Mac or whatever you are running your IDE on.

Now on the very same microcontroller the software for your tilt sensor is being executed. How could the serial monitor (which resides on your PC) route data from your tilt sensor to your LCD display? I'll tell you: It can't.

(In fact you could write a terminal script on your PC which reads data from serial and writes it back to the same interface, but it may cross your mind, that this might be a very big indirection)

So what do you wanna accomplish? You want to put data read from a device connected to your Arduino to another device connected to your Arduino. So you better tell it the Arduino. The serial monitor will not be involved, hence you won't need any calls of Serial.print() to accomplish that.

To help you with that task, we need to see the code you have written so far.

Ok. first thing you need to know: You can't have two arduino sketches running simultaneously on your arduino. This is, because there is nothing like an operating system on your arduino which might provide a scheduler to run both programs. (If you want, look up scheduler on wiki, as it is very useful to know what you can't have)

So you need two pieces of code to run on the same microcontroller (the big black thing on your arduino) one doing the tilt sensor readings and the other printing data on your display. Hence you have to make one program out of two. To accomplish this, you have two problems to solve.

 1. you have to execute both code fragments alterantely, which, because the controller is fast enough, boils down to do both task _nearly_ simultaneously

 2. you have to bring the data which is acquired by code part 1 from the tilt sensor to code part 2 writing to the display. This is (for people into programming) rather simple as it simply has to be stored in a variable.

I recommend you to look up some programming basics at the arduino home page concerning the "setup" function and the "loop" function. But for now: You can have only one of each running on your arduino. Everything which is inside "setup" is executed only once after powerup. Everything which is inside "loop" is going to be executed over and over again consecutively (if nothing breaks).

Your program might look like this:

    #include <SoftwareSerial.h> // Attach the serial display's RX line to digital pin 2
    SoftwareSerial mySerial(3,2); // pin 2 = TX, pin 3 = RX (unused)

    char gl_senstr1[15];
    char gl_senstr2[15];

    void setup() {
      mySerial.begin(9600); // set up serial port for 9600 baud
      delay(500); // wait for display to boot up
    }

    void loop() {
      mySerial.write(254); // move cursor to beginning of first line
      mySerial.write(128);
      mySerial.write(" "); // clear display
      mySerial.write(" ");
      mySerial.write(254); // move cursor to beginning of first line
      mySerial.write(128);
      mySerial.write("movement recorded");

      sprintf(gl_senstr1, "%d", digitalRead(6);

      sprintf(gl_senstr2, "%d", digitalRead(7);

      sprintf(gl_senstr1, "%d", digitalRead(6));
      sprintf(gl_senstr2, "%d", digitalRead(7));

      mySerial.write("sensor1: ");
      mySerial.write(gl_senstr1);
      mySerial.write(" sensor2: ");
      mySerial.write(gl_senstr2);

       delay(250); // Wiat 1/4 second

    }

I did not test it, because I neither own your display nor that sensor. But you can give it a try. You eventually have to dive into the art of programming if you want to accomlish little more than this. This is where the rubber meets the road.


body:
by the looks of it you need to close the brackets of the *sprintf()* statement shown below if you had copied the code from Ariser:

    sprintf(gl_senstr1, "%d", digitalRead(6);
    sprintf(gl_senstr2, "%d", digitalRead(7);

replace it with:

    sprintf(gl_senstr1, "%d", digitalRead(6));
    sprintf(gl_senstr2, "%d", digitalRead(7));

That is the error you are seeing because of *sprintf()* not seeing a close to its statement  ;)


message:
Led on when not supposed to be

So I made a program that controls two LED's when two buttons are pressed, but one of the LED's comes on when the button isn't pressed. And what's weird is that if I literally move around the breadboard the LED might turn off for a little, and if hold the button down while doing it the LED remains solid. I have done a lot of taking out and switching wires without any unexpected effects. However, if I switch the LED wires the other LED turns and stays on while the first one turns off, so I am pretty sure that it is a programming error. Here is my code:

    const int ledPin1 = 8;
    const int buttonPin1 = 1;
    const int ledPin2 = 9;
    const int buttonPin2 = 2;

    int buttonState1 = 0;
    int buttonState2 = 0;

    void setup()
    {
      pinMode(ledPin1, OUTPUT);
      pinMode(buttonPin1, INPUT);
      pinMode(ledPin2, OUTPUT);
      pinMode(buttonPin2, INPUT);
    }

    void loop()
    {
    buttonState1 = digitalRead(buttonPin1);
    buttonState2 = digitalRead(buttonPin2);

      if (buttonState1 == LOW)
      {
        digitalWrite(ledPin1, HIGH);
      }
      else
      {
        digitalWrite(ledPin1, LOW);
      }

      if (buttonState2 == LOW)
      {
        digitalWrite(ledPin2, HIGH);
      }
      else
      {
        digitalWrite(ledPin2, LOW);
      }
    }

body:
I don't think it is necessary to do the declaration of int buttonstate1 = 0; and int buttonstate2 = 0; seeing that in your loop the buttonstates gets read by you using digitalRead. Also I don't think the buttons is inverted, because you aren't using a pull up resistor if I'm correct.

Hopefully this helped.

Also something that I found helped a lot is that if you use a lastbuttonstate variable too. Than your if statement might look something like this:

    if(buttonstate1 == HIGH && previousbuttonstate1 == LOW)
    {
    digitalWrite(ledPin1, HIGH);
    previousbuttonstate1 = buttonstate1;
    }

    else if(buttonstate1 == HIGH && previousbuttonstate1 == HIGH)
    {
    digitalWrite(ledPin1, HIGH);
    }

    else if(buttonstate1 == LOW && previousbuttonstate1 == HIGH)
    {
    digitalWrite(ledPin1, LOW);
    previousbuttonstate1 = buttonstate1;
    }

    else
    {
    digitalWrite(ledPin1, LOW);
    }

Basically adding the previousbuttonstate1 just gives it a more accurate way of checking the button state(I'm typing under correction).

Sorry for the sloppy answer, but hopefully it helps.


body:
The behavior you describe is symptomatic of a floating input.

I guess you have directly wired your buttons between input pins and +5V (or GND, that won't change the observed behavior).

The problem is when you don't push the button, the input pin is left floating and can be read as HIGH or LOW based on strange factors.

The solution to this is to use pullup (if you connect the other side of the button to GND) or pulldown (if your button is connected to +5V) resistors.

The following image, off the arduino website, shows such a circuit with a pulldown resistor, i.e. connect the switch to +5V and the resistor to GND:

![Pullup resistor example](https://arduino.cc/en/uploads/Tutorial/button_schem.png)

An even simpler way is to connect the buttons to GND and use `pinMode(pin, INPUT_PULLUP);` in `setup()`.


message:
Reading a tachogenerator

I'm trying to read a tachogenerator from a washing machine. It outputs an alternating current, with multiple periods per revolution. The voltage for my test case (constant rpm) reads 5.5V. I attached the tachogenerator to Digital 2 and GND and ran this sketch, just to see if a change is detected:

    int ledPin = 13;
    volatile int state = LOW;

    void setup() {
      pinMode(ledPin, OUTPUT);
      attachInterrupt(0, blink, RISING);
    }

    void loop() {
      digitalWrite(ledPin, state);
      delay(500);
    }

    void blink() {
      if (state == LOW) state != state;
    }

Unfortunately, the LED does not light when I start the motor. When I measure the voltage while it is connected to the Arduino, it shows only about 0.7V, which would explain why the LED is not reacting. But why is this?

body:
There's an obvious code problem in your `blink()` function:

    state != state;

The above statement will never modify your state variable. The `!=` operator in C/C++ does not perform an assignment (unlike operators such as `+=` and `-=`). It's a comparison operator which just tests for inequality. You presumably meant to do this:

    state = !state;

That may not fix your problem entirely though. You might find that the interrupt doesn't get reliably triggered anyway because it's not designed to handle AC. I'd recommend using an external comparator circuit to generate a clean digital signal, such as a Schmitt trigger.


message:
Arduino's Serial Monitor Showing Constant Value

I have a breadboard Arduino; made with ATMega328PU and a UART connector using a CT2102 breakout board. With the help of [this site][1] I created a simple IR sensor, now the problem is that in the Serial Monitor I'm getting a constant value of **1023**. Even on removing the receiver (photodiode), the value's starts dropping like a capacitor discharges, and then stabilizes at some value (around 260-300).

When everything was working correctly, the value dropped to a sudden **zero** on removing the receiver, but now it isn't.

The "robot" was working perfectly and was reading the values correctly, but suddenly, the values dropped; we checked it and the Serial Monitor showed the same values. To check if the connections are working, I removed a wire from the Analog Pin of the Breadboard-Duino, and the values started to drop: like a periodic function.

The following code was used:

    int pd=2;                      //Photodiode to digital pin 2
    int buzz=13;                   //piezo buzzer to digital pin 13
    int senRead=0;                 //Readings from sensor to analog pin 0  or A0
    int limit=850 / 4;                 //Threshold range of an obstacle
    void setup()
    {
      pinMode(pd,OUTPUT);
      pinMode(buzz,OUTPUT);
      digitalWrite(pd,HIGH);       //supply 5 volts to photodiode
      digitalWrite(buzz,LOW);      //set the buzzer in off mode (initial condition)
      Serial.begin(9600);          //setting serial monitor at a default baund rate of 9600
     }
    void loop()
    {
      int val=analogRead(senRead) / 4;  //variable to store values from the photodiode
      Serial.println(val);          // prints the values from the sensor in serial monitor
      if(val <= limit)              //If obstacle is nearer than the Threshold range
      {
       digitalWrite(buzz,HIGH);     // Buzzer will be in ON state
       delay(20);
      }
      else if(val > limit)          //If obstacle is not in Threshold range
      {
       digitalWrite(buzz,LOW);      //Buzzer will be in OFF state
           delay(20);
      }
    }

Any help will be appreciated.

**EDIT**

The phototransistor/diode is a standard 2pin component which came with the IR sensor.

![Image][2]

  [1]: http://startrobotics.blogspot.de/2013/05/how-to-use-ir-led-and-photodiode-with-arduino.html
  [2]: https://i.stack.imgur.com/24CLS.jpg

body:
In your initialisation where you declare each variable and 'connecting' them to a pin you make a mistake. Now you say that senRead is a digital pin instead of a analog pin. Change the value to A0 so you will get

int senRead = A0;

Also in your void Setup() you forget to declare your analog pin as an input. Add a pinMode command that sets senRead as an input.

If this doesn't fix your problem then it is probably hardware related. Check the connections on your breadboard will most of the times solve alot of problems.


body:
If the circuit worked perfectly, as is, and suddenly stopped working, without changing any hardware configuration, it must be a hardware related problem.

Assuming your Arduino Uno is functioning properly and the pins behave accordingly (you can test blink.ino on the pin in doubt), it's either the IR sensor went bad or a the IR LED stopped working properly. Test each component individually. For the IR sensor, you could use any remote control to emit IR light on it and see if values change.

Another way to test bad pins are to switch from A0 to A1 and from PB2 to PB3 or similar.


body: I guess your ir emitter is blown.Test it with a multimeter.Apply 5v from Arduino and check the voltage between two pins or just use phone's camera.If multimeter shows anything more than 3v or it just plainly shows applied voltage the led failed or it is open.If it is not,then use phone camera and watch the led through the camera. You should see a blue light emitting from it( if it's working).


message:
How to parse array to x,y positions?

I have 16x16 LED matrix and I want to show some custom characters on it. I saw font made with array like this.

    const byte zero[16] = { // Create byte array number 0
          B0111110,
            B1111111,
            B1100011,
            B1100011,
            B1100011,
            B1100011,
            B1100011,
            B1100011,
            B1100011,
            B1100011,
            B1100011,
            B1100011,
            B1100011,
            B1100011,
            B1111111,
            B0111110
        };

But I dont know how to parse it to x, y positions. Can someone help me? Do you know better way to store characters that is easily readable by human? Thanks

body:
Th example looks like the character '0', 8 bits wide and 16 bits high, though it could be the 16x8 due to '0's symmetry. Find the '2' array, for instance and plot the 1-bits on a piece of graph paper (even a hand-drawn grid will do). Once you should see the character shape you'll know how the bits/dots are arranged in the array.

If your LED array has a square pitch (same spacing vertically and horizontally), 16-bit high characters may appear rather tall and skinny. If so, you could re-plot the characters to suit yourself. If you do decide to hand code them, look at your display hardware. It probably (but not necessarily) accepts 8 horizontally-adjacent bits at a time. But regardless, you can simplify your display code if one array-byte contains 8 bits that will be output at once.

--------- Update:

There's a lot missing from your question but I'll pick some assumptions to base an answer on.

    Y = array_index;
    X = (6-bit_position) + (is_right_hand_character ? 8 : 0);

based on assumptions that:

 - you want the display coordinates of a given bit in the array;
 - the origin (0,0) of your display is the upper left hand corner LED;
 - the first character starts in column 0; the second in column 8; The
   leftmost bit to display is in bit-6 of each byte and bit 7 (MSb) is
   not used;
 - you'll use zero-based coordinates.

The 'Y' coordinate is pretty straight-forward - byte-0 is the first byte.
The 'X' coordinate is found by subtracting the position of the bit of interest from 6, and maybe adding 8, since bit-6 goes into column-0 or column-8 for the left or right character, respectively.


body:
To get the value at a particular location, use this code:

    boolean val = zero[y] & ((B1 << maxX) >> x);

where `y` is the y position from 0 to `zero.length`, `maxX` is the length of the binary constants minus one (in this case, it would be 6), and `x` is the x position from 0 to `maxX`.

For more information, see [BitMask](http://arduino.cc/en/Tutorial/BitMask).


message:
Installing MariaMole (Alternative IDE) on Mac

I've heard about a alternative Arduino IDE called [MariaMole][1] and really liked the idea, but I just don't know how to install it on Mac OS X. The [GitHub page][2] claims that it is compatible with Mac but I just can't find a tutorial, or instructions, as to how the Git files can be compiled on Mac.

  [1]: https://github.com/aporto/mariamole
  [2]: https://github.com/aporto/mariamole

body:
For mac its not yet released ([See website](http://dalpix.com/mariamole-download)).

To try the experimental mac version, you'll have to compile it yourself with the code found on that github repository you linked to


body:
_Note: I haven't tried this myself so YMMV; this is just from my general experience and reading; all information comes with citations._

To start, I would recommend opening [an issue on GitHub][1] to ask for detailed instructions. I noticed that the [website][2] says:

> Linux and Mac distributions are still experimental, but MariaMole is working fine on both systems.

so they should have a known recipe for how to do it.

---

In the mean time, here's how I would proceed. Given that there's a file called [`CMakeLists.txt`][3] in the root directory, you need to:

* download and install [CMake][4]

Then, install the [dependencies listed on the wiki][5]:

* Qt 5.2
* QScintilla 2
* QSerial

After that, I presume just cloning the repo and running `cmake` in the root directory should do the trick. If you have any further questions, please open an issue on GitHub with your compilation error message for further assistance.

  [1]: https://github.com/aporto/mariamole/issues
  [2]: http://dalpix.com/mariamole-download
  [3]: https://github.com/aporto/mariamole/blob/master/CMakeLists.txt
  [4]: http://www.cmake.org/
  [5]: https://github.com/aporto/mariamole/wiki/Compiling-MariaMole


message:
AttachInterrupt in a library

I'm having trouble adding attachInterrupt in a library that I am creating. I researched a lot, and I noticed that this is a common mistake, but do not quite understand the answers I found.

The error in question is this:

    sketch_nov04a.ino: In function 'void setup()':
    sketch_nov04a:10: error: argument of type 'void (Teste::)()' does not match 'void (*)()'

My library is as follows:

**Teste.h**

    #ifndef TESTE_H
    #define TESTE_H
    #include <Arduino.h>

    class Teste
    {
    public:
        volatile long lastWindIRQ;
        volatile byte windClicks;

      void wspeedIRQ();
    };
    #endif

**Teste.cpp**

    #include "Teste.h"

    void Teste::wspeedIRQ()
    {
      if (millis() - this.lastWindIRQ > 10)
      {
        this.lastWindIRQ = millis();
        this.windClicks++;
      }
    }

**my implementation**

    #include <Teste.h>

    Teste teste;

    void setup()
    {
      Serial.begin(9600);
      pinMode(2, INPUT);
      digitalWrite(2, HIGH);
      attachInterrupt(0, teste.wspeedIRQ, FALLING);
    }

    void loop()
    {
      Serial.println(teste.windClicks);
      delay(3000);
    }

**EDIT**: Updated the error and corrected the problem cited by Ignacio

body:
The problem is that `wspeedIRQ()` is a member function (i.e. it's part of the `Teste` class), but `attachInterrupt()` expects a non-member function (i.e. a function which is static and/or not part of a class at all).

This is a very important distinction in C++ because it affects how the compiler calls the function behind-the-scenes. There is unfortunately no way to use a member function directly with `attachInterrupt()`.

Various workarounds are possible though. The simplest is to write a wrapper function which calls the member function. For example:

    Teste teste;

    // This is a non-member function...
    void isr()
    {
        // ...which calls the member function:
        teste.wspeedIRQ();
    }

    void setup()
    {
        //...

        // Setup interrupt to use a non-member function
        attachInterrupt(0, isr, FALLING);
    }

As a side note, your implementation of `wspeedIRQ()` won't compile at the moment anyway. The reason is that `this.` is invalid. It's a pointer so the correct syntax is `this->`.

(In practice, you usually don't need to use `this` to access member data. C++ figures it out automatically, unless there's a naming conflict.)


body:
Normally you should use digitalPinToInterrupt(pin) to translate the actual digital pin to the specific interrupt number not the pin switch comparison attachInturrupt( , , )that is limited to pin 2,3 on an arduino uno ...or if you spend more money well... here's a list.

    Board                            Digital Pins Usable For Interrupts
    Uno,    Nano, Mini, other 328-based 2, 3
    Mega,   Mega2560, MegaADK         2, 3, 18, 19, 20, 21
    Micro, Leonardo, other 32u4-based 0, 1, 2, 3, 7
    Zero                             all digital pins, except 4
    MKR1000 Rev.1                     0, 1, 4, 5, 6, 7, 8, 9, A1, A2
    Due                                 all digital pins
                                     all digital pins (Only pins 2, 5, 7, 8,
                                        10,  11, 12, 13 work with CHANGE

delay() won't work b/c values won't return from millis() (don't ask why)
[https://www.arduino.cc/en/Reference/AttachInterrupt][1] explains how to use inturrupts like let me recite the beggining

  [1]: https://www.arduino.cc/en/Reference/AttachInterrupt
Interrupts are useful for making things happen automatically in microcontroller programs, and can help solve timing problems. Good tasks for using an interrupt may include reading a rotary encoder, or monitoring user input.... blah blah

what pete didn't mention is what Interrupt Service Routines were... and how these special functions have unique limitations other functions like in c++ do not.... from c-strings to structs to overloading to f-structs to t-templates. ISR's are as short as possible and should not return anything! if your cheap and don't want to spend more than $5 for a arduino you can use sketch to use multiple isr's you can set them up as priority

but your non member functions should be volatile and global... and millis() relies on interrupts to count, so it will never increment inside an ISR. Since delay() requires interrupts to work, it will not work if called inside an ISR. micros() works initially, but will start behaving erratically after 1-2 ms. delayMicroseconds() does not use any counter, so it will work as normal. and .... global variables are used to pass data between an ISR and the main program. To make sure variables shared between an ISR and the main program are updated correctly, declare them as volatile.


message:
Many "expected `)' before ';' token" errors

As the title suggests, I have many "expected `)' before ';' token" errors. The issue is, I have this stuff in. So now I am confused, why am I getting this if the things are there.

I am new here and had an issue with adding code, so here is the pastebin link to it: http://pastebin.com/4WXxsXkB

And here is the the pastebin link to the error:
http://pastebin.com/QyehP86M

Does anyone understand how this could happen?

body:
You have two #define statements at the top of your code

    #define trigPin 3;
    #define echoPin 2;

The way `#define` works is that it replaces every instance of the name with everything after it on the line so `trigPin` is being replaced with `3;` as opposed to `3` as intended.

Fixing this should solve some of your problems.


message:
How to send two different sets of int numbers over serial?

I have a project that require for the main computer to do most of the processing then for it to send the X and Y coordinates of this processing to the arduino. This at the time didn't seem very hard but now that I have started to dive into serial some more I am completely confused. All of the example I have seen for serial only consist of 1 set of numbers and rather confusing.

The Arduino code I kinda want to go like this
http://pastebin.com/aLJfEExw (I know this is probably completely wrong but I am pretty lost right now)

The Python code is this right now
http://pastebin.com/4aN4dnSC

If you guys could help explain this better for me it would be amazing. I understand that my code is probably wrong. So if you guys could provide an example of how to send the two different sets of int's it would be amazing. Because I am completely and utterly lost.

body:
I looked at your code, but the main problem seems to be that you have not defined the problem, and it is thus not possible to definitively answer.

The conventional solution to this would be to send 2 numbers with separator (usually space) followed by a newline. I know Arduino does not have an inbuilt function to do this, but you could write one. http://arduino.cc/en/Tutorial/SerialEvent shows one way this could be done.

Another approach is to send bytes (how long is each number? I would guess 16 bits) so you would send 4 bytes and on reception assemble them into 2 16 bit integers. Whether you need to ensure the data is synchronised depends on your problem. If you are sending continuous data this is essential, and you could use the kind of compelled sequence signalling you seem to be implying.

From the code it looks like you are sending from a Raspberry Pi. If I were doing this I would probably use I²C (at least over a short distance).


body:
I wrote a communication protocol for arduino to node.js over Serial. I sent a buffer of bytes using `Serial.write()` and read it into a buffer. This allows you to send as many numbers as you want. To send long (16 bit) numbers, you simple need to loop over two at a time combining:

C++:

    long int a = 0x9A44;
    uint_8t b = ( a & 0xFF00 ) >> 8;
    uint_8t c = a & 0x00FF;

Python:

    a = ( b << 8 ) & 0xFF00 | c & 0x00FF


message:
16 bit PWM on a mega

I have two Arduinos, a nano and a mega. I want to output 16 bit PWM, but can seem to only get it working on the nano. I'm adapting the code from this website: http://www.ofrecordings.com/2014/03/16/how-to-set-up-16-bit-pwm-with-an-arduino-uno-atmega328/

    void setup() {
      // Set PB1/2 as outputs.
      DDRB |= (1 << DDB1) | (1 << DDB2);

      TCCR1A =
          (1 << COM1A1) | (1 << COM1B1) |
          // Fast PWM mode.
          (1 << WGM11);
      TCCR1B =
          // Fast PWM mode.
          (1 << WGM12) | (1 << WGM13) |
          // No clock prescaling (fastest possible
          // freq).
          (1 << CS10);
      OCR1A = 0;
      // Set the counter value that corresponds to
      // full duty cycle. For 15-bit PWM use
      // 0x7fff, etc. A lower value for ICR1 will
      // allow a faster PWM frequency.
      ICR1 = 0xffff;
    }

    void loop() {
      // Use OCR1A and OCR1B to control the PWM
      // duty cycle. Duty cycle = OCR1A / ICR1.
      // OCR1A controls PWM on pin 9 (PORTB1).
      // OCR1B controls PWM on pin 10 (PORTB2).
      OCR1A = 0x0000;
      delay(500);
      OCR1A = 0x8000;
      delay(500);
      OCR1A = 0xffff;
      delay(500);
    }

That code works on the nano, but not on the mega. I expect that it output PWM on pins 11 and 12, but no luck. Care to explain how I can get it working? It's an entirely different microprocessor, and I'm not sure which parts of the code to change.

body:
According to this chart:
http://arduino.cc/en/Hacking/PinMapping2560

The mega does not support PWM on those digital pins. It looks like 14 of the 54 pins do, use the chart to find which pins to use.


body:
Change first line:

        // Set PB1/2 as outputs.
        DDRB |= (1 << DDB1) | (1 << DDB2);`

to the

         // Set PB5/6 as outputs. [**Digital pin 11,12 on Arduino Mega!**]
        DDRB |= (1 << DDB5) | (1 << DDB6);

Now your PWM should work, but on digital pins 11 & 12 [Arduino Mega].


message:
Arduino Mega 2560 RFID Serial Communication

I have an RFID reader: http://img.tradeindia.com/fp/1/641/264.jpg

Something like above along with ITEAD TFT shield & GSM Modem. The RFID reader has an RS-232 port as well as GND, TX and 5V pins. I am using an Arduino Mega 2560 board. I have connected the TX, GND of RFID reader to RX3 pin 15 / GND (pin) of Arduino. Note I am supplying 12 V to RFID via an adapter.

Note the ITEAD TFT shield consumes the TX0, RX0 pins—so I cannot make use of the RX0 and TX0 pins. Though I have not written the code for GSM modem.

Now while running the program below, I am getting junk output both in my TFT display as well as the serial monitor:

    #define __AVR__
    #include <UTFT.h>

    // Declare which fonts we will be using
    extern uint8_t SmallFont[];
    extern uint8_t BigFont[];
    extern uint8_t SevenSegNumFont[];
    UTFT myGLCD(ITDB24,59,58,57,56);
    String myString = "";

    void setup() {
       Serial3.begin(9600);
       myGLCD.InitLCD();
       myGLCD.clrScr();
    }

    void loop() {
      myGLCD.setFont(BigFont);
      if (Serial3.available()) {
        int inByte = Serial3.read();
         myString += String(inByte);
        }
        if(myString.length() == 10)
          myGLCD.print(myString, CENTER, 0);
    }

TFT Screen output:

1310494848

Serial Monitor Output: non printable junk character.

The value is incorrect, I am pretty sure, what am I doing wrong?

I found that the ITEAD shield is sending or rather using RX0/TX0 pins very frequently—some data is going through.

BTW what is the functionality of http://arduino.cc/en/Tutorial/SoftwareSerialExample?

How can I use 3 different Serial I/Os individually at the same time without disturbing any other I/O?

body:
First of all, try testing 1 functionality at a time to isolate the issue.
Now you do not know if the LCD is not working correctly, or if the serial communication with the RFID module is not working correctly. Connect it to a computer and test both independently.

When getting gibberish from a serial line, usually it means the baudrate doesn't match. Both devices have to send the same amount of bits per seconds in order to communicate with each other.

This is the Arduino example to test 2 serial lines (for Arduino Mega) at the same time: http://arduino.cc/en/Tutorial/MultiSerialMega


message:
Stack arduino, motor shield and lcd shield

I made arduino-stack which consists of arduino r3, robotdf motor shild and robotdf lcd shield. But motor shield and lcd use same pins 4 and 5, so we have a conflict of pins. Can i use other pins?

body:
Stack one shield on top of the Arduino itself and connect the other shield using wires. This way you can pick your own pin assignment for the 'external' shield.

Be careful when using a specific library though, sometimes the used pins are hard-coded in the library itself. Modifying the .h and .cpp files for the library is possible, so you could (hard code) assign your own used pins.


message:
High frequency audio sampling and storage

I want to use an arduino **duemilanove atmega168** for audio signal processing. I can sample the signal at around 38.5kHz using [this code](http://www.instructables.com/id/Arduino-Audio-Input/step6/Sampling-rate-of-40kHz/). I want to send the sampled data over the serial to a computer for processing.

- Data acquisition rate: 38.5 kbps (using 8-bit precision)
- Maximum serial communication rate: 115200 bps (I don't know exactly how this relates to the transfer rate of the actual data (without any overheads), but anyhow the limit is 13.94 kbps)
- Arduino flash memory: 16 kB

I would like to transmit around 4-5 seconds of the audio signal to the computer. Is there a way to achieve this?

body:
After doing some reading here https://arduino.stackexchange.com/questions/4071/serial-begin-why-not-always-use-28800?rq=1 and looking at the manual for the 168. You should be able to achieve the baud rate you want by directly programming the USAR.

According to the answer there you should be able to use miniterm to keep up with a high baud rate.

As stated there you might run into problems with computer power.

Read chapter 20 here http://www.atmel.com/images/doc2545.pdf.

Basically you can set up the USART speed (UDR0) and the control registers (UCSR0A,UCSR0B and UCSR0C) such that you can send data pretty fast.

Let me know if you can't access that link and if you need me to explain some more about these things.


message:
Sending Serial Hex Command from Pin 1 (Tx)

Using Arduino Uno with 3.5mm Jack connected to ground and pin 1 for TX

Need to send two commands
I want to send
0XAA13FE010113 for Mute on, and
0XAA13FE010012 for Mute off.

Simple Serial Command to turn Monitor Mute on and off every 5 seconds....

tried everything byte character, array, write with hex, print :(

Thx for a helping a rookie
I want to impress my team

------------------------

Ideal quick answer below. thx to @martynas

    uint8_t muteON[] = { 0xAA, 0x13, 0xFE, 0x01, 0x01, 0x13 };
    uint8_t muteOFF[] = { 0xAA, 0x13, 0xFE, 0x01, 0x00, 0x12 };
    ....
    void loop() {
     Serial.write( muteON, sizeof(muteON) );
     delay(5000);               // wait for 5 second
     Serial.write( muteOFF, sizeof(muteOFF) );
     delay(5000);               // wait for 5 second
    }

body:
there are 6 bytes just make

    byte muteON[] = {0xAA,0x13,0xFE,0x01,0x01,0x13};
    byte muteOFF[] = {0XAA,0x13,0xFE,0x01,0x00,0x12};
    ...
    /* To send mute ON comand */
    for(byte i =0;i<sizeof(muteON);i++)(Serial.write(muteON[i]));
    /* To send mute OFF comand */
    for(byte i =0;i<sizeof(muteOFF);i++)(Serial.write(muteOFF[i]));


message:
How would I establish a serial connection with python without using the serial monitor?

What I want to do is give my python script some input and have the arduino do something (blink for example)

I also want to be able to read in data with the arduino to give it to my python script.

What modules for python would be useful? I'm just starting out and don't have much of an idea for this one.

I am using a windows7 machine with python 2.7.6 and have an UNO board and a Leonardo board that I want to be able to use.

body:
This question is about **Python** not Arduino... Before asking here please ask **GOOGLE**

Anyway...

This is the answer [Arduino and Python][1]

Python code:

    ## import the serial library
    import serial

    ## Boolean variable that will represent
    ## whether or not the arduino is connected
    connected = False

    ## open the serial port that your ardiono
    ## is connected to.
    ser = serial.Serial("COM11", 9600)

    ## loop until the arduino tells us it is ready
    while not connected:
        serin = ser.read()
        connected = True

    ## Tell the arduino to blink!
    ser.write("1")

    ## Wait until the arduino tells us it
    ## is finished blinking
    while ser.read() == '1':
        ser.read()

    ## close the port and end the program
    ser.close()

Arduino code:

    // Open a serial connection and flash LED when input is received

    void setup(){
      // Open serial connection.
      Serial.begin(9600);
      pinMode(13, OUTPUT);
      Serial.write('1');
    }

    void loop(){
      if(Serial.available() > 0){      // if data present, blink
        digitalWrite(13, HIGH);
        delay(500);
        digitalWrite(13, LOW);
        delay(500);
        digitalWrite(13, HIGH);
        delay(500);
        digitalWrite(13, LOW);
        Serial.write('0');
      }
    }

  [1]: http://www.instructables.com/id/Arduino-and-Python/?ALLSTEPS


message:
Unable to upload sketch to Leonardo

I'm really at my wits end. For a couple of hours I have been programming a custom board that uses everything as on the Arduino Leonardo. A few hours ago I am not able to upload anymore.

I get the following error:

       avrdude: error: buffered memory access not supported.
       Maybe it isn't a butterfly/AVR109 but a AVR910 device?

I've tried everything from re-installing the IDE, re-installing the board in Device Manager, changing the COM Port. I really just don't know anymore.

Here is some more data that might be relevant or useful:

         Using Port                     :\\.\COM6
         Using Programmer              : avr109
         Overriding Baud Rate          : 57600
         AVR Part                      : ATmega32U4
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53

[EDIT]
I've now checked the battery (yes with a multimeter), it is fully charged, as it charges when the USB is connected. I've also tried a different computer, along with a different USB cable.

body:
Try this:

First: you must find the COMx used for your "Arduino Leonardo" in the "Device Manager" of Windows.

Second: make double click to see the properties of the device, and go to the "Port configuration tab"

Third: enter in "Avanced Options" and deactivate "Use FIFO buffers", and accept all changes.


message:
SPI Arduino Due conflict with pinMode(), bug?

Consider the following minimal example, where I set `pinMode` before calling SPI functions:

    #include <SPI.h>

    void setup() {
      pinMode(10, OUTPUT);
      SPI.begin(10);
      SPI.setDataMode(10,SPI_MODE1);
    }

    void loop() {
      delay(1000);
      SPI.transfer(10,1);
    }

Now when `SPI.transfer(10,1)` is called in `loop()`, I always see that the slave selected pin goes down to 1.65V, but not 0 as it should! (see image below)

![pin mode set before calling SPI functions][1]

If we don't call `pinMode()`, like this:

    #include <SPI.h>

    void setup() {
      SPI.begin(10);
      SPI.setDataMode(10,SPI_MODE1);
    }

    void loop() {
      delay(1000);
      SPI.transfer(10,1);
    }

We get what we would expect when calling `SPI.transfer`:

![pin Mode not set][2]

Is that a bug or do you have an explanation for that behaviour?

Thank you very much in advance for your time and interest!

  [1]: https://i.stack.imgur.com/oAruY.jpg
  [2]: https://i.stack.imgur.com/Wxn6b.jpg

body:
It might have something to do with the internal pull up resistor. According to the SAM3X/A datasheet,

> Control of the pull-up resistor is possible regardless of the
> configuration of the I/O line.
>
> After reset, all of the pull-ups are enabled.

If you dig through all the include files you find:

    ../Arduino/hardware/arduino/samd/cores/arduino/wiring_digtal.c

Line 124 defines the `pinMode(uint32_t ulPin, uint32_t ulMode)` function. Examining the switch/case statement for INPUT vs INPUT_PULLUP vs OUTPUT you see the following:

 1. INPUT sets a register to `reg = PORT_PINCFG_INEN`.
 2. INPUT_PULLUP sets a register to ` reg = (PORT_PINCFG_INEN | PORT_PINCFG_PULLEN)`
 3. OUTPUT sets a register to `reg &= ~PORT_PINCFG_INEN`.

The 'register' in each case is the same. I cannot for the life of me find what value PORT_PINCFG_INEN or PORT_PINCFG_PULLEN are defined as, but they're no doubt just 8-bit masks (they're cast to uint8_t when they're assigned to the 'register'). Thus, we can assume that whichever bit controls input/output is active when asserted, as is the pullup bit. For example:

     PORT_PINCFG_INEN   = b'00000001';
     PORT_PINCFG_PULLEN = b'00000010';
    ~PORT_PINCFG_INEN   = b'11111110';

If pull-ups are enabled after reset, we can say that on reset:

     reg = b'xxxxxx1x';

Point (3) above strongly implies that the instruction is:

     reg = b'xxxxxx1x' & 'b11111110';
       so
     reg = b'xxxxxx10'; // pull-up is enabled!

Therefore, *if you call pinMode(X, OUTPUT) before anything else* you will end up with the pullup resistor enabled. Setting the pin to an input will clear the pullup enable bit, after which you can set the pin to an output and the bit will remain clear.

However, the whole arguement falls down with the simple fact that if you don't call pinMode() **at all**, the problem doesn't occur...


message:
Servo limitations vs SoftwareServo

I heard that Servo library cannot send and receive from other arduinos without inturrupting the timer and messing up the motors. SoftwareServo is supposedly the answer to this. Is this true? Neither libraries are working for this problem at the moment.

body:
I'm not sure which SoftwareServo library you are talking about, but with regards to the built in "Servo.h", no, it will not disrupt the arduino's other communication abilities, and they will not disrupt it.

I've used servos simultaneously with Serial, I2C, and SPI before and never had any problems.

The servo library does use a timer, but it will only conflict with an external library or code that uses the same timer. Which timer it uses depends on the board, just look in libraries/Servo/src/avr/ServoTimers.h to see which it uses, in what order as they fill up. Filling one up takes effort though, by default it puts up to 12 servos on each timer. The processing overhead is very low since they only update at 50Hz, so that will not become a problem.


message:
All the differences between Arduinos: Pro Mini & Pro Micro

I'd like to know the differences between these two boards: [Arduino Pro Mini][1] and [Arduino Pro Micro][2].

Even if I've read [this][3] and [this][4] related post, it is not clear enough. I've always used the Arduino Uno or Leonardo and I'm a little bit scared of using these compact miniaturised boards.

I have seen so far those differences:

- The Micro doesn’t need the separate FTDI, while the Mini does
- The Micro takes more time to boot up due to USB device (keyboard/mouse) emulation (is more like a Leonardo than an Uno)
- They both have 5 V and 3.3 V versions
- The Mini has 2 more digital IO and 2 more analog Inputs (1 more PWM)
- The pinout is the same (a shield designed for the Pro Mini is OK also with Pro Micro)
- Micro is more expensive (IF you don't have already an FTDI cable).

So, what I care about most is the boot up time (because it could make debug harder) but other than that.. if I don't need the 2 more Digital IO and the 2 more Analog Inputs.. why buy one over the other?

And some more question: can I use the Mini boot loader inside the Micro to avoid the boot up time (if I do not need the keyboard/mouse emulation)?

Is the power consumption the same? Can I use the same battery?

Sorry if this is a silly question but I'm little bit confused.

  [1]: https://www.sparkfun.com/products/11113
  [2]: https://www.sparkfun.com/products/12640
  [3]: https://electronics.stackexchange.com/questions/96805/how-to-program-arduino-nano-pro-mini-pro-micro-clone-that-has-no-usb-port
  [4]: https://www.sparkfun.com/arduino_guide

body:
It is more the differences between ATMega328P + FTDI (Pro Mini) vs ATMega32u4 (Pro Micro)

Apart from the minor pin differences, the peripherals for both MCUs are the same. The major difference is the ATMega32u4 has built in full-speed USB. This allows the board to function as a USB device by implementing the appropriate USB stack. E.g. it can act as a

 - USB to serial converter (CDC device)
 - Keyboard or mouse (HID device)
 - USB hard drive (MSC device)
 - MIDI controller
 - and more...

The LUFA library from AVR devices can be used for this but means going outside of the Arduino IDE and compiling proper C code using the latest avr-gcc tools.

The Arduino core library has built-in support for the HID and CDC device profiles. The CDC profile is used for comms with the Leonardo, Micro, etc. while the HID profile is used for keyboard / mouse emulation.

The Leonardo / Micro boot loader implements a CDC profile for communications with the PC. This CDC profile uses Arduino vendor and product ids so unlike FTDI devices, requires an extra step to install an `*.inf` file on Windows.

You would have to recompile the Pro Mini bootloader for the Micro, but even then it would require an FTDI board as programming would need to be done via the TX and RX UART pins. If you we going to go to all that trouble you could just recompile the proper boot loader to have a shorter time out. Why is difference of 1 or 2 seconds in boot loader time important?

The ATMega32u4 uses more power than the ATMega328P.


body:
In addition to what @geometrikal says (excellent answer, BTW) ATMega32u4 has 5 available true hardware interrupts (so-called "external"), whereas ATMega328p only has 2.

IMHO, that is a key advantage for some applications.


body:
> So, what I care about most is the boot up time (because it could make debug harder)

still couldn't figure out the link between boot up time and debug.

> but other than that.. if I don't need the 2 more Digital IO and the 2 more Analog Inputs.. why buy one over the other?

sounds like there is no reason for you to the other board.

> And some more question: can I use the Mini boot loader inside the Micro to avoid the boot up time (if I do not need the keyboard/mouse emulation)?

the only way to avoid boo up time in anything, pro mini or pro micro, is to not boot it up. you cannot have boot up time if you don't boot it up.

As to the two boards, they use different avrs. the U4 has amazing analog features, but most pro micros don't route out AIN0/AIN1 - rendering them as the same as pro mini. that's a shame.

obviously, if you don't use those features,  they have no value to you and cannot justify the premium / added complexity.


body:
Arduino Pro Mini
[![Arduino Pro Mini][1]][1]
[Pin Mapping][2]

Arduino Micro
[![Arduino Micro][3]][3]
[Pin Mapping][4]
[![ArduinoMicro_Pinout3.png][5]][5]

The Arduino page for the [Arduino Pro Mini][6] and the [Arduino Micro][7].

**Microcontroller**
Arduino Pro Mini: ATmega328 (ATmega168 on older boards)
Arduino Micro: ATmega32U4

**Memory**
Both have 32KB of Flash and 1KB of EEPROM
The Arduino Pro Mini has 2KB of SRAM where as the Arduino Micro has 2.5KB

**Digital I/O**
The Arduino Pro Mini has 14 (of which 6 provide PWM output)
The Arduino Micro has 14 also (of which 7 provide PWM output)
Some of the analog pins can also be used as digital I/O

**Analog Inputs**
Arduino Pro Mini: 8 (some boards only break out 6 analog inputs)
Arduino Micro: 12 ([6 dedicated and 6 from digital I/O pins][8])

**USB**
Arduino Pro Mini: Requires FTDI cable or Sparkfun breakout board to provide USB power and communication to the board.
Arduino Micro: Native USB

**Clock**
Both are 16 MHz (although the 3V Arduino Pros run at 8MHz)

**Power**
There are two version of each of the Arduinos. One runs at 3.3V and 8 MHz, the other at 5V and 16 MHz.
Arduino Pro Mini: VRAW  can accept voltage up to 12VDC.
Arduino Micro: USB or external supply of 6 to 20 volts (recommended range is 7 to 12 volts)

**Interrupts**
Arduino Pro Mini: The Atmega328 has 2 hardware interrupts available
Arduino Micro: The ATMega32u4 has 5 hardware interrupts available
credit: [Enric Blanco][9]

  [1]: https://i.stack.imgur.com/LKcvq.jpg
  [2]: https://cdn.sparkfun.com/datasheets/Dev/Arduino/Boards/ProMini16MHzv1.pdf
  [3]: https://i.stack.imgur.com/l4hOF.jpg
  [4]: https://www.arduino.cc/en/Hacking/PinMapping32u4
  [5]: https://i.stack.imgur.com/IbHDG.png
  [6]: https://store.arduino.cc/usa/arduino-pro-mini
  [7]: https://store.arduino.cc/usa/arduino-micro
  [8]: https://www.arduino.cc/en/uploads/Main/ArduinoMicro_Pinout3.png
  [9]: https://arduino.stackexchange.com/a/34577/19409


message:
Using XBee and OLED screens with Timer Interrupts

I have an Arduino board with a sensor, an OLED screen and an XBee module. I've setup the timer interrupts in timer1 to sample the sensor every one second.
I've done the following:

 - tried to update the OLED screen with the reading and it works.
 - tried sending the reading from inside loop over XBee and it works.
 - tried doing both of the above and the Arduino seems to shut down after a bit.
 - tried sending the reading from inside the timer interrupt handler and it doesn't work.

Are there limitations on what interrupt handlers can do that I'm not aware of? (Other than using time delays)

**Source code**

    #include <XBee.h>
    #include <SPI.h>
    #include <Wire.h>
    #include <Adafruit_GFX.h>
    #include <Adafruit_SSD1306.h>

    XBee xbee = XBee();
    ZBRxResponse response = ZBRxResponse();
    ZBTxRequest sensorml_level_0_zbTx = ZBTxRequest(addr64, sensorml_payload_level_0,sizeof(sensorml_payload_level_0));
    ZBTxRequest keepalive_level_0_zbTx = ZBTxRequest(addr64, keepalive_payload_level_0,sizeof(keepalive_payload_level_0));

    union u_tag {
       uint8_t b[4];
       float fval;
    }
    u;

    void setup() {
       display.begin(SSD1306_SWITCHCAPVCC);
       Serial.begin(9600);
       xbee.setSerial(Serial);
       noInterrupts();
       TCCR1A = 0;
       TCCR1B = 0;
       TCNT1  = 0;
       OCR1A = 62500;
       TCCR1B |= (1 << WGM12);
       TCCR1B |= (1 << CS12);
       TCCR1B |= (1 << CS10);
       TIMSK1 |= (1 << OCIE1A);
       interrupts();
    }

    ISR(TIMER1_COMPA_vect){
       reading =  analogRead(SENSORPIN);
       reading = (1023 / reading)  - 1;
       reading = SERIESRESISTOR / reading;
       reading = -0.15784 * reading + 305.17;
       sendObservation(reading,00);
    }

    void sendObservation(float value, int id){
       char idBuffer[] = "00";
       sprintf(idBuffer,"d",id);
       uint8_t frame[] = {'0','1','|','0','0','#','0','0','0','0'};
       frame[3] = idBuffer[0];
       frame[4] = idBuffer[1];
       u.fval = value;
       for (int i=6;i<10;i++){
          frame[i]=u.b[i-6];
       }
       ZBTxRequest request = ZBTxRequest(addr64, frame, sizeof(frame));
       xbee.send(request);
    }

I skipped most variable declarations to keep the code short.

body:
I suspect `send()` is blocking.

`XBee::send()` calls `_serial->flush()` (see [code](https://code.google.com/p/xbee-arduino/source/browse/XBee.cpp#1461)). `Serial.write()` buffers data to be written, sets `transmitting = true`, clears `TXC0` and enables the USART data register empty (DRE) interrupt. Bytes will be sent out when the DRE interrupt triggers. However, since you are currently in interrupt context, this will not happen until your ISR returns. `flush()` spins until `TXC0` is set, but since the DRE interrupt never triggers, it spins infinitely. I am basing this on [this code](https://github.com/arduino/Arduino/blob/master/hardware/arduino/cores/arduino/HardwareSerial.cpp#L455).


message:
Arduino Nano and a 3.3v Ethernet shield

I plan on purchasing [a Nano clone][1], an Ethernet shield [(ENC28J60)][2], an LCD and a DHT22 humidity + temperature sensor. This will be used in a wine cellar to monitor relative humidity and temperature.

The DHT sensor, LCD and Nano all operate on 5V logic. The Ethernet shield does not operate at 5V, but rather at 3.3V.

Does the Nano have a way to connect the two, will they work anyway (probably not), or should I use a CD4050 that is recommended on adafruit?

Any guidance is appreciated; I'm still amazed in what $10 in parts can do.

Also, in regards to the DHT22 sensor, what do I need in terms of a resistor? I've seen some people say you absolutely need a 4.7K resistor on the data pin for "pull up", and  others who say it's unnecessary. Can someone give a definite answer, either way?

Edit, wrong link on my nano clone.

  [1]: http://www.ebay.com/itm/3PCS-Nano-V3-0-ATmega328-controller-Board-5V-16M-CH340G-USB-Driver-For-Arduino-/381019048475?pt=LH_DefaultDomain_0&hash=item58b6814a1b
  [2]: http://www.ebay.com/itm/New-ENC28J60-Ethernet-LAN-Network-Module-For-Arduino-SPI-AVR-PIC-LPC-STM32-BDRG-/301354703227?pt=LH_DefaultDomain_0&hash=item462a23d97b

body:
Just get [one with a 3.3v regulator on it](http://www.ebay.com/itm/3-3V-5V-ENC28J60-LAN-Ethernet-Network-Module-Dual-MOS-For-Arduino-MCU-AVR-51-LPC-/171310795997?pt=LH_DefaultDomain_0&hash=item27e2eb4cdd). PS logic levels are allowed to be 5v.

DHT22 and LCD will also work fine on 3.3v so, alternatively, you could also get a 3.3v Nano.

The resistor value for the DHT22 depends on the length of wire between the DHT and Nano. Just buy them to be sure, or get a breakout board that already has them on the board (along with a capacitor, which is nice).


message:
Necessary sampling rate

I'm using an Arduino pro mini to receive the analog signals from three sensors. I was wondering what sampling rate I should sample at in order to properly represent these signals. I know it should be twice the highest analog frequency, but I'm not sure what frequency theses sensors operate in. They're an ECG, a 3 axis accelerometer, and a stretch resistor respectively. To my knowledge, Arduino defaults at a sampling rate of 10kHz, which I believe should be more than enough to quantize the sensor signals. I'm then sending these signals out using bluetooth mate to an android phone. Is there a specific baudrate I should send the data at?

Here is the initialization of my code:

    void setup()
    {
      Serial.begin(9600);
      bluetooth.begin(115200);
      bluetooth.print("$$$");
      delay(100);
      bluetooth.println("U,9600,N");
      bluetooth.begin(9600);
      setTime(0);
    }

Thanks so much

body:
The sampling frequency you are referring to (twice the highest frequency) is for capturing waves, but is not really a concern for the sensors you are using and the types of data they are used to measure.

If you wanted to analyse the magnitude of a 40kHz vibration in a structure, you should worry about sampling rates on your accelerometer; however, if you want to measure the accelerometers current angle to the ground (assuming its not accelerating), you only need to take one sample.

With the ECG, there will be a signal among all the analog voltages you read of a heartbeat (I'm assuming its hooked up to a person). This signal will never get much over 200 beats per minute, or 3.3 Hz. To capture a 3.3Hz signal you need a minimum sampling rate of 6.6Hz, which as still incredibly slow. The same goes for capturing a gait with your accelerometer.

If you capture the analog voltage of your sensors output with analogRead 100 times a second, you should have a very clear and well defined view of the very low frequency signals you are trying to track, and should not have any issues with transferring that much information over serial.

5, 16 bit values can theoretically be sent at 120Hz over 9600 baud, and its very easy to use faster speeds then that if you want more information.


body:
Since I think BrettAM already gave a pretty good answer, I'm going to expound just a little upon that.

First off: I think you're misunderstanding sample rate. The sample rate here is simply the number of analog readings per second that you are doing of a given signal.

If you want to know the **maximum** sample rate of the Arduino, you simply have to take a ton of samples as fast as you can and see how many you were able to take in a given second. For the Arduino with default settings, that's ~9600 per second *maximum*. If you just take 1 single sample though, your sample rate is......I don't know.....how often do you do this!? If you take 1 sample and then stop your sketch for an hour, your sample rate for that one sample was 1 sample per hour. Now, what are you sampling? If what your're sampling is *changing* faster than one noticeable change (ADC resolution step) per hour, then you need to sample faster than once per hour. If your signal (what you're sampling) is changing at 100 times per second (100Hz), however, then you need to sample at *at least* 200 Hz to even detect it's changing at 100Hz, and at *approximately 1000Hz or higher* to actually plot what that 100Hz signal looks like. Note: sampling at 2x the rate of the sampl**ed** signal is the minimum sample rate required to detect the frequency of the sampl**ed** signal, and is called the [Nyquist Frequency](http://en.wikipedia.org/wiki/Nyquist_frequency). Sampling at 10x the sampl**ed** signal is the generally-accepted rule-of-thumb for minimum sample rate required to capture the *waveform,* or *shape* of the sampl**ed** signal.

Now, let's look into data smoothing. If you just take a single sample, it might bounce around. How do you stop this? One method, is to take many samples and average the result. A library I wrote does this, among many other things, so I'll present it here.

Taking many samples in a row then using the average of the samples in any calculations helps to remove the noise component from your signal. I have written an oversampling library that among other things, does just that. An (outdated..will be updated eventually) page on it is here: [Using the Arduino Uno’s built-in 10-bit to 21-bit ADC (Analog to Digital Converter)](http://www.electricrcaircraftguy.com/2014/05/using-arduino-unos-built-in-16-bit-adc.html#.VVqTlPlViko).

The current version of the code is V2.1 alpha, and the download link is currently highlighted in yellow at the link above.

In case you need to take faster samples, you can also speed up the ADC sample rate to 50+ kHz, using my library...as opposed to settling on the default 9600Hz of the Arduino.

Play around with sampling and smoothing and stuff.  One technique is to speed up the ADC (so you don't waste too much time sampling), then take the avg. of many samples in order to help remove noise from your sensors. This may be unnecessary, if noise is minimal or changes over time on the signal are slow, but for the sake of learning I'll present this.

Here's an example sketch:

    //include the library
    #include <eRCaGuy_NewAnalogRead.h>

    //Global Vars
    byte pin = A0;
    byte bitsOfResolution = 10; //commanded oversampled resolution
    unsigned long numSamplesToAvg = 50; //number of samples AT THE OVERSAMPLED RESOLUTION that you want to take and average

    void setup()
    {
      //Configure the adc how you want it
      adc.setADCSpeed(ADC_PRESCALER_16_CLOCK_1MHZ); //this speeds up the ADC clock by a factor of 8
    }

    void loop()
    {
      //local variables
      unsigned long analogReading;

      //take a reading on the analog pin
     analogReading = adc.newAnalogRead(pin,bitsOfResolution,numSamplesToAvg);
    }

You'll see that I am speeding up the ADC and taking and averaging 50 samples to smooth the data. I have yet to test the speed, but I estimate this could prob. run at 500Hz or so max sample rate (returning an average value each time)...assuming that's all you did.

Doing this and taking a single sample is fine for what you need I believe.

Now, for baud rate. Baud rate is essentially "bits of data sent per second." It's how fast your communication signal is. Lower baud rates are generally less susceptible to electrical noise, and the data is less likely to get corrupted, but higher baud rates send the data values much more quickly and waste less of your code time sitting around transferring data. I recommend you speed it up to maximum, unless you have data transfer problems or dropouts, in which case you should slow it down a bit.

NOTE: for more detailed examples on the library download it and look in the examples folder.


message:
References (e.g, libraries and tutorials) for connecting the 24-bit ADS1256 ADC to arduino

The [ADS1256 chip][1] is a high precision 24bit, 8 channel, analog digital converter based on SPI communication that is suitable for biomedical applications and perfect for sensing ECG and EEG signals. I want to hook it up to an arduino, e.g., an arduino mega or an arduino due.

Similar ADCs from analog devices are: ADS1248, ADS1251, ADS1252, ADS1252U, ADS1253, ADS1255, ADS1259, ADS1278, ADS1298, ADS1299, etc.

It’s nice that there are [tiny, coin sized breakout boards]  available for the ADS1256 that include basic components like an 8mhz quartz crystal and cost only around 25 USD.

Several people have in the past struggled to get ADC readings using Arduino. Working only with the data sheet it took them several days or even weeks. I have a logic analyzer, multi channel oscilloscope and [bus pirate][2] ready, but I still would prefer adapting an existing library or working with a good tutorial as a starting point.

I searched for code and tutorial not only for the ADS1256 but also for similar analog devices ADC chips.

Here are the tutorials, libraries and information I found so far:

**Main Links (working solution):**

-- [ADS1213 Arduino library][3] (seems to be working!!!)

--  [ADS1213 Arduino tutorial][4] (includes above library)

**Further Information:**

- [Arduino due ADS129X tools(ADS1299, ADS1298, ADS1294, ADS1296)][5]

- [ADS1252 Arduino Tutorial][6]

- [ADS1252 Troubleshooting information][7]

- [ADS1255 Troubleshooting information][8]

- [ADS 1298 Troubleshooting information][9]

- [ADS 1248 and arduino (german)][10]

**Q:**
Is there a working library for the ADS1256 (or similar chip) and is there a current, up-to-date tutorial available for arduino?

----------

(Update with my notes.)

**Next steps** (to get a working library that should be put on github):

 1. Search for more relevant Information online (existing libraries, etc.)
 2. Ask in AVR specific forum, if question is unanswered here. Possibly contact people via e-mail that could know more
 3. Get familiar with Chip and Datasheet
 4. Decide on available codebase as the starting point
 5. Define the minimalistic testcase (This would check that some for of communication works with the chip, i.e., write register that changes the logic level of a bin of the ADC chip)
 6. Implement the minimalistic testcase (i.e., possibly use different codebase as starting point if it fails to implement)
 7. Expand and test the code to get a full implementation

**Risks:** Eittle experience with electronic design the microcontroller at hand, might miss important details that costs a lot of time. Can't be sure that my chip/PCB actually works, can be faulty hardware.

**Time Estimate**: 3 days of work doing 8 hours a day (total 24 hours). Exremly high variance (could be a matter of a few hours in the best case to a few weeks worst case).

  [1]: http://www.ti.com/product/ads1256
  [2]: http://dangerousprototypes.com/docs/Bus_Pirate
  [3]: http://arduino.cc/forum/index.php?action=dlattach;topic=53063.0;attach=15873
  [4]: http://forum.arduino.cc/index.php?PHPSESSID=q3dffkh8l0t6i89mljk3fcj603&topic=53063.0
  [5]: https://github.com/adamfeuer/ADS129x-tools
  [6]: http://forum.arduino.cc/index.php?topic=57873.0
  [7]: http://e2e.ti.com/support/data_converters/precision_data_converters/f/73/t/272825.aspx
  [8]: http://e2e.ti.com/support/data_converters/precision_data_converters/f/73/t/272825.aspx
  [9]: http://e2e.ti.com/support/data_converters/precision_data_converters/f/73/t/168648.aspx
  [10]: http://www.mikrocontroller.net/topic/302404

body:
You are lucky. Looks like there is an Arduino library available for the ADS1256. You should give it a shot: https://github.com/Flydroid/ADS12xx-Library .

I haven't tested it but checked the registers and functions from the datasheet and it does look good.


message:
Connect multiple I2C to an Uno

Is it possible to use more than 1 device that needs to use SDA for I2C with a mini?
Would you use a different analogue pin with a 10k pull up resistor and tie all of the devices to the SCL?

body:
> Is it possible to use more than 1 device that needs to use SDA for I2C with a mini?

Yes, provided they have unique I2C addresses.

> Would you use a different analogue pin with a 10k pull up resistor and tie all of the devices to the SCL?

No. All of the devices must be tied to both SDA and SCL. You may need a smaller resistor depending on how many devices there are; see NXP document UM10204 for details.


message:
Sainsmart LCD 2004 - LiquidCrytal_I2C library issue unable to compile

I bought a Sainsmart LCD2004 from Amazon to use with my Arduino Uno.
I understand that since this LCD uses I2C a new library needs to be downloaded.

From the sainsmart website I dowloaded the LCD 2004 rar
http://www.sainsmart.com/arduino/arduino-shields/sainsmart-iic-i2c-twi-serial-2004-20x4-lcd-module-shield-for-arduino-uno-mega-r3.html

When I try to compile the example titled helloworld I get the following error:

*In file included from HelloWorld.pde:3:
C:\Users\r_yob_000\Documents\Arduino\libraries\LiquidCrystal_I2C/LiquidCrystal_I2C.h:81: error: conflicting return type specified for 'virtual void LiquidCrystal_I2C::write(uint8_t)'
C:\Program Files (x86)\Arduino\hardware\arduino\cores\arduino/Print.h:48: error:   overriding 'virtual size_t Print::write(uint8_t)'*

There seems to be a conflict between two functions returning different types.

I've tried searching the issue and found a lot of posts with similar errors.
The solution suggested is usually that a new version of the LiquidCrytal_I2C needs to downloaded. Or that one should use Arduino IDE version 1.0

I have downloaded tons of LiquidCrytal_I2C libraries and tried them all on IDE version 1.0 and 1.0.6 and I still get the same error message. I've even tried changing the LiquidCrytal_I2C.h file so that it returns the correct type and still have no luck.

Could I please get some help with this issue.

Thank you very much.

body:
I just bought 3 of these that work well with this library
 [LiquidCrystal_I2C2004V1.zip](http://arduino-info.wikispaces.com/file/detail/LiquidCrystal_I2C2004V1.zip)
(*License: CC BY-NC 2012 http://www.wikispaces.com/user/view/TerryKing*).

When installing this library in Arduino IDE (version 1.6 or later), use menu item **Sketch | Include Library | Add .ZIP Library...**, navigate to the folder where LiquidCrystal_I2C2004V1.zip was downloaded, and then open the zip file.

Use the I2C address in the example "HelloWorld" supplied with LiquidCrystal_I2C2004V1:

    //YWROBOT
    //Compatible with the Arduino IDE 1.0
    //Library version:1.1
    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>

    LiquidCrystal_I2C lcd(0x27,20,4);  // set the LCD address to 0x27 for a 16 chars and 2 line display

    void setup()
    {
      lcd.init();                      // initialize the lcd
      lcd.init();
      // Print a message to the LCD.
      lcd.backlight();
      lcd.setCursor(3,0);
      lcd.print("Hello, world!");
      lcd.setCursor(2,1);
      lcd.print("Ywrobot Arduino!");
       lcd.setCursor(0,2);
      lcd.print("Arduino LCM IIC 2004");
       lcd.setCursor(2,3);
      lcd.print("Power By Ec-yuan!");
    }

    void loop()
    {
    }

Do not change the other library directory name; this one is compatible with the existing library. Just add it as a contributed library.


body: I had problems with this library too, until I realized the default library name "LiquidCrystal" conflicts with that of another library, which makes that the files get mixed up. Simply place the files in a different folder (I named mine) "LiquidCrystal_4x20". Solved it for me.


body:
You must to upgrade your I2C library.

Here you can find it the last version:
https://bitbucket.org/fmalpartida/new-liquidcrystal/downloads/

And move the old one in another folder so you can  use this one
or after you install this one do like this:

1. Go in the `Arduino\libraries\Newliquidcrystal_1.3.5\`
2. Rename the `LiquidCrystal_I2C.h`  like `LiquidCrystal_I2Ca.h`
3. When you use it in the sketch use include `LiquidCrystal_I2Ca.h`


message:
0.96" OLED and Arduino UNO usage error

I have Arduino UNO with 0.96" OLED display with 128(width)*32(height). It is said that I have to edit Adafruit_SSD1306.h for my 128*32 OLED, okey I did it from 128*64 to 128*32 but I still get the compiler error:

    ssd1306_128x32_i2c.ino:54:2: error: #error ("Height incorrect, please
    fix Adafruit_SSD1306.h!");

Yes, I fixed the Adafruit_SSD1306.h file, **but now,** it is still gives me a compiler error:

    C:\Users\OB\Documents\Arduino\libraries\Wire\utility/twi.h: In member
    function 'uint8_t TwoWire::requestFrom(uint8_t, uint8_t, uint8_t)':
    C:\Users\OB\Documents\Arduino\libraries\Wire\utility/twi.h:47: error:
    too many arguments to function 'uint8_t twi_readFrom(uint8_t,
    uint8_t*, uint8_t)'
    C:\Users\OB\Documents\Arduino\libraries\Wire\Wire.cpp:85: error: at
    this point in file
    C:\Users\OB\Documents\Arduino\libraries\Wire\utility/twi.h: In member
    function 'uint8_t TwoWire::endTransmission(uint8_t)':
    C:\Users\OB\Documents\Arduino\libraries\Wire\utility/twi.h:48: error:
    too many arguments to function 'uint8_t twi_writeTo(uint8_t, uint8_t*,
    uint8_t, uint8_t)'
    C:\Users\OB\Documents\Arduino\libraries\Wire\Wire.cpp:140: error: at
    this point in file
    C:\Users\OB\Documents\Arduino\libraries\Wire\Wire.cpp: In member
    function 'virtual size_t TwoWire::write(const uint8_t*, size_t)':
    C:\Users\OB\Documents\Arduino\libraries\Wire\Wire.cpp:195: error:
    invalid conversion from 'const uint8_t*' to 'uint8_t*'
    C:\Users\OB\Documents\Arduino\libraries\Wire\Wire.cpp:195: error:
    initializing argument 1 of 'uint8_t twi_transmit(uint8_t*, uint8_t)'

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

How can I use my four-pin OLED display with no errors?

  [1]: https://i.stack.imgur.com/A6Wbj.png
  [2]: https://i.stack.imgur.com/zAblZ.jpg

body:
May I suggest the following. I found this fork of the Adafruit library which works better than the one they have on their website [Adafruit_ssd1306syp][1]. The original `Adafruit_ssd1306` library doesn't play nice with SPI and when you want to have your OLED running on i2c and use the SPI for something else. This is a great resource. Download, unzip to your libraries directory. Then run this sketch:

    #include <Adafruit_ssd1306syp.h>

    #define SDA_PIN A4
    #define SCL_PIN A5

    Adafruit_ssd1306syp display(SDA_PIN, SCL_PIN);

    void setup() {

      display.initialize();
      display.setTextSize(1);
      display.setTextColor(WHITE);
      printM("Starting Demo...");

    }

    void printM(String mess) {

      display.println(mess);
      display.update();
    }

    void loop() {

      printM("working");
      delay(1000);

    }

  [1]: https://github.com/Miyeah/Arduino-Dormitory-Assistant/tree/master/library/Adafruit_ssd1306syp


message:
Lily Pad mp3, nested loops with timing and play randomly choosen mp3, coding problem

The best way to explain my problem is in form of code...

        const int ringerPin = A0;
        const int offhook = A4;
        const int onhook = A5;

        void setup(){
        pinMode(ringerPin, OUTPUT);
        pinMode(offhook, INPUT);
        pinMode(onhook, INPUT);
        randomSeed(analogRead(0));

      }

      int randCall = random(60000, 3600000); // generate a random number between 1 min and 60 min

    //ring every 1 to 60 minutes if the phone is down (hookon) and dont ring if the phone is picked up (no hookon)
    void loop()
    {
      if (digitalRead(hookon) == HIGH)

    void loop(){
    delay(randCall);

          //i dont know how to let this loop below here run for 30 seconds.
     void loop()
        {
          //turn audio off - i dont know how to.
        for(int x = 0; x < 15; x++){
          digitalWrite(ringerPin, HIGH);
          delay(50);
          digitalWrite(ringerPin, LOW);
          delay(80);
        }
        delay(2500);
        }
      else
        //play one randomly choosen audiofile out of 10 - i dont know how to
    }
    }

Maybe you can give me some suggestions to my coding problems.?
I wrote them inside the code descriptions.

body:
Halo, thank you for ansering anything.. I got the loop loop loop thing now runin..

So its about playing an Audiofile if hookon == LOW ........ check it out :-)

The code now looks like this.

    const int ringerPin = A0;
    const int offhook = A4;
    const int onhook = A5;
    double beginRing = -40000;

    void setup(){
        pinMode(ringerPin, OUTPUT);
        pinMode(offhook, INPUT);
        pinMode(onhook, INPUT);
        randomSeed(analogRead(0)); // this starts Arduino's random number generator
    }

    int randCall = random(60000, 3600000); // generate a random number between 1 min and 60 min

    //ring every 1 to 60 minutes if the phone is down (hookon) and dont ring if the phone is picked up (no hookon)
    void loop()
    {
      if (digitalRead(hookon) == HIGH){
        delay (randCall);
        beginRing = Time.elapsedTime;
        while(Time.elapsedTime - beginRing <= 30000 && digitalRead(hookon) == HIGH){
          //turn any audio off???
          for(int x = 0; x < 15; x++){
            digitalWrite(ringerPin, HIGH);   // turn the solenoid on (HIGH is the voltage level)
            delay(50);                           // wait for 50 msec
            digitalWrite(ringerPin, LOW);    // turn the solenoid off by making the voltage LOW
            delay(80);                          // wait for 50 msec
          }
          delay(2500);
        }
      }
      if(Time.elapsedTime - beginRing <= 30000){
        //play one randomly choosen audiofile out of 10
      }
    }

So, now its about to stop any sound if the hookon is HIGH and to play the randomly choosen file 1 out of 10 if the hookon is LOW (its in the code as description...there i need the right comands)


message:
Make upload stuck on osx 10.10 bare-arduino-project

I followed the instructions in [here](https://github.com/WeAreLeka/Bare-Arduino-Project/blob/master/INSTALL.md), including to use arduino IDE v 1.0.5, but when I tried to `make upload` it stuck. I can upload it when using Arduino IDE.

Here is what I got:

      mkdir -p /Users/bagustrihatmaja/Documents/Projects/MyAwesomeProject/bin/mega328/mySecondProject
     /Applications/Xcode.app/Contents/Developer/usr/bin/make reset
     /Users/bagustrihatmaja/Documents/Projects/MyAwesomeProject/Arduino-Makefile/bin/ard-reset-arduino  /dev/cu.usbmodem1421
     /Applications/Xcode.app/Contents/Developer/usr/bin/make do_upload
     /usr/local/bin/avrdude -q -V -D -p atmega328p -c arduino -b 57600 -P /dev/cu.usbmodem1421 \
   -U flash:w:/Users/bagustrihatmaja/Documents/Projects/MyAwesomeProject/bin/mega328/mySecondProject/mySecondProject.hex:i

What did I miss?

I use: Bare-Arduino-Project, OSX 10.10, XCode 6.1, Arduino Uno, [my Makefile](http://pastebin.com/cR79Sqqz)

body:
I'm the maintainer of the Bare-Arduino-Project, thanks for using it :)

Have you installed `pyserial` and `avrdude`?

To install `avrdude` just run `brew install avrdude` and to install `pyserial`, you need `python installed`, then you can run `pip install pyserial`.

https://github.com/WeAreLeka/Bare-Arduino-Project/blob/master/INSTALL.md#3-install-pyserial

Hope it helps :)

Next time, feel free to open an issue in the Github repo as it might also help others.

**EDIT:** my bad, I did not read your Makefile carefully!

the problem is with:

    BOARD_TAG         = mega328
    # it should be
    BOARD_TAG         = uno


message:
What is the best way to measure PWM signals ( pulseIn ) with the Arduino via a Raspberry Pi?

I connected my Arduino Uno to my raspberry via USB serial. I'm able to read out both digital and analog pins of my Arduino using the Python nanpy library (v.0.8).
However, I can't find support for the pulseIn() function. It seems nanpy doesn't support pulseIn() at all.

What is the best way to measure PWM signals with the Arduino and forward the results to the Raspberry Pi?

I am able to measure PWM using the Arduino GUI, however I would to take PWM samples at fixed time intervals over a long period of time and combine this data with other measurements that my Raspberry is making.I also tried pyFirmata, but it doesn't support pulseIn() measurements either.

body:
Nanpy seems to have a [CounterClass](https://github.com/nanpy/nanpy-firmware/blob/master/Nanpy/CounterClass.cpp) that does frequency measurements.

Or do you want to measure the PWM duty-cycle?


body:
You can just have a sketch in the arduino that takes the measurements at whatever interval you want using the `analogRead(pin)` function and then forward those results to the raspberry pi via serial using `Serial.print(whatever you want here)`. If you don't know how to use serial with arduino just go to their site, they have very good documentation.
Hope that helps :)


message:
Sense distance with Bare Conductive's Touch Board

How can I sense distance with Bare Conductive's Touch Board, like they suggest in [their product video][1]?

I know how I can set the touch and release thresholds, so my Touch Board is more sensitive and triggers before I touch a sensor. What I want to do is get the information how near I am. Not in centimeters or so, but a simple value telling me when I'm nearer to or farther from the sensor like in the video.

  [1]: https://www.youtube.com/watch?v=Y3eSrUQTesg&t=27s

body:
As a member of the Bare Conductive team, I can tell you that looking at the [grapher][1] will be helpful to you. The grapher is a processing sketch that requires the Touch Board to be running the [Datastream][2] code. Datastream will give you the sort of raw electrode data that you're looking for.

  [1]: https://github.com/BareConductive/mpr121-grapher
  [2]: https://github.com/BareConductive/mpr121/tree/public/MPR121/Examples/DataStream