body:
    char cTime[22];

    sprintf(cTime, "s/s/%2s:s:s:s", year(), month(), day(), hour(), minute(), second());

This `sprintf` line causes this error:**B0100000063f694Š

Could someone help me debug this?
Thank you.

title: sprintf trouble

Answers: 2

body: *%s* is string macro but output of *year(),...* is probably an integer type. Use *%d* or *%u* macros in format.

body: Yes - try making each of the %-specifiers match the kind of conversion you want for each variable in the rest of the call. F/ex, %d converts an integer to a string in decimal radix, %f converts a double to a number with a decimal fraction, etc. In all cases, the output will be as characters; you don't need to specify that.


body:
I'm trying to get the color sensor TCS3200 to give color values with a delay lower than 4000 ms. I've found a library to interface the TCS3200 from this [link][1].

I've modified the code to serve my needs and its works fine, almost! The before mentioned library uses [TimerOne.h][2], which can not accept a delay lower than 4000 ms.

My question is therefor, if it is somehow possible to modify my code, so I can lower the delay?

This is my code:

<!-- language: c -->

    #include <TimerOne.h>

    #define S0     6
    #define S1     5
    #define S2     4
    #define S3     3
    #define OUT    2

    int   g_count = 0;    // count the frequecy
    int   g_array[3];     // store the RGB value
    int   g_flag = 0;     // filter of RGB queue
    float g_SF[3];        // save the RGB Scale factor

    // Init TSC230 and setting Frequency.
    void TSC_Init()
    {
      pinMode(S0, OUTPUT);
      pinMode(S1, OUTPUT);
      pinMode(S2, OUTPUT);
      pinMode(S3, OUTPUT);
      pinMode(OUT, INPUT);

      digitalWrite(S0, LOW);  // OUTPUT FREQUENCY SCALING 2%
      digitalWrite(S1, HIGH);
    }

    // Select the filter color
    void TSC_FilterColor(int Level01, int Level02)
    {
      if(Level01 != 0)
        Level01 = HIGH;

      if(Level02 != 0)
        Level02 = HIGH;

      digitalWrite(S2, Level01);
      digitalWrite(S3, Level02);
    }

    void TSC_Count()
    {
      g_count ++ ;
    }

    void TSC_Callback()
    {
      switch(g_flag)
      {
        case 0:
             TSC_WB(LOW, LOW);              //Filter without Red
             break;
        case 1:
             g_array[0] = g_count;
             TSC_WB(HIGH, HIGH);            //Filter without Green
             break;
        case 2:
             g_array[1] = g_count;
             TSC_WB(LOW, HIGH);             //Filter without Blue
             break;
        case 3:
             g_array[2] = g_count;
             TSC_WB(HIGH, LOW);             //Clear(no filter)
             break;
       default:
             g_count = 0;
             break;
      }
    }

    void TSC_WB(int Level0, int Level1)      //White Balance
    {
      g_count = 0;
      g_flag ++;
      TSC_FilterColor(Level0, Level1);
      Timer1.setPeriod(1000000);             // set 1s period
    }

    void setup()
    {
      TSC_Init();
      Serial.begin(115200);
      Timer1.initialize();             // defaulte is 1s
      Timer1.attachInterrupt(TSC_Callback);
      attachInterrupt(0, TSC_Count, RISING);

      delay(4000);

      for(int i=0; i<3; i++)
        Serial.println(g_array[i]);

      g_SF[0] = 255.0/ g_array[0];     //R Scale factor
      g_SF[1] = 255.0/ g_array[1] ;    //G Scale factor
      g_SF[2] = 255.0/ g_array[2] ;    //B Scale factor

      Serial.println(g_SF[0]);
      Serial.println(g_SF[1]);
      Serial.println(g_SF[2]);
    }

    void loop()
    {
      g_flag = 0;

        int R = int(g_array[0] * g_SF[0]);
        int G = int(g_array[1] * g_SF[1]);
        int B = int(g_array[2] * g_SF[2]);

        if((R>245) && (R<265) && (G>245) && (G<265) && (B>245) && (B<265))    // White
        {
          Serial.println("Color is white");
        }else if((R>24) && (R<44) && (G>56) && (G<76) && (B>95) && (B<115))  // Blue
        {
          Serial.println("Color is blue");
        }else if((R>56) && (R<76) && (G>107) && (G<127) && (B>80) && (B<100))  // Green
        {
          Serial.println("Color is green");
        }else if((R>171) && (R<191) && (G>154) && (G<174) && (B>71) && (B<91))  // Yellow
        {
          Serial.println("Color is yellow");
        }else if((R>77) && (R<97) && (G>46) && (G<66) && (B>43) && (B<63))  // Brown
        {
          Serial.println("Color is brown");
        }else if((R>39) && (R<59) && (G>38) && (G<58) && (B>36) && (B<56))  // Brown dark
        {
          Serial.println("Color is brown dark");
        }else if((R>20) && (R<40) && (G>43) && (G<63) && (B>48) && (B<68))  // Turkis
        {
           Serial.println("Color is turkis");
        }else if((R>39) && (R<59) && (G>77) && (G<97) && (B>55) && (B<75))  // Green
        {
           Serial.println("Color is green");
        }else
        {
          Serial.print("Red = ");
          Serial.println(R);
          Serial.print("Green = ");
          Serial.println(G);
          Serial.print("Blue = ");
          Serial.println(B);

        };

       delay(4000);
    }

I've searched all over the net and didn't find any good solutions, where I can still specify the colours by hex degree.

All help would be highly appreciated!

  [1]: http://www.elecfreaks.com/5521.html
  [2]: http://playground.arduino.cc/Code/Timer1

title: TCS3200 color sensor not reading with delay lower then 4000 ms using TimerOne.h

Answers: 1

body:
You can increase the frequency (x10) by setting S0 HIGH and S1 LOW. Then you can change the timerone frequency from once a second to once every 100ms (Timer1.setPeriod(100000);). Then you can change your delay to delay(400).

PS I think you only need to wait for a bit over 3 timerone cycles, so delay(350) should also work.


body:
I'm asking if how can I implement this one. I'm aware about multiple devices being connected over SPI, like having to select individual SS pin for each. Adafruit's CC3000 works fine alone along with the default Adafruit library. CC3000 uses SPI. MFRC522 RFID module by sonmicro (bought at Sparksfun) uses SPI too. It works fine too, independently. But whenever I connect them together, only WiFi works perfectly. I dont want to turn on and off the wifi to make way for the RFID to communicate since it takes some time for it to be connected in a wireless network. I want the two to work synchronously (or having to be scheduled but really fast that's unnoticeable by the user)

here's my code as of now. i cannot post it here as strange things happen i don't know why haha https://drive.google.com/file/d/0B0bZsYo0xMH8YV9uWXJaRFdPT3M/view?usp=sharing

I'm thinking of replacing the RFID with SonMicro's SM130 RFID Module w/ SparkFun Eval board with UART (convertible to I2c) or Adafruit's PN532 with I2c by default. Are these okay to be paired with SPIs like the CC3000? Or should I change CC3000 with the Official WiFi module (UART) or WiFly Module (SPI-to-UART)

title: Adafruit CC3000 WiFi Module working together with MFRC522 RFID Module Issues both SPI over Arduino

Answers: 1

body:
I couldn't get your code to download so this might be wrong, but it sounds like the modules are running different SPI modes: http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus#Mode_numbers

I had this problem a few years ago. You'd expect SPI to be SPI, but it comes in four different flavours and they won't talk to each other on the same bus. Unfortunately there's no solution but to replace the modules; the Arduino can only run one SPI bus, so can only talk to one of these modules at a time.

However you can run UART and I2C or UART and SPI concurrently by using SoftwareSerial (don't use the native Tx/Rx pins, bad things happen).

So your best bet is to switch to modules that use I2C or UART. Personally I'd use UART, simply for the simplicity of having two separate connections and a higher data rate.


body:
This question is regarding a project using an Arduino Uno.

I have one of these [quadrature rotary encoders][1].

I'm using a slightly modified version of the code from the article, [Quadrature Encoder too Fast for Arduino (with Solution)][2], which uses a library called [digitalwritefast][3].

My version of the code on [pastebin][4] - I modified to use different pins for the Uno and a single encoder:

<!-- language: c -->

    #include <digitalWriteFast.h>  // library for high performance reads and writes by jrraines

    #define c_LeftEncoderInterrupt 0
    #define c_LeftEncoderPinA 2
    #define c_LeftEncoderPinB 3

    volatile bool _LeftEncoderBSet;
    volatile long _LeftEncoderTicks = 0;

    void setup()
    {
      Serial.begin(115200);
      pinMode(c_LeftEncoderPinA, INPUT);
      digitalWrite(c_LeftEncoderPinA, LOW);
      pinMode(c_LeftEncoderPinB, INPUT);
      digitalWrite(c_LeftEncoderPinB, LOW);
      attachInterrupt(c_LeftEncoderInterrupt, HandleLeftMotorInterruptA, RISING);
    }

    // Interrupt service routines for the left motor's quadrature encoder
    void HandleLeftMotorInterruptA()
    {
      _LeftEncoderBSet = digitalReadFast2(c_LeftEncoderPinB);   // read the input pin
      _LeftEncoderTicks -= _LeftEncoderBSet ? -1 : +1;
    }

    void loop()
    {
      Serial.print(_LeftEncoderTicks);
      Serial.print("\n");
      delay(20);
    }

I am attaching output A of the encoder to pin 2 and output B to pin 3.

This setup works fine and I can detect turns in both directions, but my problem is, if I set pin B to any other pin, I get positive direction only (regardless of the direction in which the encoder is turned) - as if pin B isn't plugged in at all (I am modifying `c_LeftEncoderPinB` accordingly).

I'm assuming that this is something to do with pin 3 being the only other interrupt pin on the Uno (I can't see anything else unique about that pin). Yet I don't know why because the interrupt is on pin A (we're reading the value of pin B in that interrupt, though).

  [1]: http://www.sparkfun.com/products/11102
  [2]: http://www.hessmer.org/blog/2011/01/30/quadrature-encoder-too-fast-for-arduino
  [3]: http://code.google.com/p/digitalwritefast/
  [4]: http://pastebin.com/ts1QzbgM

title: Rotary encoder on Uno and interrupts issue

Answers: 3

body:
When turning one way, A is asserted, then B is asserted, then A is deasserted then B is deasserted. You can detect this because A is asserted first, even if you can't tell when B has changed. But if you turn the opposite way then you fail to detect the initial assertion of B, and the code fails.

What you may be able to do is use PinChangeInt to capture the pin change interrupt rather than an external interrupt. This should allow you to use almost any I/O pins on the Uno for the encoder.

body:
My first thought is that something else is off because there is no reason that shouldn't work.  It will of course only count 1/4 of the ticks since that's how it was designed to work for very fast motors.  I can't comment yet but to Gerben above, I think it is meant to be bidirectional as indicated by the ternary operator.  My guess is the problem is with the digitalReadFast library and I would be interested to know if this works when using digitalRead() instead.

My second thought is that this is usually not the best way to do things.  Firstly, you would need a really fast motor for the read fast function to matter.  Secondly, you're sacrificing resolution by only using one interrupt instead of two.  The more generally accepted method is to attach both pins of the encoder to an interrupt.  Alternatively, you could use pin change interrupts which allow any pin to be used as an interrupt.  However, there are only 3 interrupt service routines on the Uno, one for each port of pins.  Whenever one pin on that port triggers, the ISR triggers and you need to keep track of the pin states in order to do anything with it.  Here's a good example of the [first][1] and info on the [second][2] method.

  [1]: http://bildr.org/2012/08/rotary-encoder-arduino/
  [2]: http://thewanderingengineer.com/2014/08/11/arduino-pin-change-interrupts/

body: OK embarrassingly it turns out my wiring was wrong! I was going astray as it was working in both directions as described, even when only one of the outputs was connected, as long output B was connected to an interrupt. Once the wiring was sorted everything worked perfectly, in both directions, using just one of the interrupt ports.


body:
I plan on creating a homebrew Arduino breakout board using the ATMEGA328P smd version. I'm geeting confused by the wealth of information out there as to whether I should be using ICSP or ISP to program it. It is a blank chip, aka no Arduino bootloader on it yet. I'd rather not have to buy a specialized programmer to burn the bootloader, I do have another Arduino I could use to burn the bootloader and upload sketches to it with.

So the question is; Do I use ISP or ICSP, or both?

title: Homebrew Arduino using ATMEGA328P, ISP or ICSP?

Answers: 2

body: ICSP is used for PICs, not AVRs. Use ISP, which can be performed either by an Arduino via ArduinoISP or by a dedicated programmer.

body:
To program it you could use an ISP programmer. In which case you would not need the bootloader. You can [use an Arduino as an ISP programmer][1], but that's not really a long term solution, as you can no longer use the arduino for anything else.

The other option is to program it using a usb-to-serial. In this case you do need the arduino bootloader. To program this bootloader (once) you can use the above method, using an arduino board.

Third option would be implement USB into the bootloader, just like the *completely Open Source* Pro Trinket ([bootloader](https://github.com/adafruit/Adafruit_ProTrinket_Bootloader) and [schematic](https://learn.adafruit.com/system/assets/assets/000/018/948/large1024/adafruit_products_protrink5vschm.png?1408558753)). You'd have to add some resistors, zener diodes and a usb plug (just strip an old usb cable). A bit more technical and challenging, but definitely the cheapest

  [1]: https://www.arduino.cc/en/Tutorial/ArduinoISP


body:
I am intending to show the initial, searching for signal..., screen until the location is updated and then show the location on the lcd. However, even after the led on the gps indicates a satellite fix, the screen never leaves the searching for signal screen. Any help would be greatly appreciated-- very new to microcontroller programming. Sorry for the poorly formatted code block as well, I am in a rush.
Thanks in advance.

    #include <SoftwareSerial.h>
    #include <LiquidCrystal.h>
    #include <TinyGPS++.h>

    #define RXPin 2
    #define TXPin 3
    #define GPSBaud 4800

    SoftwareSerial ss(RXPin, TXPin);
    TinyGPSPlus gps;
    LiquidCrystal lcd(12, 11, 10, 7, 6, 5, 4);

    double latt;
    double lon;
    int screen;

    void setup(void);
    void loop(void);
    void readGPS(void);
    void update(void);
    void render(void);

    void setup() {
      //variable initialization
      latt = 0.0;
      lon = 0.0;
      screen = 0;

      //lcd initial setup
      pinMode(9, OUTPUT);
      analogWrite(9, 100);
      pinMode(13, OUTPUT);
      digitalWrite(13, HIGH);

         //display intial screen
      lcd.begin(16,2);
        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print("Searching for");
       lcd.setCursor(6,2);
        lcd.print("Signal ...");
        ss.begin(GPSBaud);
    }

    void loop() {
     readGPS();
     update();
    }

    /** Receives data from the gps if available */
    void readGPS() {
     while (ss.available() > 0) {
      gps.encode(ss.read());
     }
    }

    /** Processes the data read by readGPS() */
    void update() {
     if (gps.location.isUpdated()) {
      latt = gps.location.lat();
      lon = gps.location.lng();
      render();
     }
    }

    /** Displays the current screen on the lcd */
    void render() {
     if (screen == 0) {
      lcd.clear();
      lcd.setCursor(0,0);
      lcd.print("Lat:");
      lcd.print(latt);
      lcd.print(" Lng:");
      lcd.print(lon);
      lcd.setCursor(0,1);
      lcd.print("Sats:");
      lcd.print(gps.satellites.value());
     }
    }

title: Adafruit gps breakout module help

Answers: 1

body:
Adafruit GPS breakout has their own library setup.

Below is the code I use for my telemetry. Notice I'm using HardwareSerial though.

You can just change that into SoftwareSerial.

    #include <SoftwareSerial.h>
    #include <Adafruit_GPS.h>
    #define GPSECHO false // Disables GPS breakout debug

    boolean usingInterrupt = false;

    HardwareSerial gpsSerial = Serial1;
    Adafruit_GPS GPS(&Serial1);

    SoftwareSerial XBee(2, 3); // For wireless

    unsigned int REFRESH = 20;

    double lat_deg, lon_deg, lat_min, lon_min;
    char lat, lon;

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

      GPS.begin(115200);
      GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);
      GPS.sendCommand(PMTK_SET_NMEA_UPDATE_5HZ); // Either 1HZ or 5HZ
      GPS.sendCommand(PMTK_API_SET_FIX_CTL_5HZ);
      GPS.sendCommand(PGCMD_ANTENNA);

      useInterrupt(true);
    }

    SIGNAL(TIMER0_COMPA_vect)
    {
      char c = GPS.read();
    #ifdef UDR0
      if (GPSECHO)
        if (c) UDR0 = c;
    #endif
    }

    void useInterrupt(boolean v)
    {
      if(v)
      {
        OCR0A = 0xAF;
        TIMSK0 |= _BV(OCIE0A);
        usingInterrupt = true;
      }
      else
      {
        TIMSK0 &= ~_BV(OCIE0A);
        usingInterrupt = false;
      }
    }

    void loop()
    {
      if(GPS.newNMEAreceived())
      {
        if(!GPS.parse(GPS.lastNMEA()))
        {
          writeData(1, true);
          Serial.print(GPS.hour, DEC); Serial.print(F(","));
          Serial.print(GPS.minute, DEC); Serial.print(F(","));
          Serial.print(GPS.seconds, DEC); Serial.print(F(","));
          Serial.print((int)GPS.fix); Serial.print(F(","));
          Serial.print((int)GPS.fixquality); Serial.print(F(","));
          Serial.print(F("-999")); Serial.print(F(","));
          Serial.print(F("-999")); Serial.print(F(","));
          Serial.print(F("-999")); Serial.print(F(","));
          Serial.print(F("-999")); Serial.print(F(","));
          Serial.print(F("-999")); Serial.print(F(","));
          Serial.print(F("-999"));
        }
        else if(GPS.fix)
        {
          writeData(1, true);
          parseGPS(GPS.latitude, GPS.longitude);
          Serial.print(GPS.hour, DEC); Serial.print(F(","));
          Serial.print(GPS.minute, DEC); Serial.print(F(","));
          Serial.print(GPS.seconds, DEC); Serial.print(F(","));
          Serial.print((int)GPS.fix); Serial.print(F(","));
          Serial.print((int)GPS.fixquality); Serial.print(F(","));
          Serial.print(lat_dd, 8); Serial.print(F(","));
          Serial.print(lon_dd, 8); Serial.print(F(","));
          Serial.print(GPS.speed); Serial.print(F(","));
          Serial.print(GPS.angle); Serial.print(F(","));
          Serial.print(GPS.altitude); Serial.print(F(","));
          Serial.print(GPS.satellites);
        }
      }
      delay(REFRESH);
    }

    void parseGPS(float _latitude, float _longitude)
    {
      lat_deg = (int) (_latitude / 100);
      lon_deg = (int) (_longitude / 100);

      lat_min = _latitude - (lat_deg * 100);
      lon_min = _longitude - (lon_deg * 100);

      lat_dd = (double) lat_deg + ((double) lat_min / 60);
      lon_dd = (double) lon_deg + ((double) lon_min / 60);

      lat = GPS.lat; lon = GPS.lon;

      if (lat == 'S') lat_dd = -lat_dd;
      if (lon == 'W') lon_dd = -lon_dd;
    }

    void writeData(float data, boolean next)
    {
      Serial.print(data);
      if (next) Serial.print(F(","));
    }


body:
Update: This piece of code does not do the same as the one in the right answer, it also reacts when one lets go of the button.

    int button_prev = 0;
    int button = 0;

    void loop(){

        button_prev = button;

        button = digitalRead(12);

        if (button_prev != button) {

          digitalWrite(act_pin[j], HIGH);

          j = (j+1) % 5;

        }
    }

I printed out j and it seems like, instead of counting up +1 everytime the button is pressed once, it turns +1 and then +1 again which makes two LEDs at a time turn on.
But I don't see where the behavior of j comes from...

[Update: There was a mistake in the code which caused the random behavior, but now, nothing happens when I push the button.]

[I wrote a sketch which is supposed to make the Arduino turn one of five LEDs on one after another every time I press the switch.

But instead of turning one LED on after another, directly after upload it just makes them turn on and of at random. I don't push the button.
`Serial.println` as well just spits out one character, similiar looking to a `d`.]

Can anyone point out my mistake to me?

This is the circuit

![enter image description here][1]

and this is the *old code* of the sketch

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

    int j = 0;

    void setup(){

      Serial.begin(9600);

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

         pinMode(act_pin[k], OUTPUT); //sets analog pins A0 - A4 as output

         digitalWrite(act_pin[k], LOW); //turns LEDs connected to A0 - A4 off

         pinMode(12, INPUT); //sets pin connected to button as input

    }

    }

    void loop(){

      char button = {digitalRead(12)}; //stores if the button was pressed

      Serial.println(button);

      if(button == HIGH){

        digitalWrite(act_pin[j], HIGH); //turns LEDs on A0 - A4 on one after one with every button press

        j = (j+1) % 5; //makes digitalWrite jump to the next LED next time the button is pressed and limits it to 4

        button = LOW; //turns the button's pin low again, so nothing will happen until the button is pressed again
    }

    }

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

title: Unintended reaction: Sketch makes LEDs turn on and of randomly/LEDs don't react

Answers: 3

body:
>     if(button = HIGH)

Oops.

    if (button == HIGH)

And see the Debounce example sketch to learn how to debounce inputs.

body:
Your code has a serious bug here:

    if(button == HIGH){

        digitalWrite(act_pin[j], HIGH);

        j = j+1;

        button = LOW;
    }

You increment `j` without any boundary so it will have the following cycling values:

    0, 1, 2, 3 ... 32767, -32768, -32767 ... -1, 0 ...

Hence, quickly `act_pin[j]` will return garbage...

The solution is easy, you must limit `j` to `[0,1,2,3,4]`, just replace the `j = j + 1` line as follows:

    j = (j + 1) % 5;

`%` is the modulo integral operation that will give you the reminder of dividing j by 5, which is always strictly less than 5, and it cycles as you want.

body:
I think you're looking for the action (in pseudo-code):

    ONCE (Button Pressed):
        Light LED j;
        j++

But you have an IF(button) in a Loop{}. Something like:

    WHILE (Button Pressed):
        Light LED j;
        j++

So when you press the button j will increment every iteration of Loop {}  (very fast) and you won't be able to see the LEDs changing. Your 'button = LOW' is not effective because 'button' gets set again the next time if the button is still pressed.

Try printing j instead of button at the line:

    Serial.println(j);

and that should highlight the problem.

I would implement a ONCE(Button Pressed) function by observing the previous button state and checking it has changed from LOW to HIGH.

        button_prev = button;
        button = digitalRead(12);
    // Check if button changed from LOW to HIGH
        if (!button_prev && button) {
        ...code
        }

EDIT: Dealing with Contact Bounce

Switches are mechanical so they don't switch cleanly. This is called contact bounce and means the switch switches on/off very rapidly for about 10ms or so after the contact has been pressed or released.

See [Measuring Switch Bounce][1]

![enter image description here][2]

You can deal with it quite simply in the code as follows (pseudo code) just by waiting for the bounce to dissapear and checking the button is still pressed:

    ONCE (Button Pressed):
       WAIT(20ms)              // wait for the bounce to stop
       IF(Button Pressed):     // Ensure the button is still pressed
        ...code...

Try the following Arduino Code:

        button_prev = button;
        button = digitalRead(12);
    // Check if button changed from LOW to HIGH
        if (!button_prev && button) {
           delay(20);                 // Wait for debounce
           if(digitalRead(12))  {     // Make sure the button is still pressed
            ...code
           }
        }

  [1]: http://www.picotech.com/experiments/switch_bounce/measuring-switch-bounce.html
  [2]: https://i.stack.imgur.com/I0Zol.gif


body:
I'm using 1mOhm resistor in parallel to a piezo that is connected to analog1 pin on the Due,

![enter image description here][1]

and the following code to observe the readings in the serial monitor:

    int piezo = A0;
    int threshold = 200;//anything over 200 means I've hit the piezo

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

    //this part checks if the threshold has been reached and then writes the strenght of the signal

    void loop(){
        int piezoVal = analogRead(piezo);

        if (piezoVal>threshold){
            Serial.println(piezoVal);

            delay(10); //delay is used to prevent from getting multiple values one after another, usually 3-4
        }
    }

The things that bother me are:

- if I do not use threshold, then I am constantly getting readings from the piezo, even if the threshold is slightly below 200.

- if I do not use delay, then I'm getting getting multiple values one after another

- and the strangest thing is while I hit the mouse pad that covers the piezo, the readings in the serial monitor are not matching the force being used to trigger the piezo. Sometimes they stay the same, sometimes they reach 6-700 after I directly touch the piezo, sometimes I hit really hard and I only get some slight increase (for ex. from 225 to 229).

This doesn't make sense to me. I think the stronger the vibration, the higher the values should be. Cause I've tried with two different piezos and different resistors (1mOhm, 1.2 mOhm and 1.5 mOhm) and I'm still getting the same result. I bought the Due few days ago in order to build a drum kit, and I have no problem with sending midi notes to a DAW, but this piezo sensitivity thing is driving me crazy. Any suggestions?

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

title: Problem with piezo readings and Arduino Due

Answers: 1

body:
The problem is timing.  When you tap or hit the sensor it produces an impulse response: a signal that increases to a peak, then decays back to zero.  You are expecting the code to capture the peak value.  Your code is spinning in loop() as quickly as possible, but captures just the first point above the threshold. The signal can still be increasing when you capture and print.

So imagine this stream of signal values

    time  signal   analogRead()
          at pin   occurs
    ----  ------   --------
     1     190      190
     2     190
     3     199
     4     210
     5     220      220 - trips threshold, prints and then waits
     6     230
     7     260
     8     280
     9     320      (this point occurs during delay())
     10    280
     11    260

The same exact signal, but at a slightly different time could be read different by the code:

    time  signal   analogRead()
          at pin   occurs
    ----  ------   --------
     1     190
     2     190
     3     199      199
     4     210
     5     220
     6     230
     7     260      260
     8     280
     9     320      (closer, but still did not read the peak)
     10    280
     11    260

So the strategy of catching the first point above the threshold makes it unlikely you can capture the peak value.  There are two ways forward: hardware or software.

You could use electronics that latches the maximum value.  If you search "peak hold circuit" you will find many circuits that would capture and hold the peak.  That frees the Arduino to somewhat lazily spin in the loop and still be able to accurately capture the peak.  Once it sees the value is no long increasing, it resets the peak hold and goes back to waiting.

You could use code to capture the peak. Something along the lines of this psuedo code:

    lastreading = analogread()
    if(lastreading > threshold) {
      peakreading = lastreading
      keeplooking = true
      while(keeplooking) {
        nextreading = analogRead()
        if(nextreading > lastreading) {
          // the signal is increasing, save this and see if next point is even higher
          peakreading = nextreading
          lastreading = nextreading
        }
        else {
          //signal is decreasing, the peak is over
          keeplooking = false
        }
      }

This software approach could still miss a sharp peak that occurs between analogRead()'s, but may be good enough for your use.


body:
<!-- 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

title: Modbus slave data into word

Answers: 1

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/


body:
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

title: Debouncing results in no reaction at all

Answers: 3

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.


body:
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.

title: Over-the-air upgrades?

Answers: 6

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.


body:
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.

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

Answers: 2

body: Bluetooth support on OpenWRT is broken, simply does not work.

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


body:
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.

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

Answers: 2

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  ;)


body:
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);
      }
    }

title: Led on when not supposed to be

Answers: 2

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()`.


body:
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?

title: Reading a tachogenerator

Answers: 1

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.


body:
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

title: Arduino's Serial Monitor Showing Constant Value

Answers: 3

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).


body:
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

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

Answers: 2

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).


body:
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

title: Installing MariaMole (Alternative IDE) on Mac

Answers: 2

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


body:
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

title: AttachInterrupt in a library

Answers: 2

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.


body:
I have a fio v3 + a 9DOF sensor hooked up to an XBEE. On another UNO board, I have a GSM shield and another XBEE board.

The fiov3 is supposed to sample data from the sensor, send it through the xbee. The receiving XBEE will then receive and pass the data to the UNO. The UNo then activates the GSM shield on condition.

However my resulting output on the UNO is as shown :

![enter image description here][1]

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

The data received is corrupted.

CODE ON UNO.

    /*****************************************************************
    XBee_Serial_Passthrough.ino

    Set up a software serial port to pass data between an XBee Shield
    and the serial monitor.

    Hardware Hookup:
      The XBee Shield makes all of the connections you'll need
      between Arduino and XBee. If you have the shield make
      sure the SWITCH IS IN THE "DLINE" POSITION. That will connect
      the XBee's DOUT and DIN pins to Arduino pins 2 and 3.
    *****************************************************************/
    // We'll use SoftwareSerial to communicate with the XBee:
    #include <SoftwareSerial.h>
    // XBee's DOUT (TX) is connected to pin 2 (Arduino's Software RX)
    // XBee's DIN (RX) is connected to pin 3 (Arduino's Software TX)
    SoftwareSerial XBee(2, 3); // RX, TX

    void setup()
    {
      // Set up both ports at 9600 baud. This value is most important
      // for the XBee. Make sure the baud rate matches the config
      // setting of your XBee.
      XBee.begin(9600);
      Serial.begin(9600);
    }

    void loop()
    {
      if (Serial.available())
      { // If data comes in from serial monitor, send it out to XBee
        XBee.write(Serial.read());
      }
      if (XBee.available())
      { // If data comes in from XBee, send it out to serial monitor
        Serial.write(XBee.read());
      }
    }

CODE ON FIOV3.

    #include <SPI.h> // Included for SFE_LSM9DS0 library
    #include <Wire.h>
    #include <SFE_LSM9DS0.h>

    #define LSM9DS0_XM  0x1D // Would be 0x1E if SDO_XM is LOW
    #define LSM9DS0_G   0x6B // Would be 0x6A if SDO_G is LOW
    // Create an instance of the LSM9DS0 library called `dof` the
    // parameters for this constructor are:
    // [SPI or I2C Mode declaration], [gyro I2C address], [xm I2C address]
    LSM9DS0 dof(MODE_I2C, LSM9DS0_G, LSM9DS0_XM);

    const byte INT1XM = 4; // INT1XM tells us when accel data is ready
    //const byte INT2XM = 8; // INT2XM tells us when mag data is ready
    //const byte DRDYG = 7;  // DRDYG tells us when gyro data is ready
    const int buttonPin = 15;     // the number of the pushbutton pin

    int buttonState = 0;

    void setup(){

      pinMode(INT1XM, INPUT);
      //pinMode(INT2XM, INPUT);
      // pinMode(DRDYG, INPUT);
      pinMode(buttonPin, INPUT);

      dof.setAccelODR(dof.A_ODR_1600);
      dof.setAccelScale(dof.A_SCALE_16G);

      Serial.begin(115200); // Start serial at 115200 bps
      Serial1.begin(9600);
      // Use the begin() function to initialize the LSM9DS0 library.
      // You can either call it with no parameters (the easy way):

      uint16_t status = dof.begin();
      // Or call it with declarations for sensor scales and data rates:
      //uint16_t status = dof.begin(dof.G_SCALE_2000DPS, dof.A_SCALE_6G, dof.M_SCALE_2GS);

      // begin() returns a 16-bit value which includes both the gyro and
      // accelerometers WHO_AM_I response. You can check this to make sure
      // communication was successful.
      // Serial.println(status, HEX);

    }

    void loop(){

      //Serial1.println("Hello!");

       buttonState = digitalRead(buttonPin);

      if (buttonState == 1) {

        //  Serial1.println("Hello!");

      printAccel();
      }

      //if (Serial1.available()){
         // Serial.write(Serial1.read());
    //  }

    }

    void printAccel()
    {
      // Only read from the accelerometer if the accel interrupts,
      // which means that new data is ready.
      if (digitalRead(INT1XM))
      {
        // Use the readAccel() function to get new data from the accel.
        // After calling this function, new values will be stored in
        // the ax, ay, and az variables.
        dof.readAccel();

        Serial.print("A: ");

        // Using the calcAccel helper function, we can get the
        // accelerometer readings in g's.
        Serial.print(dof.calcAccel(dof.ax));
        Serial.print(", ");
        Serial.print(dof.calcAccel(dof.ay));
        Serial.print(", ");
        Serial.println(dof.calcAccel(dof.az));

        Serial1.print("A: ");

        // Using the calcAccel helper function, we can get the
        // accelerometer readings in g's.
        Serial1.print(dof.calcAccel(dof.ax));
        Serial1.print(", ");
        Serial1.print(dof.calcAccel(dof.ay));
        Serial1.print(", ");
        Serial1.println(dof.calcAccel(dof.az));

      }
    }

Any idea how to mitigate this would be greatly appreciated.

title: Garbled data output from sensor through XBEE?

Answers: 0


body:
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?

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

Answers: 1

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.


body:
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.

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

Answers: 2

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


body:
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.

title: 16 bit PWM on a mega

Answers: 2

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].


body:
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?

title: Arduino Mega 2560 RFID Serial Communication

Answers: 2

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

body: i think the RFID is a other baud rate e.g 115200.. i dont know the device, i dont know if this is the problem, but test it :)


body: 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?

title: Stack arduino, motor shield and lcd shield

Answers: 1

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.


body:
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?

title: High frequency audio sampling and storage

Answers: 1

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.


body:
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
    }

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

Answers: 1

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]));


body:
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.

Answers: 1

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


body:
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.

title: Unable to upload sketch to Leonardo

Answers: 1

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.


body:
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

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

Answers: 1

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...


body: 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.

title: Servo limitations vs SoftwareServo

Answers: 1

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.


body:
I am looking to have an Arduino UNO stack with a GSM Shield and an XBEE shield for wireless communication.

However, since the GSM Shield requires digital pins 2 and 3, I would have to reroute the RX/TX of the XBee to another digital pin.

I have tried changing

    SoftwareSerial XBee(2, 3); // RX, TX

to other values, but this does not work.

How would I go about doing this?

title: Change XBee shield TX/RX Software serial?

Answers: 0