message:
Reading I2C sensors with a timer interrupt

I would like to read a sensor connected via I2C using Timer3 and Arduino Mega. Values are read from the sensor in the interrupt service routine and timer3 is set to trigger an interrupt at 200Hz.

**Step I: testing the timer**

I tested the timer using a counter and incrementing its value in the ISR. The output is displayed every second. It works!

    200
    201
    200
    201

**CODE**

    // Timer variable
    volatile int cont=0;

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

      setupL3G4200D(2000); // Configure L3G4200  - 250, 500 or 2000 deg/sec
      delay(1500); //wait for the sensor to be ready

      // Initialize Timer
      cli();
      TCCR3A = 0;
      TCCR3B = 0;

      // Set compare match register to the desired timer count
      OCR3A=77; //16*10^6/(200Hz*1024)-1 = 77 -> 200 Hz
      //OCR3A=193; //16*10^6/(80Hz*1024)-1 = 194 -> 80 Hz

      TCCR3B |= (1 << WGM32);
      // Set CS10 and CS12 bits for 1024 prescaler:
      TCCR3B |= (1 << CS30) | (1 << CS32);
      // enable timer compare interrupt:
      TIMSK3 |= (1 << OCIE3B);
      // enable global interrupts:
      sei();

      k = micros();
    }

    void loop()
    {
      delay(1000);
      Serial.println(cont);
      cont=0;
    }

    ISR(TIMER3_COMPB_vect)
    {
      cont++;
    }

**Step II: Reading values from the sensor in the ISR**

Now I add the I2C function in the Interrupt Service Routine, but the program is blocked after the calcBias() function which reads from the sensor, measures and saves the acquisition time in the samplingTime variable.

**CODE**

    // Timer variables
    volatile float phi=0;
    volatile float theta=0;
    volatile float psi=0;
    volatile int x = 0;
    volatile int y = 0;
    volatile int z = 0;
    volatile int cont=0;

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

      setupL3G4200D(2000); // Configure L3G4200  - 250, 500 or 2000 deg/sec
      delay(1500); //wait for the sensor to be ready

      calcBias():
      Serial.print("Readings take: (us)");
      Serial.println(samplingTime);

      // Initialize Timer
      cli();
      TCCR3A = 0;
      TCCR3B = 0;

      // Set compare match register to the desired timer count
      OCR3A=77; //16*10^6/(200Hz*1024)-1 = 77 -> 200 Hz
      //OCR3A=193; //16*10^6/(80Hz*1024)-1 = 194 -> 80 Hz

      TCCR3B |= (1 << WGM32);
      // Set CS10 and CS12 bits for 1024 prescaler:
      TCCR3B |= (1 << CS30) | (1 << CS32);
      // enable timer compare interrupt:
      TIMSK3 |= (1 << OCIE3B);

      Serial.println("Enabling interrupts..");
      // enable global interrupts:
      sei();

      k = micros();
    }

    void loop()
    {
      delay(1000);
      Serial.println(cont);
      Serial.println(z);
      cont=0;
    }

    ISR(TIMER3_COMPB_vect)
    {
      // Update x, y, and z with new values 2.5ms
      getGyroValues();
      cont++;
    }

    void getGyroValues()
    {

      //starting samplingTimer
      samplingTime = micros();

      // Gets the angular velocity from the sensor
      byte zMSB = readRegister(L3G4200D_Address, 0x2D);
      byte zLSB = readRegister(L3G4200D_Address, 0x2C);
      z = ((zMSB << 8) | zLSB);

      samplingTime = micros()- samplingTime;
    }

    void calcBias()
    {
      Serial.println("Bias");

      // Reads sensors and display three values
      getGyroValues();

      [...]

      Serial.println(bx);
      Serial.println(by);
      Serial.println(bz);
    }

    void writeRegister(int deviceAddress, byte address, byte val)
    {
        Wire.beginTransmission(deviceAddress); // start transmission to device
        Wire.write(address);       // send register address
        Wire.write(val);         // send value to write
        Wire.endTransmission();     // end transmission
    }

    int readRegister(int deviceAddress, byte address)
    {
        int v;
        Wire.beginTransmission(deviceAddress);
        Wire.write(address); // register to read
        Wire.endTransmission();

        Wire.requestFrom(deviceAddress, 1); // read a byte

        while(!Wire.available())
        {
            // waiting
           // Serial.println("No Data");
        }

        v = Wire.read();
        return v;
    }

I thought that the interrupt frequency was to high and I tried with 80 Hz and 20 Hz. Same results.

Here is the output:

    starting up L3G4200D
    Bias
    4.00
    0.00
    -3.00
    Read

body: Try putting `sei();` at the start of the ISR. I think I2C needs interrupts enabled to work.


sender: user

sender: assistant

body:
I2C requires interrupts to work, however enabling interrupts inside an ISR is **not recommended**. For one thing you may get into a race condition, where another interrupt occurs while processing the existing one.

Since you are doing virtually nothing in your main loop, a more sensible design would be to simply test if it is time to take a reading, and when that time is up, take the reading then.

As an example, your main loop could be rewritten as:

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

    unsigned long lastReading;
    unsigned long lastDisplay;
    void loop()
    {
      if (millis () - lastReading >= 5)   // 200 Hz
        {
        lastReading = millis ();
        // Update x, y, and z with new values 2.5ms
        getGyroValues();
        cont++;
        }

      if (millis () - lastDisplay >= 1000)  // one second
        {
        lastDisplay = millis ();
        Serial.println(cont);
        Serial.println(z);
        cont=0;
        }
    }

Now you don't need the timer, and you are interrupt-friendly. :)

More information about interrupts: <http://www.gammon.com.au/interrupts>


message:
Good button debouncing/stateChange library

I need debouncing/stateChange for a push button configuration. Is there a good library for debouncing/stateChange buttons in Arduino (without delay)?

body:
I can receommend the following library:

http://log.liminastudio.com/itp/physical-computing/arduino-a-new-improved-button-library-with-some-handy-features
https://github.com/virgildisgr4ce/Button

On the website you will find some examples on how to use it. I have implemented this library already in several sketches and it works very reliably.


body:
I think what you need is an interrupt-based detection of the button. This way, your Arduino can do what it needs to do without stalling for the delay function.

    // Example code usage

    int pin = 13; // LED on board
    int interrupt0pin = 2; // pin attached to int0 if you're using Uno
    int buttonState;

    void setup()
    {
      pinMode(pin, OUTPUT);
      pinMode(interrupt0pin, INPUT);
      attachInterrupt(0, buttonUpdate, CHANGE); // calls buttonUpdate() when button input changes (you can also use high-to-low or low-to-high)
    }

    void loop()
    {
        if (buttonState)
            digitalWrite(pin, HIGH);
        else
            digitalWrite(pin, LOW);
    }

    void buttonUpdate()
    {
      buttonState = digitalRead(interrupt0pin);
      delay(50); // 50ms works for most switches - adjustable
    }

Find out more here: http://arduino.cc/en/Reference/AttachInterrupt

Good luck!


body: You can put a capacitor in parallel with the switch - 100nf should do the trick. Some capacitors have a minus on the packaging, next to one of the pins - if so, make sure that side is to negative (ground).


body:
The [Button library][1] in the Arduino playground works perfectly.

  [1]: http://playground.arduino.cc/code/Button


body:
I put this together for a guy the other day. Its not a library but it achieves reading and debouncing all of your buttons and works very well maybe it could help you

    const byte numbuttons = 15;                                                     // DEFINE HOW MAY DIGITAL INPUTS TO MONITOR(NUMBER OF BELOW PINS TO USE)
    const byte digitalpin[] = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 16 };   // DECLARE ALL DIGITAL INPUT PINS WHICH CAN BE USED IN THE ORDER IN WHICH THEY WILL BE PHYSICALLY USED(DONT INCLUDE ANY PINS USED FOR OTHER THINGS
    const byte debouncetime = 50;                                                   // THIS VALUE IS THE TIME TO WAIT BEFORE RECHECKING (FOR DEBOUNCE
    byte readstate[numbuttons];                                                     // READ ARRAY
    byte laststate[numbuttons];                                                     // HOLDS THE BUTTON LAST STATE FOR STATE CHANGE DETECTION
    byte NumBut;                                                                     // THIS IS THE VARIABLE FOR DIGITAL FORLOOP COUNTER
    unsigned long checktime;                                            // RECORDS THE TIMES (IN MILLIS() TO RECHECK THE STATE FOR EACH BUTTON. FOR DEBOUCING

    byte CURRENT_SETTING;
    void setup() {

      // SET INITIAL STATES FOR DIGITALS
      for (NumBut = 0; NumBut < numbuttons; NumBut++) {
        pinMode(digitalpin[NumBut], INPUT_PULLUP);
        laststate[NumBut] = digitalRead (digitalpin[NumBut]);
        checktime = 0;
      }
    }

    void loop() {
      //call the read button method
      READBUTTONS();
      PROGRAM_OUTPUT();
    }

    void READBUTTONS() {
      for (NumBut = 0; NumBut < numbuttons; NumBut++) {

        readstate[NumBut] = (digitalRead (digitalpin[NumBut]));                                                                   // READ DIGITAL INPUTS INTO ARRAY

        if (readstate[NumBut] != laststate[NumBut] && millis() >= checktime )   {
          if (readstate[NumBut] == 0 && laststate[NumBut] == 1) {
            checktime = millis() + debouncetime;
            CURRENT_SETTING = NumBut;
          }
          laststate[NumBut] = readstate[NumBut];
        }
      }
    }

    void PROGRAM_OUTPUT(){
        switch ( CURRENT_SETTING ) {
        case 0:   //do something to turn off output break;
        case 1:   //do something with setting 1 break;
        case 2:   //do something with setting 2 break;
        case 3:   //do something with setting 3 break;
        default:    break;
    }
    }


body:
You can use my library

https://github.com/anlgncr/Buttons

This library lets you use buttons as many as you wish with only one instance of class.

You can also call a function when button is pushed or released.


body:
I'm on this subject right now and I'll use this to note my findings.

I found many libs on this, and this is my wishlist:
 - support many buttons
 - support toggles or switches
 - support debouncing and maybe de-glitching
 - non-blocking functions
 - support long-press, double-click

Candidates:

- Switch from avandalen: [tutorial](https://www.avdweb.nl/arduino/hardware-interfacing/simple-switch-debouncer) - [github](https://github.com/avandalen/avdweb_Switch) - [lib ref@arduino](https://www.arduino.cc/reference/en/libraries/switch/) - [@platformio](https://platformio.org/lib/show/2117/Switch)
- EasyButton from Evert Arias: [tutorial](https://easybtn.earias.me/docs/fundamentals/) - [github](https://github.com/evert-arias/EasyButton) - [lib ref@arduino](https://www.arduino.cc/reference/en/libraries/easybutton/) - [@platformio](https://platformio.org/lib/show/5741/EasyButton)
- JCButton from JChristensen: [github](https://github.com/JChristensen/JC_Button) - [lib ref@arduino](https://www.arduino.cc/reference/en/libraries/jc_button/) - [@platformio](https://platformio.org/lib/show/77/JC_Button)
- ezButton from ArduinoGetStarted: [tutorial](https://arduinogetstarted.com/tutorials/arduino-button-library) - [github](https://github.com/ArduinoGetStarted/button) - [lib ref@arduino](https://www.arduino.cc/reference/en/libraries/ezbutton/) - [@platformio](https://platformio.org/lib/show/8336/ezButton)

Here are my findings for each lib:

### **Switch**
  - it's really easy to use
  - you can use it as a switch or a button, same class handles both
  - supports callbacks
  - supports many buttons
  - supports debouncing and de-glitching
  - supports double click and long press
  - most configs have defaults, and you define them at the Button setup
  - as I use PlatformIO, some warnings from this lib are shown while compiling my project

### **EasyButton**
  - it's really easy to use
  - very good docs
  - supports callbacks
  - supports many buttons
  - does not support toggles/switches, although you can simulate it by checking the `wasPressed` and `wasReleased` properties
  - supports debouncing
  - supports double click, triple click, or a given number of clicks
  - you may have a different action for single, double or triple click for the same button
  - supports multiple times of long press, if needed
  - most configs have defaults, and you define them at the Button setup

### **JC Button**
  - easy to use, not as easy as Switch and EasyButton tough
  - you can use it as a `Button` or a switch (`ToggleButton`), different class for each
  - supports many buttons
  - does not support callbacks
  - supports debouncing
  - supports multiple times of long press, if needed
  - most configs have defaults, and you may define them at the Button setup, but long press time is something you define while querying it's status rather than defining it once at the button setup

### **ezButton**
  - easy to use, not as easy as Switch and EasyButton tough
  - supports many buttons
  - does not support toggles/switches, although you can simulate it by checking the `isPressed` and `isReleased` events
  - does not support long press
  - does not support callbacks
  - supports debouncing, does not debounce by default (you must call `setDebounceTime` on setup)
  - supports an easy way to count button clicks

### Veredict
I chose avdweb/Switch. Reasons:
 - in terms of debouncing AND de-glitching, it did better according to my tests
 - I need a solution for Buttons and Switches, and it provides them in the same class


message:
Arduino/C++ byte manipulation

Consider this scenario, I have a single byte of data; I have to use the 8 bits it is composed of to generate 4 extra bits from it.

Now, my problem is that I have to store this data somewhere while I operate on it and then return the final answer in byte form.

eg. 1 byte of 8 bits becomes 12 bits. Thus 2 bytes results in 24 bits which I want to transfer in packets of 3 bytes.

01001101 becomes this with added bits: _ _ 0 _ 1 0 0 _ 1 1 0 1

What would be the most efficient way to accomplish this?

body:
Assuming the incoming bytes are guaranteed to come in even numbers, and
your output is in little-endian order, you could do something like this:

    void process_and_send_bytes(uint8_t data_in)
    {
        uint16_t some_12_bit_function(uint8_t);  // processing function
        void send_byte(uint8_t);                 // sending function
        static uint8_t data_on_old = 0;
        static bool has_data_on_old = false;
        uint16_t processed_data = some_12_bit_function(data_in);
        if (has_data_on_old) {
            send_byte(processed_data << 4 | data_on_old);  // two pieces
            send_byte(processed_data >> 4);      // high 8 bits
            has_data_on_old = false;
        }
        else {
            send_byte(processed_data);           // send low 8 bits
            data_on_old = processed_data >> 8;   // save higher 4 bits
            has_data_on_old = true;
        }
    }

Basically, when you get the first byte, this function outputs one byte
and keeps 4 bits on hold. When you get the next byte, this outputs the
4 bits that where on hold, together with the new 12 bits, as two
8-bit packets.


body:
Sometimes the brute-force way is also the most efficient. Just copy the bits one at a time from the corresponding source variable to the destination variable:

    int merge_bits (int old_bits, int new_bits)
    {
       int retval = 0;
       if (old_bits & 0x01) retval |= 0x001;
       if (old_bits & 0x02) retval |= 0x002;
       if (old_bits & 0x04) retval |= 0x004;
       if (old_bits & 0x08) retval |= 0x008;
       if (new_bits & 0x01) retval |= 0x010;
       if (old_bits & 0x10) retval |= 0x020;
       if (old_bits & 0x20) retval |= 0x040;
       if (old_bits & 0x40) retval |= 0x080;
       if (new_bits & 0x02) retval |= 0x100;
       if (old_bits & 0x80) retval |= 0x200;
       if (new_bits & 0x04) retval |= 0x400;
       if (new_bits & 0x08) retval |= 0x800;
       return retval;
    }

On most microprocessors, this will compile into just a few instructions per statement.

This is also arguably more maintainable than a complex series of shift and mask operations.


body:
I haven't tested this in any way whatsoever, but you could use a 32-bit integer as a buffer to store the bytes as you process them.  Then, any multiples of 8 bytes that end up in the buffer can be passed on to wherever they are needed.

The first byte that comes in you process and push all 12 bits into the 32-bit integer - increment a counter by 12.  You now have 12 bits in the buffer variable.

Then while the number of bits in the buffer is at least 8 bits you grab the upper-most 8 bits and pass them on to wherever they are going.  Decrement the counter by 8 for each iteration.  You have now sent 1 byte and you have 4 bits left in the buffer.

The next byte that comes in you push the new 12 bits into the buffer.  The counter, increased by 12, is now 16.

16 is greater than or equal to 8, so send out the upper 8 bits of the 16 and decrement the counter by 8.

8 is greater than or equal to 8, so send out the upper 8 bits of the 8 and decrement the counter by 8.

Counter is now 0, so nothing else to send.  Back to the beginning again.

Something like:

    void processByte(uint8_t in) {
        static uint32_t buffer = 0;
        static uint8_t validBits = 0;
        buffer <<= 12; // Make room for 12 new bits.
        buffer |= (first processed bit << 11);
        buffer |= (second processed bit << 10);
        buffer |= ((in & 0x80) << 2);
        buffer |= (third processed bit << 7);
        buffer |= ((in & 0x70) << 1);
        buffer |= (fourth processed bit << 4);
        buffer |= (in & 0x0F);
        validBits += 12;

        while (validBits >= 8)
            validBits -= 8;
            executeByte((buffer >> validBits) & 0xFF);
        }
    }


message:
Connect 5V DC Fan to Ardumoto

I wish to connect 2 simple 5V DC Brushless Fan (80x80x15mm, https://www.sparkfun.com/products/9649) to Ardumoto (https://www.sparkfun.com/products/9815).

Therefore, how to I turn on/off the fan as I do not know how to address it? Do I need to connect a power supply to the Ardumoto, to the Arduino board or 2 separate power supplies to each one of them?

Thanks.

body:
If you look at the [schematic][1] on the product page it shows that the `Vin` from the arduino is connected to the same Vin on the shield and the Vin to the motor driver. So it is either or where you want to connect power.

With regards to controlling the fan, brushless fans are polarized because of the internal control circuitry, this means that **it cannot be made to reverse**, therefore you should always give the direction pin a high signal. The [Sparkfun hookup guide][2] has a example code which shows how to control the motor shield, and some explination.

  [1]: https://www.sparkfun.com/datasheets/DevTools/Arduino/Ardumoto_v13.pdf
  [2]: https://learn.sparkfun.com/tutohttps://learn.sparkfun.com/tutorials/ardumoto-shield-hookup-guiderials/ardumoto-shield-hookup-guide


message:
Generating a PWM frequency greater than 125 kHz using Arduino Uno

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

I need to obtain a PWM frequency of at least 125 kHz. I plan to drive a pair of MOSFETs using this PWM as the driver signal. The below code gives a 1 kHz frequency. Can I just change the delay values to obtain a lower time period, and thereby a higher frequency?

    void setup()
    {
      pinMode(13, OUTPUT);
    }

    void loop()
    {
      digitalWrite(13, HIGH);
      delayMicroseconds(100); // Approximately 10% duty cycle @ 1KHz
      digitalWrite(13, LOW);  // Can I change the delay to 1 and 9 for a totaL T=10 µsec and hence f = 100 kHz?
      delayMicroseconds(900);
    }

---

**Update**

On looking up the answers provided, I stumbled across a few tutorials. I used the code below and it resulted in 125 kHz and 1.6 MHz (measured with a CRO, not simulation). But the code was supposed to provide 250 kHz and 8 MHz.

My requirement of 125 kHz is satisfied, but I am just curious to know why the [sketch][1] not working as it should.

Second sketch:

    // A sketch that creates an 8 MHz, 50% duty cycle PWM and a 250 kHz,
    // 6-bit resolution PWM with varying duty cycle (changes every 5µs
    // or about every period.

    #include <avr/io.h>
    #include <util/delay.h>

    int main(void)
    {
      pinMode(3, OUTPUT); // Output pin for OCR2B
      pinMode(5, OUTPUT); // Output pin for OCR0B

      // Set up the 250 kHz output (but cro measures only 125 kHz)
       TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
       TCCR2B = _BV(WGM22) | _BV(CS20);
       OCR2A = 63;
       OCR2B = 0;

      // Set up the 8 MHz output
       TCCR0A = _BV(COM0A1) | _BV(COM0B1) | _BV(WGM01) | _BV(WGM00);
       TCCR0B = _BV(WGM02) | _BV(CS00);
       OCR0A = 1;
       OCR0B = 0;

      // Make the 250 kHz rolling
      while (1) {
        _delay_us(5);
        if (OCR2B < 63)
          OCR2B += 5;
        else
          OCR2B = 0;
      }
    }

  [1]: http://www.arduino.cc/en/Tutorial/Sketch

body: It's a bit beyond the normal Arduino capabilites so you need to delve into setting some of the registers for your ATMEGA chip directly. See the "Using the ATmega PWM registers directly" http://arduino.cc/en/Tutorial/SecretsOfArduinoPWM


body:
Yes, you can reduce the delay.

From the documentation:

> This function works very accurately in the range 3 microseconds and up. We cannot assure that `delayMicroseconds` will perform precisely for smaller delay-times.

Note that, there are a few cycles between the delays, so as you get shorter timeperiods, you will get less and less accuracy.

You could hand-code the delay. I would imagine you could get up to 1 MHz, but with little control over the duty cycle (at that frequency).You would need to disable interrupts, and you could do nothing else at all.

If you want still more, you could set a fuse on the ATmega, and get your native clock speed out on of pin 14 CKO (this shows up as digital pin 8 on the Arduino board) - I would expect a 50% duty cycle; you will have NO control over - you can't switch it on or off, or affect the duty cycle. It can be used to run multiple chips off the same clock.


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

> My requirement of 125 kHz is satisfied, but I am just curious to know why the sketch not working as it should.

According to my measurements, it is. Using this slightly modified version of your code:

    // A sketch that creates an 8 MHz, 50% duty cycle PWM and a 250 kHz,
    // 6-bit resolution PWM with varying duty cycle (changes every 5 µs
    // or about every period.

    #include <avr/io.h>
    #include <util/delay.h>

    int main(void)
    {
      pinMode(3, OUTPUT); // Output pin for OCR2B
      pinMode(5, OUTPUT); // Output pin for OCR0B

      // Set up the 250 kHz output
      TCCR2A = bit(COM2A1) | bit(COM2B1) | bit(WGM21) | bit(WGM20);
      TCCR2B = bit(WGM22) | bit(CS20);
      OCR2A = 63;
      OCR2B = 31;

      // Set up the 8 MHz output
      TCCR0A = bit(COM0A1) | bit(COM0B1) | bit(WGM01) | bit(WGM00);
      TCCR0B = bit(WGM02) | bit(CS00);
      OCR0A = 1;
      OCR0B = 0;
    }

I get the predicted 8 MHz output on pin 5:

[![8 MHz scope output][1]][1]

And the 250 kHz output on pin 3:

[![250 kHz scope output][2]][2]

  [1]: https://i.stack.imgur.com/xYt3y.png
  [2]: https://i.stack.imgur.com/vTqVw.png


body:
To your original question: You can reduce the delay, but there's a limit to how small the delay can be.

Two reasons: Firstly, the loop() function does have some overhead, and secondly the code that you write takes time to execute. This is why the hardware PWM timer is valuable - it generates the pulses without much software intervention.

> I used the code below and it resulted in 125 kHz and 1.6 MHz (measured with a CRO, not simulation).

This is really just to add to Nick's answer...
(To understand what's going on, you need to refer to the datasheet. Based on your questions, I'm assuming you haven't stared at it long enough.)

### In the first case: 125 kHz.

I am not sure if you're aware, but you're using a special mode of "Fast PWM" which is slightly different from the analogWrite() provided in Arduino.

In this mode, your PWM period is determined by the time it takes your timer counter to match the value in OCR2A register. This means that with a 16 MHz clock, and your output is toggled at a rate of 16 MHz/63 = 250 kHz (roughly).

So far so good, but what does the CRO see? The CRO considers a period to be made up of both high and low signal. It takes TWO 250 kHz cycles to toggle the signal up and down. Hence, the reading shows 125 kHz.

As to why the rolling would make your reading difficult: Think what kind of wave will appear when OCR0B = 0. ;-)

### Case 2: 8 MHz

The same applies in the seccond case, and you should expect a 16 MHz cycle that toggles the signal up and down (which gives a 8 MHz reading on the CRO). As to why you are getting 1.6 MHz - that's an odd case. Can you post your CRO reading?


message:
How to: soil moisture measurement with WaterMark?

I am new with Arduino, and i cant find documentation about how to connect Arduino with Watermark successfully.

I would like to connect my Arduino UNO with a watermark like this:

http://guideimg.alibaba.com/images/shop/72/08/19/4/watermark-soil-moisture-sensor-w-15-cable_3234944.jpg

Does anyone know any schema or documentation about how to do it? Have anyone tried it before?

I have found this: https://oceancontrols.com.au/datasheet/davis/ECS-014_07395-158_IM_06440_6470.pdf

but still not clear how to do it in Arduino.

Thanks you for your time.

body:
You can google
"Arduino-based system for soil moisture measurement"
and the author about this paper is "Vuk Radman" .
[![enter image description here][1]][1]
Now, I am also try to find the method using Arduino to connect WaterMark 200ss Sensor. The paper I share to you is what I have found from GoogleScholar, but I haven't used this method yet. Nevertheless, I think the method mentioned in the paper is feasible. Hopefully, this information can help you.

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


message:
Question about infrared receiver with metal shell to detect heart pulse rate?

I'm newbie to the world of arduino and environmental sensing. I have been searching for a while about how can I measure the heart pulse rate, I came through the following tutorial:

[Click Here][1]

I have the following [Arduino IR Receiver with metal shell module][2] that I want to use as the previous tutorial suggesting, but, the IR receiver used in the tutorial has no metal shell, so, my question is if they are both functioning the same way?
Can I position my IR Receiver exactly as the one in the tutorial or do I need some workaround to reach my goal based on the fact that it has a metal shell?
Thanks in advance.

  [1]: http://medicarduino.net/?page_id=204.
  [2]: http://www.amazon.com/KY-022-Infrared-Sensor-Receiver-Arduino/dp/B00KMMF7AO/ref=sr_1_cc_7?s=aps&ie=UTF8&qid=1426591190&sr=1-7-catcorr&keywords=arduino infrared receiver

body:
"Proper" oxygen meters use a bimodal LED - red + IR - so there will be limitations to this. They also have a piece of copper foil wrapped around the sensor & heavily earthed, so your shielded sensor has, already, an advantage!

You should be able to use your receiver exactly the same way. If you can ground the shield, do so.


message:
Why is the atmega chip reset three times during programming?

I'm trying to understand the auto reset process and why a capacitor hooked up between DTR and Reset works so I ran it through my logic analyzer and I'm seeing the chip reset three times during the programming process. Does anyone know why it's done three times and not just once?

You can see in the picture the top pin is the DTR and the bottom two are attached to reset (digital/analog). When DTR drops low the reset pin does too for between 200-500us but it does it three times in around 1 second.

![Auto Reset][1]

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

body:
It does it to "force" a reset.

Historically, when you open the serial port on an FTDI interface, the DTR will automatically go LOW.  However, recently FTDI decided it'd be a good idea to change their driver so that when you open the port the DTR line doesn't go low - you have to manually tell it to go low.  But this is only on the FTDI official drivers.

If you have a driver that is newer than a certain date (no idea what date) then just running `avrdude` by itself on an FTDI interface may not work properly since DTR isn't being lowered.

To get around that Arduino have included a forced toggling of the DTR line as part of the programming sequence to make the target board reset.

But of course, if the driver is old enough, or not the "official" FTDI driver (i.e., you're in Linux for instance) then the lowering of the DTR by `avrdude` works fine.

So what you are seeing there is first a brief toggle of DTR by the IDE to force a reset, then `avrdude` opening the port and DTR going low, then finally the IDE toggling DTR again one last time to force a final reset.

And to me that says you're either not in Windows, or you have an FTDI driver while does toggle the DTR line automatically.

I also have a feeling that `avrdude` may also have started including manual control of the DTR line within it - so if `avrdude` is new enough, even with a new FTDI driver that doesn't automatically, you will still see the repeated action of DTR.

It's what we call *belt and braces*.  Use every method possible to get the board to reset, so no matter what you hardware and software arrangement the board has a very good chance of being reset into the bootloader.


message:
Port manipulation using C code

I'm trying to manipulate the ports of Arduino using C code. I have attached an LED to pin 8 and a tact switch to pin 13 (with a pull down resistor). The code works fine, and the results are printed on the screen. So, when the button is pressed, the byte `PINB & (1 << PB5)` equals 32, or `0b00100000`.

However, if I try to use

    if( PINB &(1<<PB5) == 32){

or

    if( PINB &(1<<PB5) == 0b00100000){

the LED doesn't respond.

Here's the full code:

    void setup() {
      DDRB |= 0b00011111;
      Serial.begin(9600);
      }

    void loop() {
      Serial.print("PINB &(1<<PB5)");
      Serial.println(PINB &(1<<PB5));

      if( PINB &(1<<PB5) ){
        PORTB |= (1<<PB0);
        }
      else{
        PORTB &= ~(1<<PB0);
        }
      }

What am I missing?

body: `==` has higher precedence than `&`, which means that your comparison will be performed incorrectly. But that doesn't matter, since you don't need to check if the port has a *specific* value, just if the appropriate bit is set.


message:
Seeedstudio Wifi shield v1.1 Not working with Arduino Mega 2560

I have been trying use the [Seeedstudio wifi shield v1.1][1] with Arduino Mega 2560 as part of my project but I could not make the WiFly library provided on the [wiki][2] work with the Mega. I tried to run the example sketch wifly_test but it did not work I tried some troubleshooting and found that the write commands to the shield were not successful. After a few hours of searching on the internet, I found out the problem and was able to solve it. I am posting my solution below. Anyone is welcome to add to my solution.

  [1]: http://www.seeedstudio.com/depot/Wifi-Shield-p-1220.html
  [2]: http://www.seeedstudio.com/wiki/Wifi_Shield_V1.1

body:
The WiFly library provided at the Seeedstudio wiki uses the software serial to communicate with the WiFi shield. All the example files provided by the WiFly library use pins 2 and 3 as the Rx and Tx of the software serial. Moreover, the Wifi shield only allows pins 0-7 to be chosen as Rx and Tx by using different jumper combinations.
The [SoftwareSerial][1] library, on the other hand, has the following limitation for the Arduino Mega

> Not all pins on the Mega and Mega 2560 support change interrupts, so only the following can be used for RX: 10, 11, 12, 13, 14, 15, 50, 51, 52, 53, A8 (62), A9 (63), A10 (64), A11 (65), A12 (66), A13 (67), A14 (68), A15 (69).

Thus, as a workaround, I jumped pin 2 of the shiled with pin 10 (Rx of Software Serial) and pin 3 with pin 11 (Tx of Software Serial) using connecting wires and used the jumper setting given on the wiki. Finally I made the following changes in the example code

    // Pins' connection
    // Arduino       WiFly
    //  10    <---->    TX (via connecting pin 2 to 10 on wifi shield)
    //  11    <---->    RX (via connecting pin 3 to 11 on wifi shield)
<!-- language: c++ -->

    SoftwareSerial uart(10, 11); //change software serial pins for Mega

This allowed the Mega to communicate with the Wifi shield successfully using the WiFly library.

  [1]: http://arduino.cc/en/Reference/softwareSerial


message:
Why are MOSFETs only giving 8.1V for LEDs, not 12V?

I'm using three PWM outputs from an Arduino Mini Pro to drive the R/G/B parts of some strips of LEDs. The circuit is basically this:
![circuit diagram][1]

I've got a single 12V power supply, rated at 200W, to light the LEDs and to power the Arduino via the RAW pin, and there are 5 metres of 60LEDs/m RGB LEDs, i.e. a total of 300 LEDs, which should be drawing ~72W according to the spec sheet (14.4W/m).

The problem is that even when the sketch says **`digitalWrite(9, 255); digitalWrite(10, 255); digitalWrite(11,255)`**, the LEDs are considerably dimmer than when connected directly to the 12V supply. My cheap, digital volt meter measures ~8.1V <del>between GND and the PWM pins</del> across the LEDs, not the 12V that the transformer is supplying.

Am I doing something wrong? Does the MOSFET really cause such a large drop in voltage? Is there anything I can do to mitigate it? (It's important to get as much brightness as possible from the LEDs for this project).

  [1]: https://i.stack.imgur.com/GWrfB.gif

body:
By my calculations you are sinking 6 amps:

    72 W / 12 V = 6 A

I have some doubt that the Arduino board is designed to handle that amount of current through its ground plane. Try running a separate ground wire to the MOSFET sources.

I would also be concerned about the gauge of wire you are using, and whether the prototyping board can handle that amount of current.


body:
Your MOSFETs may not be appropriate for driving from a 5V device. I had a similar problem and someone suggested I need to use a MOSFET with a low turn-on voltage, specifically IRLB8743 (http://www.irf.com/product-info/datasheets/data/irlb8743pbf.pdf) which is fully enabled at 4.5V. You might also find that your MOSFETS are getting warm because they are acting as resistors if not fully engaged.
In the above datasheet it says "Very low RDS(on) at 4.5V" meaning low resistance when VGS (arduino output voltage) is at 4.5V or more.

Your datasheet is here http://pdf.datasheetcatalog.com/datasheet2/8/0iyt26iogeofcyaowtrx4z7iwiky.pdf and I'd love to be able to tell you how to compare but I'm not sure which values to look at :/

The breadboard itself may also be introducing resistance. If you wiggle the mosfets around and the lights change brightness this is likely.

LEDs have a set forward (turn on) voltage. You can expect to see that voltage drop over LEDs and not more, which does not indicate the problem (current).


message:
How do I change the Console colour of Arduino IDE?

Leading on from the question [Can I change font Color and/or Type for IDE 1.5.6r2?][1], in 1.6.0, or 1.6.11 it does not seem to be possible to change `console.color` or `console.error.color`. To be precise, you can change the settings in the `preferences.txt`2 file, but they appear to be ignored when the IDE is restarted. Have these become hard coded?  I see from the [preference.txt example file][2] that

    # Some colors have been hardcoded into the source in app/ in order to ensure
    # consistency with the images distributed and stored with the application.
    # They have been commented out below so that users who install an old
    # version of the software will not get incorrect colors left-over from this
    # config file.

However, the settings to which I refer are not commented out, and so would led me to believe that they can be changed. Orange text on black is just horrific to read.

For example:

    console.error.color=#FFF000
    console.color=#FFCCCC

but I still get white/orange(red?) text for the output and error messages respectively.

I am making the edits while the Arduino IDE is not running.

-----
1 In 1.6.3 the ignored `console.color` etc. lines appear to have been removed from the `preferences.txt` file.

2 `C:\Users\username\AppData\Roaming\Arduino15\preferences.txt`

  [1]: https://arduino.stackexchange.com/questions/4364/can-i-change-font-color-and-or-type-for-ide-1-5-6r2
  [2]: https://code.google.com/p/arduino/source/browse/trunk/build/shared/lib/preferences.txt?r=71

body:
It turns out that the `theme.txt` configuration file is _not_ located alongside the `preferences.txt` file, but alongside/under the Arduino application's `.jar` files. Thus, for the current version (1.6.3):

 - on OS X, `.../Arduino-1.6.3.app/Contents/Java/lib/theme/theme.txt`
 - on Win7, `C:\Program Files\Arduino\lib\theme\theme.txt`
 - on Linux, `.../arduino-1.6.3/lib/theme/theme.txt`
 - on Windows 10, when installed as an App, C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\lib\theme\theme.txt, however it does not seem possible to edit it - it can be opened in notepad++ but a save fails.

See an associated Github issue, [IDE Background and print color options needed](https://github.com/arduino/Arduino/issues/1878), for a little more discussion.


body:
Download the Dark Theme of Jeff Thompson from [Github: jeffThompson/DarkArduinoTheme][1]

[![Jeff Thompson's - Dark Arduino Theme][2]][2]

Screenshot:

[![Screenshot of Jeff Thompson's - Dark Arduino Theme][3]][3]

  [1]: https://github.com/jeffThompson/DarkArduinoTheme
  [2]: https://i.stack.imgur.com/WIcm4.jpg "Jeff Thompson's - Dark Arduino Theme"
  [3]: https://i.stack.imgur.com/O3mQW.png "Screenshot of Jeff Thompson's - Dark Arduino Theme"


message:
How to monitor 12 V LiPo charging from Arduino

What's the safest way to determine a lithium-ion polymer battery's discharge and charging state using an Arduino?

I see a ton of 12 V LiPo batteries like [**this**][1] being sold on eBay and elsewhere.

![enter image description here][2]

They have a built-in charger, and I'd like to use one to power an Arduino, but the Arduino needs to know "when" the battery needs to be charged, and "when" the battery is fully charged. Unfortunately, the battery doesn't expose any pins or LEDs or other outputs that I could tap into.

I've found a few LiPo charging circuits specifically designed for the Arduino, but they all can only handle 3.7 V cells.

I'd like to avoid having to disassemble the battery or modify it to allow me to monitor its state. Is there an easier way, like connecting a battery lead to an analog pin and measuring voltage, or using a coulomb counter?

  [1]: http://www.ebay.com/itm/12V-4000mAh-Lithium-ion-Super-Rechargeable-Battery-Pack-AC-Charger-SPC-2369-US-/370921997007
  [2]: https://i.stack.imgur.com/UfGIR.jpg

body:
If you want to buy something off the shelf that will provide power for an Arduino, try a power bank - they have USB out, and are also charged via USB. I found that I had to put a 100 Ohm resistor to stop mine going to sleep, but it's +5V native.

A 100 ohm resistor (0.25 watt at least!) draws 50mA, so a 5200mAH powerbank like http://www.dx.com/p/universal-5200mah-external-li-ion-battery-charger-power-bank-w-led-indicator-usb-cable-pink-362725#.VQneCnWjlIc would leak it empty in 104 hours. If you use at least 50mA at all times, then this isn't needed - I think an Arduino draws 35mA already, so you should get away with a 300 Ohm resistor, drawing 16mA. Some experimentation might be needed.


body:
Use a 10V zener diode. Check it’s voltage drop, and use that in your analogRead logic.

Get the full voltage with a DMM, and also the low cut-off voltage.


message:
Integrating Shift Registers into 7 Segment LED Circuit

I'm trying to implement a shift register(s) into my circuitry and program to control two seven segment LEDs that would count up from 00 - 99. So far I have a fairly straightforward code (at least, I think. It's my first time experimenting with creating my own void functions) that controls the 7 segs in this manner, but I end up using every single digital pin on my Uno. Here it is:

    const int led1a = 13;
    const int led1b = 12;
    const int led1c = 11;
    const int led1d = 10;
    const int led1e = 9;
    const int led1f = 8;
    const int led1g = 7;
    const int led2a = 6;
    const int led2b = 5;
    const int led2c = 4;
    const int led2d = 3;
    const int led2e = 2;
    const int led2f = 1;
    const int led2g = 0;

    void setup() {
        pinMode(led1a, OUTPUT);
        pinMode(led1b, OUTPUT);
        pinMode(led1c, OUTPUT);
        pinMode(led1d, OUTPUT);
        pinMode(led1e, OUTPUT);
        pinMode(led1f, OUTPUT);
        pinMode(led1g, OUTPUT);
        pinMode(led2a, OUTPUT);
        pinMode(led2b, OUTPUT);
        pinMode(led2c, OUTPUT);
        pinMode(led2d, OUTPUT);
        pinMode(led2e, OUTPUT);
        pinMode(led2f, OUTPUT);
        pinMode(led2g, OUTPUT);
    }

    void loop () {
        led1_0();
        led2_run();
        led1_1();
        led2_run();
        led1_2();
        led2_run();
        led1_3();
        led2_run();
        led1_4();
        led2_run();
        led1_5();
        led2_run();
        led1_6();
        led2_run();
        led1_7();
        led2_run();
        led1_8();
        led2_run();
        led1_9();
        led2_run();
    }

    void led1_0() {
        digitalWrite(led1a, HIGH);
        digitalWrite(led1b, HIGH);
        digitalWrite(led1c, HIGH);
        digitalWrite(led1d, HIGH);
        digitalWrite(led1e, HIGH);
        digitalWrite(led1g, HIGH);
        digitalWrite(led1f, LOW);
    }
    void led1_1() {
        digitalWrite(led1a, LOW);
        digitalWrite(led1b, HIGH);
        digitalWrite(led1c, HIGH);
        digitalWrite(led1d, LOW);
        digitalWrite(led1e, LOW);
        digitalWrite(led1f, LOW);
        digitalWrite(led1g, LOW);
    }
    void led1_2() {
        digitalWrite(led1a, HIGH);
        digitalWrite(led1b, HIGH);
        digitalWrite(led1f, HIGH);
        digitalWrite(led1e, HIGH);
        digitalWrite(led1d, HIGH);
        digitalWrite(led1c, LOW);
        digitalWrite(led1g, LOW);
    }
    void led1_3() {
        digitalWrite(led1a, HIGH);
        digitalWrite(led1b, HIGH);
        digitalWrite(led1c, HIGH);
        digitalWrite(led1d, HIGH);
        digitalWrite(led1f, HIGH);
        digitalWrite(led1e, LOW);
        digitalWrite(led1g, LOW);
    }
    void led1_4() {
        digitalWrite(led1a, LOW);
        digitalWrite(led1b, HIGH);
        digitalWrite(led1c, HIGH);
        digitalWrite(led1f, HIGH);
        digitalWrite(led1g, HIGH);
        digitalWrite(led1e, LOW);
        digitalWrite(led1d, LOW);
    }
    void led1_5() {
        digitalWrite(led1a, HIGH);
        digitalWrite(led1f, HIGH);
        digitalWrite(led1g, HIGH);
        digitalWrite(led1c, HIGH);
        digitalWrite(led1d, HIGH);
        digitalWrite(led1b, LOW);
        digitalWrite(led1e, LOW);
    }
    void led1_6() {
        digitalWrite(led1a, HIGH);
        digitalWrite(led1g, HIGH);
        digitalWrite(led1f, HIGH);
        digitalWrite(led1c, HIGH);
        digitalWrite(led1d, HIGH);
        digitalWrite(led1e, HIGH);
        digitalWrite(led1b, LOW);
    }
    void led1_7() {
        digitalWrite(led1a, HIGH);
        digitalWrite(led1b, HIGH);
        digitalWrite(led1c, HIGH);
        digitalWrite(led1d, LOW);
        digitalWrite(led1e, LOW);
        digitalWrite(led1f, LOW);
        digitalWrite(led1g, LOW);
    }
    void led1_8() {
        digitalWrite(led1a, HIGH);
        digitalWrite(led1b, HIGH);
        digitalWrite(led1c, HIGH);
        digitalWrite(led1d, HIGH);
        digitalWrite(led1e, HIGH);
        digitalWrite(led1f, HIGH);
        digitalWrite(led1g, HIGH);
    }
    void led1_9() {
        digitalWrite(led1a, HIGH);
        digitalWrite(led1b, HIGH);
        digitalWrite(led1c, HIGH);
        digitalWrite(led1d, HIGH);
        digitalWrite(led1g, HIGH);
        digitalWrite(led1f, HIGH);
        digitalWrite(led1e, LOW);
    }
    void led2_0() {
        digitalWrite(led2a, HIGH);
        digitalWrite(led2b, HIGH);
        digitalWrite(led2c, HIGH);
        digitalWrite(led2d, HIGH);
        digitalWrite(led2e, HIGH);
        digitalWrite(led2g, HIGH);
        digitalWrite(led2f, LOW);
    }
    void led2_1() {
        digitalWrite(led2a, LOW);
        digitalWrite(led2b, HIGH);
        digitalWrite(led2c, HIGH);
        digitalWrite(led2d, LOW);
        digitalWrite(led2e, LOW);
        digitalWrite(led2f, LOW);
        digitalWrite(led2g, LOW);
    }
    void led2_2() {
        digitalWrite(led2a, HIGH);
        digitalWrite(led2b, HIGH);
        digitalWrite(led2f, HIGH);
        digitalWrite(led2e, HIGH);
        digitalWrite(led2d, HIGH);
        digitalWrite(led2c, LOW);
        digitalWrite(led2g, LOW);
    }
    void led2_3() {
        digitalWrite(led2a, HIGH);
        digitalWrite(led2b, HIGH);
        digitalWrite(led2c, HIGH);
        digitalWrite(led2d, HIGH);
        digitalWrite(led2f, HIGH);
        digitalWrite(led2e, LOW);
        digitalWrite(led2g, LOW);
    }
    void led2_4() {
        digitalWrite(led2a, LOW);
        digitalWrite(led2b, HIGH);
        digitalWrite(led2c, HIGH);
        digitalWrite(led2f, HIGH);
        digitalWrite(led2g, HIGH);
        digitalWrite(led2e, LOW);
        digitalWrite(led2d, LOW);
    }
    void led2_5() {
        digitalWrite(led2a, HIGH);
        digitalWrite(led2f, HIGH);
        digitalWrite(led2g, HIGH);
        digitalWrite(led2c, HIGH);
        digitalWrite(led2d, HIGH);
        digitalWrite(led2b, LOW);
        digitalWrite(led2e, LOW);
    }
    void led2_6() {
        digitalWrite(led2a, HIGH);
        digitalWrite(led2g, HIGH);
        digitalWrite(led2f, HIGH);
        digitalWrite(led2c, HIGH);
        digitalWrite(led2d, HIGH);
        digitalWrite(led2e, HIGH);
        digitalWrite(led2b, LOW);
    }
    void led2_7() {
        digitalWrite(led2a, HIGH);
        digitalWrite(led2b, HIGH);
        digitalWrite(led2c, HIGH);
        digitalWrite(led2d, LOW);
        digitalWrite(led2e, LOW);
        digitalWrite(led2f, LOW);
        digitalWrite(led2g, LOW);
    }
    void led2_8() {
        digitalWrite(led2a, HIGH);
        digitalWrite(led2b, HIGH);
        digitalWrite(led2c, HIGH);
        digitalWrite(led2d, HIGH);
        digitalWrite(led2e, HIGH);
        digitalWrite(led2f, HIGH);
        digitalWrite(led2g, HIGH);
    }
    void led2_9() {
        digitalWrite(led2a, HIGH);
        digitalWrite(led2b, HIGH);
        digitalWrite(led2c, HIGH);
        digitalWrite(led2d, HIGH);
        digitalWrite(led2g, HIGH);
        digitalWrite(led2f, HIGH);
        digitalWrite(led2e, LOW);
    }
    void led2_run() {
        led2_0();
        delay(1000);
        led2_1();
        delay(1000);
        led2_2();
        delay(1000);
        led2_3();
        delay(1000);
        led2_4();
        delay(1000);
        led2_5();
        delay(1000);
        led2_6();
        delay(1000);
        led2_7();
        delay(1000);
        led2_8();
        delay(1000);
        led2_9();
        delay(1000);
    }

So how would I reduce the amount of pins used while still keeping functionality? I have two 74HC595N shift registers at my disposal.

Thanks!

body:
I have done exactly this, to great effect.

    int clockPin = 4;
    int dataPin  = 2;
    int oePin    = 3;

    // Here are the digits from 0 to 9, as bitmaps.
    // You will need to work out which segments are which,
    // according to your wiring, and make your own.
    unsigned char digitmaps[]={0x7b,0x11,0xe3,0xb3,0x99,0xba,0xfa,0x13,0xfb,0xbb};

    void setup() {
      pinMode(clockPin,OUTPUT);
      pinMode(dataPin,OUTPUT);
      pinMode(oePin,OUTPUT);
    }

    void sendnumber(unsigned int number, int oePin,int dataPin,int clockPin) {
       digitalWrite(oePin,LOW);
       shiftOut(dataPin,clockPin,MSBFIRST, digitmaps[(number/10)]);
       shiftOut(dataPin,clockPin,MSBFIRST, digitmaps[number]);
       digitalWrite(oePin,HIGH);
     }

    void loop() {
      for (int i=0; i<100; i++) {
        sendnumber(i,oePin,dataPin,clockPin);
        delay(1000);
      }
     }

The crux of the matter is shiftOut, which shifts 8 bits out the dataPin, toggling the clockPin as it goes, high bit first (MSBFIRST), looking up the pattern in the table. dataPin goes to serial in on the FIRST shift register, clockpin to BOTH clocks, oePin to BOTH OE and another one, I think store register? Q7' or QH' (depending on your docs - it's the overflow pin) of the first goes to the serial in of the second, and +5v & GND, as per normal, and the 8 parallel out Q0-Q7 go to the pins on the 7-segment.

If there's anything unclear, or anything I've missed, let me know. My example shows 2 digits, but any number will work, up to the available power.

Things might be clearer if I convert the digitmaps to binary. The below compiles to the same thing as the one above.

    unsigned char digitmaps[]={
       B01111011, // 0
       B00010001, // 1
       B11100011, // 2
       B10110011, // 3
       B10011001, // 4
       B10111010, // 5
       B11111010, // 6
       B00010011, // 7
       B11111011, // 8
       B10111011}; // 9

This is because, in my wiring, from left to right the bits represent in the 8 on my display: center,bottom left,bottom,right bottom,top left,decimal point/not used,top,right top. You can see that the digit "1" has 2 1's in it: the 4th (right bottom) and the last (right top). An 8 has all of the bits set to 1, except position 6 - because that's the decimal point. Send individual bits (e.g. B00010000) to see which segments shows up, make a map, and then combine them.


message:
Flickering LCD when using > 5v power supply on a Pro Mini

I have a Pro Mini wired up to an LCD via an I2C board. At http://www.arduino.cc/en/Main/ArduinoBoardProMini it says the pro mini can accept up to 12v on the RAW pin as it has a voltage regulator on board. When I plug a 12v power supply into the raw pin, the LCD works fine initially, then slowly degrades into flickering more and more. It also does this with a 9v power supply. At 5v it works perfectly. Any ideas what's going on?

body:
If the LCD has a backlight you are absolutely over heating the regulator on that board by running it at 9 or 12V: At 12V with 100mA for the backlight and using 175C/W thermal resistance for the regulator:
Tj = 25C + ((12V - 5V) x 100mA x 175C/W) = 147C
That regulator goes into thermal limit at 125C.


message:
Integrating an analog signal using Arduino Uno SMD

I need to integrate an analog signal using my Arduino Uno. I am sampling the input signal at 1 KHz using a delay command in my `void loop()` and adding up the values at the analog read at that specific time. Then I multiply my added output with 0.001 s to get my integration.

Since, I am new to Arduino Uno, I want some review on the code to check whether I am correct or not. Kindly help, I'll be indebted.

    const int a=13; //my output pin
    const int c=A0; //my input pin
    int d=0; //my summation variable
    int e=0; //my integration variable(integration as a summation)
    void setup()
    {
      pinMode(a, OUTPUT);
    }
    void loop()
    {
      int b=analogRead(c);
      d=d+b; //my summation
      e=d*10^-3; //my integration as a summation, by sampling my signal at 1ms
      analogWrite(a,e); //writing my integration into my output pin

      //print the results to the serial monitor
      Serial.print("input=");
      Serial.print(b);
      Serial.print("\t output=");
      Serial.println(e);

      delay(1); //wait for 1ms as I want it sampled at that rate
    }

body:
I'm not entirely clear on what you're trying to achieve mathematically. However, I can see a number of issues in your code which I'll try to address briefly.

**Arithmetic**
I suspect this line isn't doing what you intended:

    e=d*10^-3

The `^` operator in C/C++ is actually a bitwise XOR (exclusive-or). There is no arithmetic raise-to-the-power operator.

There is a function called `pow()` for calculating exponents. However, there's no point using it for a fixed value. It would be better to explicitly write the number, i.e. 0.001.

**Precision**
The power issue notwithstanding, it's important to note that you're working with integers here, and the result of `analogRead()` is only in the range 0 to 1023. Dividing that by 1000 and storing the result as an integer will destroy your data -- most readings will effectively be 0. (That's not to mention the fact that an `int` has a limited range and will overflow quite quickly if you don't reset it.)

The simple solution would be to store the data using the `float` data type (floating point). You would need to declare variables `b`, `d` and `e` as `float` instead of `int`. That should let you divide down by 1000 without losing significant precision.

**Output range**
The `analogWrite()` function has a very specific output range. It will only accept values 0 to 255 (inclusive). I'm not entirely sure what you're hoping to do with it, but I suspect you'll need some way to map your integration calculation onto that output range, or possibly reset your summation periodically.

If you don't do that, you'll probably find that `e` ends up over 255 very quickly (within a couple of seconds). The result is that you won't see any change on the output PWM.


body:
There are a couple of issues with your code.

First of all, `10^-3` is not a valid constant in C/C++ code. The correct syntax would be `1e-3`, which means 1 × 10<sup>-3</sup>. But you have the further problem that you're working with integer variables, and 0.001 rounded to the nearest integer is just zero. You'll probably want to use `float` variables for this math.

Also, the values you get from `AnalogRead()` are all non-negative integers, so your summation will quickly overflow unless you subtract a constant from each reading in order to get both positive and negative values.

The second issue is about the `delay()` function, and trying to use it to determine the sample rate of your system. The `delay()` function is not all that precise. It really is just guaranteed to produce a delay of *at least* the number of milliseconds specified, but it can be more — sometimes much more.

Furthermore, the other operations in your loop take much longer than 1 ms anyway. For example, you're printing on the order of 25 to 30 characters to a serial port on every iteration, which is an overall rate of 25,000 to 30,000 characters per second. Unless you're running your serial port at an insane baud rate (430.8 kbaud or more), it simply won't be able to keep up, and it will end up increasing the period of your loop to whatever time it needs.

All of this means that the sample period of your loop is NOT 1 ms as you want, and in fact, it can vary quite a lot based on other things that are going on in the system, such as interrupts. For doing this kind of DSP, you will want to learn how to use a timer interrupt to control the sampling of the analog input, and you'll need to trim the amount of data transmitted for each sample to an amount your serial link can handle.


body:
Here is an edited version of your code:

    /*
     * Integrate a signal read on analog input 0.
     * Print the result every 2 seconds on the serial port.
     */

    const int input_pin = A0;
    unsigned long last_time_sampled = 0;
    unsigned long last_time_printed = 0;

    // The integral is in units of DN*us, 1 DN being the ADC step.
    float integral = 0;

    // Convert from DN*us to V*s, assuming a 5 V reference.
    const float conversion = 5.0 / 1024 * 1e-6;

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

    void loop()
    {
        int sample = analogRead(input_pin);
        unsigned long now = micros();

        // Approximate the signal as a constant equal to the current sample
        // from the time of the previous sample until now.
        integral += sample * (now - last_time_sampled);
        last_time_sampled = now;

        // Print the results every 2 seconds.
        if (now - last_time_printed >= 2000000) {
            Serial.print("input = ");
            Serial.print(sample);
            Serial.print(", output = ");
            Serial.println(integral * conversion);
            last_time_printed = now;
        }

        // Limit the sampling rate to no more than 1000/s.
        delay(1);
    }

The main changes I did are:

1. I renamed the variables to give them more meaningful names. This
   single change makes the code a lot more readable.
2. I removed those comments made redundant by the better variable names.
3. I removed `analogWrite()`, since I couldn't make any sense out of it.
4. I compute the time between samples as time differences. Unless you
   take your samples on some kind of timer interrupt, the delay between
   samples will never be 1 ms.
5. I stored the integral as a float to avoid overflows.
6. I removed the summation variable, as it was redundant with the
   integration variable. Instead, there is a conversion factor for
   converting the integral from its “natural” unit (DN⋅µs) into a more
   human-friendly unit (V⋅s).
7. I print the results only every 2 seconds, as nobody will read
   something printed every millisecond.
8. I added some comments, most importantly for making explicit the
   approximation used in computing the integral.

There is still one caveat with this code: once the integral is roughly
107 times larger than the samples, which should happen after
only a few hours, the integral is not incremented any more, due to loss
of precision.


message:
GSM Modem with MAX232 to Arduino Serial?

I have GSM modem that has MAX232 interface for RX/TX/GND on three pins.
Is it possible to interface Arduino in some way?

Tnx for help.

body: Yes, with another MAX232, or bypass the MAX232 somehow.


message:
How to convert the 0-5V to a 4-20mA current loop?

I'm pretty clueless about electronics so everything has to be explained in simple terms to me.

I have an Arduino with a program which provides a value via the Analog output, so that is anything from 0-5V.

On the other side I have a PLC (programmable logic controller) with an IO card which allows to connect to a (4-20mA) current loop.

How do I convert from lets say 1-5V to the 4-20mA in a somewhat cheap and safe way (I don't want to destroy the PLC [and possibly the Arduino])?

Of course the Arduino and the PLC have separate power sources.

body:
If all you need is analog 4-20mA loop transmitter, then you need an op-amp, the transistors that its output drives, a sense resistor, and a few other resistors. Note that these are at least 1% resistors. **This needs to be built on a printed circuit board, not a solderless breadboard.**  Two of my coworkers at Maxim Integrated wrote an applications note about a 4-20mA current-loop transmitter: http://www.maximintegrated.com/en/app-notes/index.mvp/id/5610  see this figure:

![4-20mA circuit from Maxim Integrated app note 5610][1]

Since you are already using a PWM (hopefully with an RC low-pass filter), you just need everything after the DAC output. (*Performance will not be as good with an Arduino PWM as it would be with a 16-bit voltage-output DAC, but the general idea would still work.*) For your purpose, you can also ignore all of the stuff about the HART modem -- that's an extra feature for sending digital information along the same loop. Only relevant if your PLC receiver was expecting it.

There are also numerous prebuilt 4-20mA transmitter boards available, this has been around many decades in the industrial control market. Since Maxim Integrated makes precision DAC chips, we don't make reference designs that take 0-5V (especially from a PWM!) and convert to 4-20mA -- but we do sell reference design boards that include the DAC. Such as our Monterey system board (MAXREFDES15#). http://www.maximintegrated.com/en/app-notes/index.mvp/id/5683

There's also a `4-20mA Current-Loop Transmitter` from ti.com, XTR117: http://www.ti.com/lit/ds/symlink/xtr117.pdf

There's also a board from mikroElektronika, MIKROE-1296 (available through mouser.com) that uses an Analog Devices DAC (through SPI interface) to drive the 4-20mA transmit circuit. Again, this is an idea that's been around many decades, so a search for `4-20mA transmitter` should yield lots of useful information.

So your best bet is probably to purchase one of these prebuilt 4-20mA transmitter boards, which most likely will include its own precision DAC. You'll have to modify your Arduino code to drive the SPI interface, specific to whichever DAC you end up using. Or, if you really want to use the PWM to drive 4-20mA (at reduced performance), be sure to at least use an RC low-pass filter to get it as close as possible to a stable DC level.

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


body:
Here is an article which explain how you can use arduino and a 4-20mA current loop transmitter to generate 4-20mA signal. Its using a DAC and 4-20mA current generator.
[https://ncd.io/interfacing-isolated-4-20ma-current-loop-transmitter-arduino/][1]
So this is how it works
in this article they are using a 4-20mA current transmitter board with arduino, You can build it by yourself as well as you can get it from it from [https://store.ncd.io/shop/?fwp_product_type=4-20ma-transmitter][2]. it has a DAC and a XTR ( its a TI part which is used to generate 4-20mA signal) and signal and power isolator. In these application it is very important that you use isolation between device and your arduino or any other master device. Once you have all the hardware setup, you can send i2c commands and it will generate 4-20mA current loop signal. Lets say you have a device which provides 0-5V and you want to control a different device which needs 4-20mA signal in that case you can use arduino analog input to read the 0-5V and you can use this 4-20mA transmitter to convert that 0-5V into 4-20mA.
For more info checkout the above mentioned article.

  [1]: https://ncd.io/interfacing-isolated-4-20ma-current-loop-transmitter-arduino/
  [2]: https://store.ncd.io/shop/?fwp_product_type=4-20ma-transmitter


message:
AVCC and AREF when using a reference voltage lower than 5V?

I'm designing a circuit that will use a 2.5v reference for the AREF. Should AVCC be powered from 5V or 2.5V?

body:
> AVCC is the supply voltage pin for the A/D Converter, PC3:0, and ADC7:6. It should be externally connected to VCC, even if the ADC is not used. If the ADC is used, it should be connected to VCC through a low-pass filter. Note that PC6...4 use digital supply voltage, VCC.

So it should be connected to 5V.


message:
Saving Arduino output to a text file in append mode

I used the code below to save output from an Arduino Uno to a text file.

The problem is whenever I run the code the old data in the text file is deleted.

I don't want the old data to be deleted, what should I change?

    import processing.serial.*;
    Serial mySerial;
    PrintWriter output;
    void setup() {
       mySerial = new Serial( this, Serial.list()[0], 9600 );
       output = createWriter( "data.txt" );
    }
    void draw() {
        if (mySerial.available() > 0 ) {
             String value = mySerial.readString();
             if ( value != null ) {
                  output.println( value );
             }
        }
    }

    void keyPressed() {
        output.flush();  // Writes the remaining data to the file
        output.close();  // Finishes the file
        exit();  // Stops the program
    }

body:
There are a couple of ways to append to a text file.

1. You can either read the entire file in a temporary variable, then append the new data to it and then write to file.

2. you can implement using printWriter instead like mentioned here:
https://processing.org/discourse/beta/num_1267767630.html

Let me know if it works.


message:
Cheap weatherproof ultrasonic range sensor?

What's an inexpensive ultrasonic range sensor that's reasonable waterproof or weatherproof that also interfaces easily with an Arduino?

I've used [these][1] kinds of ultrasonic range sensors, which are cheap and trivial to wire to an Arduino, but they're not very robust and are easily damaged since you can't cover them without that covering obstructing the soundwave.

Maxbotix sells a "Weather-Resistant" ultrasonic range sensor, but it's around $100, which is a little out of my price range.

I've researched those "parking sensors" used on cars, but I haven't seen anyone successfully interface them with an Arduino. It's also hard to tell how they're controlled. Some sites sell batches of the sensor for $3/each, but I don't think this includes the control electronics. Ebay listings that include what appears to be a bulky controller board seem to go for around $50-$100, which makes them a little pricey.

  [1]: http://www.seeedstudio.com/wiki/Ultra_Sonic_range_measurement_module

body: Those modules are just the ultrasonic transducers. You can see the two pin connector. You can probably get those cheap boards, de-solder the two transducers, and connect the wires from two of the water-proof ones.


message:
Razor 9DOF SMD Capacitor replacing

I just bought This IMU a while ago, and when I reached the point where I wanna connect it, I noticed that one of the capacitors have been removed by accedint, and since it took too long to check the product, I won't get to replace it or get any refund, so my question, how can I replace that SMD capacitor?
P.S. I have some Ultrasonic sensors might have the same SMD capacitors that I can take off and replace with if anyone can help.

![The circled capacitor is the one][1]

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

body:
You are on a tough road. I hope someone can give you specifics.  Normally you would able to identify the capacitor from its parts designation, but that board does not have any. So you will have to match the schematic (assuming spark fun provides one) to the board layout to figure out what it is.  The cost of the part is probably over a penny, maybe even 2 cents. In other words, not an issue.

It will require hot air to desolder one from another board and to solder this one on. Someone might be able to do it with a fine tip solder  pencil, but not likely.

Bottom line; find someone who has experience repairing boards, or order another one. Amazon has breakout boards for the 6050 for $6. But I see this one has Serial, and a magnetometer, so it is not quite the same. But depending on what you plan to do with it, it could work.


body:
You are looking for C22,  0.1uF capacitor, connected to smooth the 3.3v from the regulator. If you are not using the battery connector, you can probably just leave it out.

You could just get a capacitor with leads and connect it somewhere between 3.3v and ground. You can use the ISP header (2x3 holes on the right) for this. I think it's the top-right and bottom-right pin.


body: Try using two soldering pencils, one in each hand. makes it easy to remove the capacitor from the donor board.


message:
Using A 4 Ohm Speaker With Arduino

I've salvaged a 4 Ohm, 1.5 Watt speaker from an old computer, and I was wondering how I'd go about getting it to work with my Arduino. I've heard of various amplifier circuits such as opamps, but I do not know which would be the best for my situation. I've also heard that using the speaker in certain ways (such as directly connected to a pin from the Arduino) could damage both the speaker and the output pin, so that is definitely something I'd like to avoid. I'm not looking for anything complicated; I'm just trying to get a feel for the general circuitry, programming, and speaker volume. Any suggestions?

body:
5v, 4ohm, >1amp from a pin rated for 0.04amps; this isn't safe!
You would need a driver, but it would suffice to add a small transistor & a couple of resistors to drive it; [here](http://hackaweek.com/hacks/?p=327) is a slightly more complex layout, there are many examples on the web.


message:
Different dht21 readings on different arduinos

First of all, let me begin by saying that I'm still pretty much a rookie.

I have a project with a dht21, an LDR and an ultrasonic distance sensor. I have 3 different arduino uno boards, namely:

- A (supposedly) original arduino uno r3.
- A chinese nhduino, arduino uno r3 clone.
- And [this][1] one, sitting on top of [this][2].

I've been playing around with the three boards for the last couple of months, testing a variety of sensors and having the same results with the three boards, as expected. But then, with the aforementioned setup, I'm getting very different readings on the DHT21 sensor. If I use the "regular" (first two) arduinos plugged in my laptop, the readings are consistent. But if I use the banana pi(duino), I get the temperature reading correct, but getting weird humidity readings... pretty most of the time a 5% humidity value.

Everything tested on the same room, same sensors and same protoboard. No external power supply.

I'm totally clueless here, any ideas of what could be the problem?

Thanks.

  [1]: http://www.banana-pi.net/index.php/en/product/banana-pi/modules/banana-pi-bpiduino-uno-module-detail
  [2]: http://www.bananapi.org/p/product.html

body: Problem solved. Using a ywrobot breadboard PSU and now it works. I haven't tested current in the circuit but looks like it was just too low. I wish I'd had datasheet for the board to look at. In a language different from chinese would have been ok, I guess.


message:
What is the rise time of an output pin of atmega328 changing its state?

I've already searched a lot and didn't found the answer. Also, I don't have an o'scope. Anyone can help me?

body:
Last time I measured on a circuit (it was an i2c network master and with a 2560), it was about 0.3us, so that gives you a high value for that. Also, I believe it cannot be faster than one/half of a CPU cycle which takes: 1/(16E6)=62.5ns/2 = 31.25ns, so here's the lower boundary.

And there you got a possible range.

Then the rise time will definitely depend on the configuration of the circuit. It might be less or more depending on pull ups, capacitance attached at the pin out exit. It might also depend on the configuration of the pin (PWM? Internal Pull-up?…)

Finally, I believe there should some nominal values given in the datasheet.

Edit: Useful knowledge from the [datasheet], but there's no definitive answer for *any* pin:

[datasheet]:http://www.atmel.com/Images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet.pdf

P311: **29.4.3 External Clock Drive**

    | Symbol | Parameter | Min | Max   | Min | Max   | Min | Max   |
    | ------ | --------- | --- | ----- | --- | ---   | --- | ----- |
    | tCLCH  | Rise Time |     | 2.0µs |     | 1.6µs |     | 0.5µs |

P313: **29.6 SPI Timing Characteristics**

    | Description    | Mode      | Min | Typ   | Max    |
    | -------------- | --------- | --- | ----- | ------ |
    | Rise/Fall time | Master    |     | 3.6ns |        |
    | Rise/Fall time | Slave     |     |       | 1600ns |

P315: **29.7 Two-wire Serial Interface Characteristics**

    | Symbol | Parameter                      | Condition | Min        | Max   |
    | ------ | ------------------------------ | --------- | ---------- | ----- |
    | tr     | Rise Time for both SDA and SCL |           | 20 + 0.1Cb | 300ns |

HTH


body:
I just measured on my Uno with a pocket scope and a cheap 1× probe. I got something around 40 ns, but it was at the bandwidth limit of this basic scope, and I believe this probe has quite high capacitive load. A faster scope and a better probe would probably give a shorter rise time.

**Update**: I tried again with a better scope (an Hameg HM-305) and a decent 10× probe, the observed rise time was somewhere in the 10 ns range, which is about the rise time of the internal amplifier of the scope. Then the higher boundary would be about 10 ns.


body: I got 8 ns on both the rising and falling edges. If using the PORT instruction to set and clear bits instead of the much slower digitalWrite() instruction, the highest frequency I got by toggling a pin high and low was 2.666 Mhz. This is slowed down by the excessive time the arduino takes to pass execution back to the top of the Loop() marker. The duty cycle of the pulse output at 2.666 Mhz was somewhere in the region of 15%.


message:
Is PulseIn fast enough for Quadcopter?

I've been trying to use interrupts to control a quadrotor with a tx/rx to no success. I'm using an arduino mega as my control board. I have successfully read a singe channel using attach interrupt and PulseIn. I have also successfully read multiple channels with pulse but failed to do so with attach interrupt and pinchange int. Should I just go ahead and use PulseIn

body:
You should avoid pulseIn for a quadcopter, the main reason being that pulseIn takes too long to execute.

pulseIn waits for a pulse to start, then waits until that pulse finishes, and then returns how long it took to finish. Standard RC signals pulse at 50-60Hz, with the "high" part of the signals being between 1 and 2 milliseconds. 60Hz is one pulse per 16 milliseconds or so.

What that amounts to is pulseIn taking at most 18 milliseconds, but never less that 1 millisecond to execute per channel. lets say you want to measure 4 channels (throttle, pitch, yaw, roll); the average time would be around 40 milliseconds.

In general 40 milliseconds isn't so long, but your quad will need to read the accelerometer and gyroscope and stabilize itself more often then that in the air. A loop that takes 40 ms is running at 25Hz, but the stabilize loop in all the quadcopter implementations I'm familiar with is run at 100Hz or higher (thats areoquad, multiWii, and ardupilot).

You should use interrupts to read the values, because interrupts are non blocking, and give higher quality readings. Some specialized quadcopter boards have other processors read the actual RC signals and send the result back to the main processor to cut down on the number of interrupts they have to use.

----------

FYI, The standard servo output library sends new signals at 50Hz. Those open source quadcopters use their own implementations that run at higher output frequencies, since brushless ESCs support that. There is a pull request with code to add support for different refresh intervals to the arduino servo library [here][1] that I have tested; You could try appling it as a patch to your installation if the output rate gives you trouble down the road.

  [1]: https://github.com/arduino/Arduino/pull/2446


message:
Serial communication and Arduino program in C

When I flash this simple code (using [Arduino-Makefile][1]):

    #include <avr/io.h>
    #include <util/delay.h>
    #include <Arduino.h>

    void init_io(void) {

        // open serial port
        Serial.begin(9600);
        while (!Serial);
        Serial.println("Comm-link online");

    }//END: init_io

    int main(void) {

        init_io();

        while (1) {

            // send data only when you receive data:
            if (Serial.available() > 0) {

                // read the incoming byte:
                int incomingByte = Serial.read();

                // say what you got:
                Serial.print("I received: ");
                Serial.println(incomingByte, DEC);

            } else {

                //  Serial.println("No serial ");

            }

        }//END: loop

        return 0;
    }//END: main

I only see first two chars printed in the serial output:

> ~$> Co

  [1]: https://github.com/sudar/Arduino-Makefile

The input also does not work as intended - tested on two independent microcontrolers, Mega and Uno. I'm not sure what's the cause of this behaviour. Here's the Makefile:

    BOARD_TAG    = uno # megaADK uno
    MONITOR_PORT  = /dev/ttyACM0
    ARDUINO_LIBS =

    include $(ARDMK_DIR)/Arduino.mk

It's definitely not a hardware problem, I've used serial i/o before in other projects.

body:
When using the Arduino core library, you normally do not write a
`main()` function. Instead, you write `setup()` and `loop()` and rely on
libcore's provided `main()` for calling them.

If you nevertheless want to provide your own `main()`, then you should
call `init();` (with no arguments) before you try to use the library.
Adding this single call makes your program work on my Uno.

However, since it does not seem to be officially documented, this trick
may not be safe against upgrades in the core library. Writing `setup()`
and `loop()` should be more future-proof.


message:
How can I drive this LCD TFT with an Arduino?

As I understand it, the Arduino comes with a TFT library which uses SPI to drive LCD TFTs. I recently bought a TFT labelled "HY-32.TFT" on the front and "HY-TFT320_262k heyaodz111211" on the back.

It uses an XPT2046 touch screen controller, but I'm more interested in just getting something on the screen currently.

To use the Arduino library, I need to connect pins:

- SCLK
- MOSI
- CS
- DC
- RESET

But I can't see these apart from some similarly named ones associated with TP (touchpad?) and SD (sd card), as the photo shows:

![back][1]
![front][2]

Is it possible to drive this with my Arduino? If so, how?

UPDATE: It looks like the datasheet for the controller and the board can be downloaded from [3.0" 3" TFT LCD Module Display + Touch Panel + PCB adapter][3].

  [1]: https://i.stack.imgur.com/XsNFr.jpg
  [2]: https://i.stack.imgur.com/U4geV.jpg
  [3]: http://www.icstation.com/module-display-touch-panel-adapter-p-2292.html

body: From what I'm seeing, the touch screen and card reader use SPI but the LCD uses a bunch of Digital I/O lines. The link in Gerben's comment includes a library for the LCD that might be what you're looking for. I hope you're using a ATMega board as it doesn't look like an Uno or similar board will have enough I/O for the LCD.


body:
If you search for "arduino lcd tft shield" on ebay you should if a few shields for your kind of lcd. But all of them require an Arduino MEGA (or DUE).
You could also use some kind of a shift register to drive this lcd with an Arduino UNO (or other small boards).


message:
How big of a difference is there between an Arduino Uno and the rest?

Lately I've been fooling around with a project for my Microsoft Sidewinder Force Feedback Pro Joystick. I've found out that there is a project currently for it [built for the Teensy 2.0][1]. On the page for the Teensy 2.0 there is a link for an [Arduino Library][2] for the very same project that was (I guess) converted. There isn't much documentation for it, and I don't think there is much progress being made on it anymore. However when I grab the files and try to upload it to my Arduino Uno it spits out an Unsupported device. Doing some digging around I found where it shows what devices are supported in the includes.h.. Which happen to be

    #if defined(__AVR_AT90USB162__) || defined(__AVR_AT90USB82__)
     #define __AVR_AT90USBX2__
    #elif defined(__AVR_ATmega16U4__) || defined(__AVR_ATmega32U4__)
     #define __AVR_ATmegaXU4__
    #elif defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__)
     #define __AVR_AT90USBX6__
    #else
     #error "Unsupported device"
    #endif

Which ends up being the red arduino, arduino micro, arduino leonardo, and I think a few teensys.

What I want to know is if you can upload this code onto a UNO. I'm not really wanting to purchase a teensy just to check if this will work or not.

  [1]: https://code.google.com/p/adapt-ffb-joy/
  [2]: https://code.google.com/p/sidewinder-arduino/

body:
Generally, the differences between the different chips are mostly: amount of memory (sram, eeprom), number of pins (analog, digital, pwm), numbering of pins, and hardware support for protocols (serial, SPI, 2 wire etc)

In this case, you would have to go through the code wherever you find `#IFDEF __AVR_AT90USBX2__` or `#IFNDEF __AVR_AT90USBX2__` and the others - you would need to work out what it is doing differently for each, and work out how you would do the same thing on the Arduino Uno (which runs on an Atmega328).


body: That program will make the arduino board act like a keyboard to the PC it's plugged in. This can't be done on the Uno, since it doesn't have USB support.


body:
The code won't work as a traditional project when uploaded on an Uno, because the Uno does not talk directly to the Host, it only speaks UART.

But good news is that the Uno uses another atmega chip, an Atmega8u2 on the older models or Atmega16u2 on the others. That IC handles directly the USB connection with the host on behalf of the Atmega328. And that code below is actually (close enough) support for that IC:

    #elif defined(__AVR_ATmega16U4__) || defined(__AVR_ATmega32U4__)
     #define __AVR_ATmegaXU4__

That means you should be able to upload the code (or a similar one) on that 'frontend' IC, so it acts as a HID device, and connects to the main 328 for any I/O you might need.

To do the upload on that other chip, you can use an ISP programmer on the 6pins header close to USB, or you can use the DFU programmation mode over USB.

I'm sorry for not giving external references or code, but I'm answering from my phone!

Edit: after a short browse over the code, it's definitely *possible* to implement that using an uno, but you'll need to split the code between the two chips: the USB interface to behave like ah HID device and the main I/O chip to talk midi, and implement comms between both.

Edit #2:

Here's a few resources that might help to work out USB and Midi using Arduino, but it looks like none is a cooked in USB on atmegaXu2 to Midi on atmega328:

 * http://unojoy.tumblr.com/
 * http://forum.arduino.cc/index.php/topic,111.0.html
 * http://hunt.net.nz/users/darran/weblog/15f92/Arduino_UNO_Big_Joystick_HID_firmware.html
 * https://stackoverflow.com/questions/16710701/joystick-usb-definition-for-use-with-arduino
 * http://hackaday.com/2011/03/28/hiduino-the-only-limit-is-yourself/
 * http://arduino.cc/en/Hacking/DFUProgramming8U2
 * http://arduino.cc/en/tutorial/midi
 * https://sites.google.com/site/bharatbhushankonka/home/diy-midi-over-usb-using-arduino-uno
 * http://www.instructables.com/id/Turn-your-Arduino-Uno-into-an-USB-HID-Mididevice/

And if you're not at ease with AVR development, it's gonna be **HARD**. You'd better get a teensy2 or a leonardo where that code should compile and work with little effort.

HTH


message:
Can I use IR Transmitter/Receiver for heart beat detecting?

Specifically, I want to know if the KY-022 module and KY-005 module can be used for heart beat detecting according to this [tutorial][1]?

KY-005:

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

KY-022:

[![enter image description here][3]][3]

If so, can you please explain to me how can I achieve such thing with respect to the following:
1- Is there any kind of synchronization between transmitter/receiver?
2- How to get a stable analog value from the receiver?
3- The Correlation between Heart beat rate and the obtained values?

providing circuit sketch will be very helpful but not necessary.
Thanks in advance.

  [1]: http://medicarduino.net/?page_id=204
  [2]: https://i.stack.imgur.com/7R0Ej.png
  [3]: https://i.stack.imgur.com/LKYUQ.png

body:
No, you cannot.  The sensor you link to has a circuit which attempts to detect IR light modulated at a specific frequency, and produces a digital output.   For a heartbeat sensor you need an analog output to feed into far more sophisticated signal processing - effectively the built-in processing gets in the way and means you cannot use it for this purpose.

Additionally, sensors of this type typically have an automatic gain control which means that they desensitize when subjected to continuous signal - they are designed for sources like remote controls where the modulation is itself pulsed on an off in small fractions of a second, so they interpret constant modulated light as noise and soon turn off their output.


message:
Arduino Due analog output has 500mV offset

I use a simple serial connection to tell the Due what to output into an analog output pin. However, the outputs are offset about 550mV (as seen on an oscilloscope) and the maximum value of 255 gives ~2.7V. What am I missing? Why can't the DAC output 0V - 3.3V mapped onto 0 - 255 values?

    int output = DAC1; // analog output pin
    String inData;

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

    void loop() {
      while (Serial.available() > 0) {
        char value = Serial.read();
        inData += value;
        if(value == '\n'){
          val = inData.toInt(); // 0..255
          analogWrite(output, val);
          Serial.println(val);
          inData = "";
        }
      }
    }

body:
I don't know how old this thread is, anyway I thought it doesn't hurt to give some insight because I experienced the same problem. Look at:
http://www.atmel.com/Images/Atmel-42187-ATSAM3X-and-ATSAM3A-Series-Checklist_AP-Note_AT03462.pdf
page 13: DAC0 and 1 voltage lays between 1/6 ADVREF and 5/6 ADVREF which corresponds to approximately ADVREF=3.2v; Span is (4/6)*3.2 = 2.1v
for periodic signals, Offset can be removed by using a small decoupling capacitor which will act as a high pass filter.
Hope this helps


body:
```
int output = DAC1; // analog output pin
String inData;
int val;

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

}

void loop() {
  while (Serial.available() > 0) {
    char value = Serial.read();
    inData += value;
    if(value == '\n'){
      val = inData.toInt(); // 0..255
      val=constrain(val, 543, 2720);
      analogWrite(output, map(val,543,2720, 0, 255));
      Serial.println(val);
      inData = "";
    }
  }
}
```


message:
Why is my interrupt code not working?

### Background

I'm trying to write code to read signals from a six-channel RC receiver on an [Arduino Mega 2560][1]. Currently I am keeping the code to just read one channel to make things easy to troubleshoot. The problem is my shared variable is not updating, leading me to believe that my interrupt service routine is not detecting any rising edges.

I thought my receiver was broken, so I tested it using [the standard Arduino attach interrupt function][2]. It worked perfectly, so my receiver is fine.

I used [Serial.print()][3] to see if my volatile channel variable was updating (that is, change its value to the channel 1 flag value). It was not updating, so my [ISR][4] must be wrong. You can find the original code in the blog post.

What's wrong? I'm out of ideas.

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

    #include <PinChangeInt.h>

    //Pin assignment
    #define channel1PIN 10

    //Bit flags
    #define Channel1FLAG 1

    //Flag holder
    volatile uint8_t bFLAGUPDATESHARED;

    //Shared variables: Accessed by the interrupt service routine and read in 'void loop'.
    volatile uint16_t unCHANNEL1SHARED;

    //Start time variables: These are used to set the start time of the rising edge of
    //a pulse. They are only accessed by the ISR, and thus they are unsigned integers and
    //not volatiles.

    uint32_t ulCHANNEL1START;

    void setup()
    {
      Serial.begin(9600);
      Serial.print("RC Channel PWM Read Interrupt Test");

      //PinChangInt library function. Used to set attach interrupts.
      PCintPort::attachInterrupt(channel1PIN, calcCHANNEL1, CHANGE);
    }

    void loop()
    {
      //In-loop variables to hold local copies of channel inputs.
      //This is static so it retains values between call loops.
      static uint16_t unCHANNEL1IN;

      //The in-loop copy of the bSHAREDFLAGUPDATE volatile flag holder
      static uint8_t bFLAGUPDATELOCAL;

      //Check to see if any channels have received signals. If so, copy
      //shared variables to local in loop variables.
      if (bFLAGUPDATESHARED)
      {
        //Switch off interrupts when I copy shared variables to local variables
        noInterrupts();

        bFLAGUPDATELOCAL = bFLAGUPDATESHARED;

        if (bFLAGUPDATELOCAL & Channel1FLAG)
        {
          unCHANNEL1IN = unCHANNEL1SHARED;
        }

        bFLAGUPDATESHARED = 0;
        interrupts();
      }

      Serial.println(unCHANNEL1IN);

      //Clear local update flags copy as all values have been copied to local variables
      bFLAGUPDATELOCAL = 0;
    }

    void calcCHANNEL1()
    {
      if (digitalRead(channel1PIN) == HIGH)
      {
        //If pin goes high, start timer and set ulCHANNEL1START to timer start
        ulCHANNEL1START = micros();
      }
      else
      {
        //If it is not rising, it must be falling so set shared
        //variable to current time-start time
        unCHANNEL1SHARED = (uint16_t)(micros() - ulCHANNEL1START);

        //Tell that channel 1 has received a signal
        bFLAGUPDATESHARED |= Channel1FLAG;
      }
    }

  [1]: https://www.arduino.cc/en/Main/ArduinoBoardMega2560
  [2]: https://www.arduino.cc/en/Reference/AttachInterrupt
  [3]: https://www.arduino.cc/en/Serial/Print
  [4]: https://en.wikipedia.org/wiki/Interrupt_handler

body: On the ATmega1280/2560, only ports B, J, F, and K have pin change interrupt capability. These map approximately to pins 10 through 15, 50 through 53, and A6 through A15 (although part of port J is unmapped to Arduino pins, therefore PCINT11 through PCINT15 are unavailable on the Arduino Mega/Mega 2560).


body:
Only **some** ports on the Atmega2560 support pin-change interrupts, specifically ports B, E (bit 0), J (bits 0 to 6) and K.

Looking at the reference schematic that means that these pins on the board are supported:

         Chip
    Name  Pin  Pin on board
    -----------------------

    Port B

    PB0 - 19 - D53 (SS)
    PB1 - 20 - D52 (SCK)
    PB2 - 21 - D51 (MOSI)
    PB3 - 22 - D50 (MISO)
    PB4 - 23 - D10
    PB5 - 24 - D11
    PB6 - 25 - D12
    PB7 - 26 - D13

    Port E

    PE0 - 2 - D0 (RXD0)

    Port J

    PJ0 - 63 - D15 (RXD3)
    PJ1 - 64 - D14 (TXD3)
    PJ2 to PJ6 - not connected on board

    Port K

    PK0 - PK7 - (89 - 82)  - A8 - A15

Thus you can see that D10 to D12, which you say works, are in that list. Other random ones would not be.

---

### SoftwareSerial

You can see confirmation on the page for [SoftwareSerial](https://www.arduino.cc/en/Reference/softwareSerial) where it says:

> Not all pins on the Mega and Mega 2560 support change interrupts, so only the following can be used for RX: 10, 11, 12, 13, 14, 15, 50, 51, 52, 53, A8 (62), A9 (63), A10 (64), A11 (65), A12 (66), A13 (67), A14 (68), A15 (69).

This is because SoftwareSerial uses pin-change interrupts to detect incoming serial data, and thus the disclaimer on that page about which pins it will work with.

---

### Atmega2560 pin-outs

[![Atmega2560 pin-outs][1]][1]

---

>  PinchangeInt should work on any digital pin

Note that the Atmega328P (as used in the Uno) has less ports, and all are available for pin-change interrupts on that board.

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


message:
How to communicate the Arduino board with SIM900?

I have a problem. I bought a SIM900 board, but I can not connect there with the Arduino. To send AT commands on the serial the SIM900 doesn't respond, but the LED indicating that the network is on. I've tried to change the baud rate of 9600 to 19200 in the firmware of the Arduino, but it still fails. I think I'm having a problem with the connections of the SIM900, since this board strikes me as obscure (could not find the schematic on the Internet)

The board I have is identical to this:
![enter image description here][1]

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

I'm 90% sure that I am connecting to the wrong pins. But I tried to reverse the jumpers and even some soldered pins on UART.

body:
I'll tell you what worked for me, because I didn't find the schematics of this board. But your board may work differently, so it is always good to check the datasheet and the schematic (if you have one).

##**Power**##

Be sure to use an external 5V source that can supply up to 2A without dipping significantly.

##**Code**##

    #include <SoftwareSerial.h>

    SoftwareSerial GPRS(7, 8);         //7 = TX, 8 = RX
    unsigned char buffer[64]; port
    int count=0;
    int i = 1;                         //if i = 0, send SMS.
    void setup(){
      //delay(10000);
      GPRS.begin(19200);               // the GPRS baud rate
      Serial.begin(19200);             // the Serial port of Arduino baud rate.
      Serial.print("I'm ready");
      Serial.print("Hello?");
    }

    void loop(){
      if (GPRS.available()){         // if date is comming from softwareserial port ==> data is comming from gprs shield

        while(GPRS.available()){          // reading data into char array
          buffer[count++]=GPRS.read();     // writing data into array
          if(count == 64)break;
        }
      Serial.write(buffer,count);            // if no data transmission ends, write buffer to hardware serial port
      clearBufferArray();              // call clearBufferArray function to clear the storaged data from the array
      count = 0;                       // set counter of while loop to zero
    }

    if (Serial.available())            // if data is available on hardwareserial port ==> data is comming from PC or notebook
      GPRS.write(Serial.read());       // write it to the GPRS shield
      if(i == 0){
        GPRS.print("AT+CMGF=1\r"); //sending SMS in text mode
        Serial.println("AT+CMGF=1\r");
        delay(1000);
        GPRS.print("AT+CMGS=\"+554988063979\"\r"); // phone number
        Serial.println("AT+CMGS=\"+554988063979\"\r");
        delay(1000);
        GPRS.print("Test\r"); // message
        Serial.println("Test\r");
        delay(1000);
        GPRS.write(0x1A); //send a Ctrl+Z(end of the message)
        delay(1000);
        Serial.println("SMS sent successfully");
        i++;
      }
    }

    void clearBufferArray(){              // function to clear buffer array
      for (int i=0; i<count;i++){
        buffer[i]=NULL;                  // clear all index of array with command NULL
      }
    }

##**Connection**##

![enter image description here][1]

##**Testing...**##

Open the serial monitor Arduino, set the baud rate in 19200 in "Both NL & CR". If not work, set to "Carriage Return". Type "AT" and wait for an OK.

![enter image description here][2]

##**Help**##

If you need help, these links were useful to me:

 1. http://www.seeedstudio.com/wiki/GPRS_Shield_V1.0
 2. http://www.seeedstudio.com/wiki/GPRS_Shield_V2.0
 3. http://www.elecfreaks.com/wiki/index.php?title=EFCom_GPRS/GSM_Shield

  [1]: https://i.stack.imgur.com/PfIu8.jpg
  [2]: https://i.stack.imgur.com/YaamU.png


message:
I2C TinyWireS SEND: How to convert unsigned long to uint8_t array?

How do you convert an unsigned long to a `uint8_t` array? I am interested in sending an unsigned long integer from an ATTiny85 to an Arduino Uno via I2C. The issue is with `TinyWireS.Send()` which can only send a var of type `uint8_t`. I believe the solution would be to use `TinyWireS.Send()` in an array?

body:
This might not be politically correct code, but it is pretty simple to just cast a pointer to uint8_t like this:

    long data = 5;
    uint8_t *rx = (uint8_t*) &data;

You can still use array subscripts even though its a pointer, and you can pass it to a function like an array. Just don't go past `rx[3]`.

Alternately, you could also make a union like this:

    union{ long data; uint8_t bytes[4]; } convert;
    convert.data = 5;

And then use `convert.bytes` as your array to send.


body:
I do exactly this with an ATtiny You have 32 bit long that needs to be broken up into 4 8-bit chunks. You need to some simple bit shifting to accomplish this.

    volatile unsigned long Data1;//this is the data you are sending
    volatile byte SendCount;
    volatile uint8_t sendByte;

    void requestEvent()
    {

      SendCount++; //increment this
      switch (SendCount)
      {
        case 1:
          Data1 = GetMyData();
          //Data1 = 55555;
          sendByte = Data1 & 0xFF;
          break;
        case 2:
          sendByte = Data1 >> 8;
          break;
        case 3:
          sendByte = Data1 >> 16;
          break;
        case 4:
          sendByte = Data1 >> 24;
          SendCount=0;
          break;
      }

      TinyWireS.send(sendByte);
    }

You need to initialize `SendCount = 0;` in your Setup method.

You will need to recompose the 4 bits back into a 32 bit long on the Master device too.


message:
Arduino Uno - combined LCD and keypad interfacing problem

I have a problem with the Arduino Uno.

I need to use a 4x3 keypad and 16x2 LCD together with an Arduino Uno. As 4x3 keypad requires 7 pins, I have defined pins 2, 3, 4, 5, 6, 7 and 8 to it. A 16x2 LCD requires 6 pins but only 5 pins remain (9, 10, 11, 12 and 13). Pins 0 and 1 are used for serial.

Please suggest a probable solution.

body:
You could use a shift register to read the switches as outlined by the excellent tutorial [Parallel to Serial Shifting-In with a CD4021BE][1]. Quoting the summary:

> Sometimes you'll end up needing more digital input than the 13 pins on
> your Arduino board can readily handle. Using a parallel to serial
> shift register allows you collect information from 8 or more switches
> while only using 3 of the pins on your Arduino.

So you would only use 3 pins to read the seven switches, which would leave you with 9 pins to play with, for the LCD.

In addition, you could use a similar method for the LCD, using a shift-out register, and use just 3 pins for the 6 inputs of the LCD. A tutorial for that is [Alphanumeric LCD with Shift Register on Arduino – part 1][2], using the [AlphaLCD library][3] or [3-Wire Serial LCD using a Shift Register][4], which has no library, but provides code.

This would leave you with 6 pins free (out of the total 12 pins, if you exclude pins 0 and 1 for serial), after both the switches and LCD are wired up.

Of course, this solution requires you to purchase one or two shift (in and/or out) registers.

The Arduino IDE may come with a built-in library that use shift registers, but I am not sure about that. Maybe someone can confirm, or refute, this?

I hope that this helps.

  [1]: http://www.arduino.cc/en/Tutorial/ShiftIn
  [2]: http://www.electroschematics.com/11155/alphanumeric-lcd-shift-register-arduino-part-1/
  [3]: http://www.electroschematics.com/wp-content/uploads/2015/01/AlphaLCD.zip
  [4]: http://www.electronics-lab.com/projects/mcu/015/