body:
I´m using Spark Fun Micro Pro board 5V:
https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide/hardware-overview-pro-micro

and to that i´ve hooked a true color OLED from digole:
http://www.digole.com/index.php?productID=859

Got a wire from OLED "data" to Pro micro "TX"-pin.

The OLED starts up and runs the start up screen, but the sample code I uploaded won't run. And that code looks like this:(the code is pretty long, if anybody would have a simplified sample code it would be much appreciated!! To get the OLED to show a simple "Hello World" would make me a very happy man! =)

Thanks!
<!-- language-all: lang-cpp -->

    #ifndef DigoleSerialDisp_h
    #define DigoleSerialDisp_h

    #include <inttypes.h>
    #include "Print.h"
    #include "Wire.h"
    #include "Arduino.h"

    // Communication set up command

    // Text function command

    // Graph function command

    #define Serial_UART 0
    #define Serial_I2C 1
    #define Serial_SPI 2
    #define _TEXT_ 0
    #define _GRAPH_ 1

    void setup() {}

    void loop () {}

    class DigoleSerialDisp : public Print {

    public:
    #if defined(_Digole_Serial_UART_)

    DigoleSerialDisp(HardwareSerial1 *s, unsigned long baud) //UART set up

    {

        _mySerial = s;

        _Baud = baud;

        _Comdelay=2;

    }

    size_t write(uint8_t value) {
        _mySerial->write((uint8_t)value);
        return 1; // assume sucess
    }

    void begin(void) {

        _mySerial->begin(9600);
        _mySerial->print("SB");
        _mySerial->println(_Baud);
        delay(100);
        _mySerial->begin(_Baud);

    }

     #endif

     #if defined(_Digole_Serial_I2C_)

    void begin(void) {
        _myWire->begin();
    }

    DigoleSerialDisp(TwoWire *s, uint8_t add) //U2C set up

    {

        _myWire = s;
        _I2Caddress = add;
        _Comdelay=6;

    }

    size_t write(uint8_t value) {

        _myWire->beginTransmission(_I2Caddress);

        _myWire->write((uint8_t)value);
        _myWire->endTransmission();

        return 1; // assume sucess

    }

    #endif

    #if defined(_Digole_Serial_SPI_)

    void begin(void) {

    }

    DigoleSerialDisp(uint8_t pin_data, uint8_t pin_clock, uint8_t SS) //spi set up

    {

        _Clockpin = pin_clock;
        _Datapin = pin_data;
        _SSpin = SS;

        pinMode(_Clockpin, OUTPUT);
        pinMode(_Datapin, OUTPUT);
        pinMode(_SSpin, OUTPUT);

        digitalWrite(_SSpin, HIGH);
        digitalWrite(_Clockpin, LOW);
        digitalWrite(_Datapin, LOW);

        _Comdelay=6;

    }

    size_t write(uint8_t value) {

        digitalWrite(_SSpin, LOW);
        digitalWrite(_SSpin, LOW);
        digitalWrite(_SSpin, LOW);

        shiftOut(_Datapin, _Clockpin, MSBFIRST, value);

        digitalWrite(_SSpin, HIGH);

        return 1; // assume sucess

    }

    #endif

    //    virtual size_t write(uint8_t);

        /*---------fucntions for Text and Graphic LCD adapters---------*/

    void disableCursor(void) {

        Print::print("CS0");

    }

    void enableCursor(void) {

        Print::print("CS1");

    }

    void clearScreen(void) {

        Print::print("CL");

    }

    void setI2CAddress(uint8_t add) {

        Print::print("SI2CA");

        write(add);

        _I2Caddress = add;

    }

    void displayConfig(uint8_t v) {

        Print::print("DC");

        write(v);

    }

    //print function

    size_t println(const __FlashStringHelper *v) {

        preprint();

        Print::println(v);

        Print::print("\x0dTRT");

    }

    size_t println(const String &v) {

        preprint();

        Print::println(v);

        Print::println("\x0dTRT");

    }

    size_t println(const char v[]) {

        preprint();

        Print::println(v);

        Print::println("\x0dTRT");

    }

    size_t println(char v) {

        preprint();

        Print::println(v);

        Print::println("\x0dTRT");

    }

    size_t println(unsigned char v, int base = DEC) {

        preprint();

        Print::println(v, base);

        Print::println("\x0dTRT");

    }

    size_t println(int v, int base = DEC) {

        preprint();

        Print::println(v, base);

        Print::println("\x0dTRT");

    }

    size_t println(unsigned int v, int base = DEC) {

        preprint();

        Print::println(v, base);

        Print::println("\x0dTRT");

    }

    size_t println(long v, int base = DEC) {

        preprint();

        Print::println(v, base);

        Print::println("\x0dTRT");

    }

    size_t println(unsigned long v, int base = DEC) {

        preprint();

        Print::println(v, base);

        Print::println("\x0dTRT");

    }

    size_t println(double v, int base = 2) {

        preprint();

        Print::println(v, base);

        Print::println("\x0dTRT");

    }

    size_t println(const Printable& v) {

        preprint();

        Print::println(v);

        Print::println("\x0dTRT");

    }

    size_t println(void) {

        Print::println("\x0dTRT");

    }

    size_t print(const __FlashStringHelper *v) {

        preprint();

        Print::println(v);

    }

    size_t print(const String &v) {

        preprint();

        Print::println(v);

    }

    size_t print(const char v[]) {

        preprint();

        Print::println(v);

    }

    size_t print(char v) {

        preprint();

        Print::println(v);

    }

    size_t print(unsigned char v, int base = DEC) {

        preprint();

        Print::println(v, base);

    }

    size_t print(int v, int base = DEC) {

        preprint();

        Print::println(v, base);

    }

    size_t print(unsigned int v, int base = DEC) {

        preprint();

        Print::println(v, base);

    }

    size_t print(long v, int base = DEC) {

        preprint();

        Print::println(v, base);

    }

    size_t print(unsigned long v, int base = DEC) {

        preprint();

        Print::println(v, base);

    }

    size_t print(double v, int base = 2) {

        preprint();

        Print::println(v, base);

    }

    size_t print(const Printable& v) {

        preprint();

        Print::println(v);

    }

    void preprint(void);

    /*----------Functions for Graphic LCD/OLED adapters only---------*/

    //the functions in this section compatible with u8glib

    void drawBitmap(unsigned int x, unsigned int y, unsigned int w, unsigned int h, const uint8_t *bitmap);

    void drawBitmap256(unsigned int x, unsigned int y, unsigned int w, unsigned int h, const uint8_t *bitmap);

    void drawBitmap262K(unsigned int x, unsigned int y, unsigned int w, unsigned int h, const uint8_t *bitmap);

    void setTrueColor(uint8_t r, uint8_t g, uint8_t b);

    void setRot90(void);

    void setRot180(void);

    void setRot270(void);

    void undoRotation(void);

    void setRotation(uint8_t);

    void setContrast(uint8_t);

    void drawBox(unsigned int x, unsigned int y, unsigned int w, unsigned int h);

    void drawCircle(unsigned int x, unsigned int y, unsigned int r, uint8_t = 0);

    void drawDisc(unsigned int x, unsigned int y, unsigned int r);

    void drawFrame(unsigned int x, unsigned int y, unsigned int w, unsigned int h);

    void drawPixel(unsigned int x, unsigned int y, uint8_t = 1);

    void drawLine(unsigned int x, unsigned int y, unsigned int x1, unsigned int y1);

    void drawLineTo(unsigned int x, unsigned int y);

    void drawHLine(unsigned int x, unsigned int y, unsigned int w);

    void drawVLine(unsigned int x, unsigned int y, unsigned int h);

    //-------------------------------

    //special functions for our adapters

    void setFont(uint8_t font); //set font, availale: 6,10,18,51,120,123, user font: 200-203

    void nextTextLine(void); //got to next text line, depending on the font size

    void setColor(uint8_t); //set color for graphic function

    void backLightOn(void); //Turn on back light

    void backLightOff(void); //Turn off back light

    void directCommand(uint8_t d); //send command to LCD drectly

    void directData(uint8_t d); //send data to LCD drectly

    void moveArea(unsigned int x0, unsigned int y0, unsigned int x1, unsigned int y1, char xoffset, char yoffset); //move a area of screen to another place
    void drawStr(unsigned int x, unsigned int y, const char *s);
    void setPrintPos(unsigned int x, unsigned int y, uint8_t =0 );
    void setLCDColRow(uint8_t col, uint8_t row);

    void setTextPosAbs(unsigned int x, unsigned int y);
    void write2B(unsigned int v);

    void displayStartScreen(uint8_t m) {

        Print::print("DSS");

        write(m);

    } //display start screen

    void setMode(uint8_t m) {

        Print::print("DM");

        write(m);

    } //set display mode

    void setTextPosBack(void) {

        Print::print("ETB");

    } //set text position back to previous, only one back allowed

      void setTextPosOffset(char xoffset, char yoffset) {

        Print::print("ETO");

        write(xoffset);

        write(yoffset);

    }

    void setLinePattern(uint8_t pattern) {

        Print::print("SLP");

        write(pattern);

     }

    void setLCDChip(uint8_t chip) {      //only for universal LCD adapter

        Print::print("SLCD");

        write(chip);

     }
    void setBackLight(uint8_t bl){
        Print::print("BL");

        write(bl);

    }

    void uploadStartScreen(int lon, const unsigned char *data); //upload start screen

    void uploadUserFont(int lon, const unsigned char *data, uint8_t sect); //upload user font

    void digitalOutput(uint8_t x) {Print::print("DOUT");write(x);}

    private:

    unsigned long _Baud;

    HardwareSerial *_mySerial;

    uint8_t _I2Caddress;

    TwoWire *_myWire;

    uint8_t _Clockpin;

    uint8_t _Datapin;

    uint8_t _SSpin;

    uint8_t _Comdelay;

    };

    #endif

title: Can't get my code to my OLED

Answers: 0


body:
The below code starts off with lots of data in the beginning, distracting the reader from the actual code.  What is the best practice to clean this up:

    #include <Wire.h>
    // For LED Backpack
    #include "Adafruit_LEDBackpack.h"
    #include "Adafruit_GFX.h"
    // For LCD Shield
    #include <Adafruit_MCP23017.h>
    #include <Adafruit_RGBLCDShield.h>

    // For pixel Units, such as hero
    #include <Unit.h>

    Adafruit_BicolorMatrix matrix = Adafruit_BicolorMatrix();
    Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

    Unit *hero;
    boolean doesNeedRedraw = true;
    boolean textNeedsRedraw = true;
    int8_t lastButtonPress = 0;
    int8_t frame = 0;

    void setup() {
      /* Important Setup Routine */
    }

    static const uint8_t PROGMEM
      smile_bmp[] =
      { B00111100,
        B01000010,
        B10100101,
        B10000001,
        B10100101,
        B10011001,
        B01000010,
        B00111100 },
      neutral_bmp[] =
      { B00111100,
        B01000010,
        B10100101,
        B10000001,
        B10111101,
        B10000001,
        B01000010,
        B00111100 },
      frown_bmp[] =
      { B00111100,
        B01000010,
        B10100101,
        B10000001,
        B10011001,
        B10100101,
        B01000010,
        B00111100 },
      walls_bmp[] =
      { B10100000,
        B10110000,
        B10010000,
        B11011100,
        B01000100,
        B01110100,
        B00010100,
        B00011100 };

    void loop() {
      /* Important Main Loop Routine */
    }

title: Arduino: Put Data in Other File

Answers: 2

body:
One way to clean that up is to create a "Globals.inc" file and cut and paste all of your globals into there.  After that's done, simply include the globals file from your main .ino file with `#include "Globals.inc"`

(Main.ino)

    #include <Wire.h>
    // For LED Backpack
    #include "Adafruit_LEDBackpack.h"
    #include "Adafruit_GFX.h"
    // For LCD Shield
    #include <Adafruit_MCP23017.h>
    #include <Adafruit_RGBLCDShield.h>

    // For pixel Units, such as hero
    #include <Unit.h>

    #include "Globals.inc"

    void setup() {
      /* Important Setup Routine */
    }

    void loop() {
      /* Important Main Loop Routine */
    }

(Globals.inc)

    Adafruit_BicolorMatrix matrix = Adafruit_BicolorMatrix();
    Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

    Unit *hero;
    boolean doesNeedRedraw = true;
    boolean textNeedsRedraw = true;
    int8_t lastButtonPress = 0;
    // 0-255
    uint8_t frame = 0;

    static const uint8_t PROGMEM
      smile_bmp[] =
      { B00111100,
        B01000010,
        B10100101,
        B10000001,
        B10100101,
        B10011001,
        B01000010,
        B00111100 },
      neutral_bmp[] =
      { B00111100,
        B01000010,
        B10100101,
        B10000001,
        B10111101,
        B10000001,
        B01000010,
        B00111100 },
      frown_bmp[] =
      { B00111100,
        B01000010,
        B10100101,
        B10000001,
        B10011001,
        B10100101,
        B01000010,
        B00111100 },
      walls_bmp[] =
      { B10100000,
        B10110000,
        B10010000,
        B11011100,
        B01000100,
        B01110100,
        B00010100,
        B00011100 };

body:
There is actually not a lot wrong with the way the code is.  You are writing / using embedded code. It is not expected to be some planned out UML model, and does not need to look like it is.

If you just want less lines, start by converting your binary data to hex. Otherwise the answer of a global.h is valid (and I would still convert binary to hex). You could easily shrink 24 lines down to 3.

If you could use a real IDE navigation would be unimportant, but since Arduino chose not to use a standard build process it takes extra effort (but still worth it). You could also switch to native AVR (and easily use a real IDE), which is what I plan to do as soon as the proof of concept is finished.


body:
I'm trying to use the Arduino Uno to make a strip of LEDs blink as fast as they can while still blinking at different rates. I am able to get them blinking at different rates but the blinking is very slow:

    #include <Adafruit_DotStar.h>
    #include <SPI.h>         // COMMENT OUT THIS LINE FOR GEMMA OR TRINKET

    #define NUMPIXELS 144 // Number of LEDs in strip

    // Here's how to control the LEDs from any two pins:
    #define DATAPIN    11
    #define CLOCKPIN   13
    Adafruit_DotStar strip = Adafruit_DotStar(NUMPIXELS, DATAPIN, CLOCKPIN);

    void setup() {
    strip.begin(); // Initialize pins for output
    strip.show();  // Turn all LEDs off ASAP
    }

      int brightness = 1; //Setting brightness of all LEDs

       void loop() {

      for(int i=1; i<6; i++)
    //This loop is here so the number i can be used below to get different blink     //rates for the 3 LEDs blink at the same time
      {
        if(i%2==0){

        strip.setPixelColor(0, brightness, brightness, brightness);
        }
        else
        {strip.setPixelColor(0, 0);
        }
        //Sets blink rate of first LED, will be the fastest

        if(i%3==0){

        strip.setPixelColor(1, brightness, brightness, brightness);
        }
        else
        {strip.setPixelColor(1, 0);
        }
         //Sets blink rate of second LED

        if(i%4==0){

        strip.setPixelColor(2, brightness, brightness, brightness);
        }
        else
        {strip.setPixelColor(2, 0);
        }
         //Sets blink rate of third LED

       strip.show();
      }
      }
I thought I would be able to make them blink as fast as possible by using the micro() function as my counter instead of the i in the for loop, but this led to strange behavior:

    #include <Adafruit_DotStar.h>
    #include <SPI.h>

    #define NUMPIXELS 144 // Number of LEDs in strip

    // Here's how to control the LEDs from any two pins:
    #define DATAPIN    11
    #define CLOCKPIN   13
    Adafruit_DotStar strip = Adafruit_DotStar(NUMPIXELS, DATAPIN, CLOCKPIN);

    void setup() {

      strip.begin(); // Initialize pins for output
      strip.show();  // Turn all LEDs off ASAP

      Serial.begin(9600);
    }

    int brightness = 1;

    void loop() {

        int time = micros();

        if(time%2==0){

        strip.setPixelColor(0, brightness, brightness, brightness);
        }
        else
        {strip.setPixelColor(0, 0);
        }

      if(time%3==0){
        strip.setPixelColor(1, brightness, brightness, brightness);
        }
        else
        {strip.setPixelColor(1, 0);
        }

       if(time%4==0){
        strip.setPixelColor(1, brightness, brightness, brightness);
        }
        else
        {strip.setPixelColor(2, 0);
        }

       strip.show();
    }

This led to the first LED appearing on (good, presumably I wouldn't be able to see it blinking) and the second blinking at a rate I could see (I shouldn't be able to see this) and the third LED is not on at all.

Can anyone see the mistake I'm making? Am I using the micro() function right?
Thank you!

title: Blinking LEDs as fast as possible at different rates.

Answers: 0


body: My arduino gets some data from sensors and save it into EEPROM. Now, I want that when I connect my arduino to PC there should be a software(like sketch) which can fetch data from arduino's EEPROM processes it and saves it into a file in PC. I am willing to create such a software but how will I then communicate with arduino like Sketch does?

title: How to transfer data from Arduino to some software in computer?

Answers: 3

body:
The options that I see:

* Via serial - this can either be done wirelessly via Bluetooth serial adapter, or via the standard USB connector. Your program will have to have a way of sending the data - some way to indicate that you want to download the data.
* Transfer via ICSP - these are the 2x3 grid of pins on your Arduino. You can download the data, without having to write any code. You will need something like a USBASP - they're cheap. You can download the entire EEPROM, and dissect it once you have it on your computer.

I have a vague recollection that EEPROM may be overwritten when you upload a sketch, so if you want to use serial (the first option), make sure your sketch already knows how to transfer the data before you collect it. This is not a limitation for ICSP.

body:
You should specify what programming language/compiler/IDE you want to use for the part on your pc.

I would suggest using "Processing" - https://processing.org/ it's a similiar IDE as the arduino IDE and the coding is also a bit similiar. You can use a serial library to receive data from USB/COM port.

Processing has the ability to create a window with graphics. You could read the position of something with your arduino, then send it to 'processing' and it will draw the object on the screen (after a bit of coding).

Guide: https://learn.sparkfun.com/tutorials/connecting-arduino-to-processing

body:
Just use serial communication. Make sure you know which port your Arduino is recognized in your system, make a sketch to send data through Arduino's [serial communication][1] and try making a simple [Node.js][2] application using [**serialport**][3] package which will receive your data. There is a code sample where you can start from. Just set the port and start receiving data. And that's good, using Node.js you are really close to web tools, so it's easy to migrate your application to web.

It's really simple and you can get it done in a few minutes, even if you have not been introduced to node.

These kind of embedded applications have been accepted by Node.js and there are plenty of robotics projects which use node on the web.

    var SerialPort = require("serialport").SerialPort
    var serialPort = new SerialPort("/dev/ttyACM0", {
      baudrate: 57600
    });

Usually Arduino is recognized as ttyACM0 on Unix-based systems.
With this line of code you establish a serial communication with your board.

Going further you can register events like data, which is fired when data comes from Arduino:

    // it opens the connection and register an event 'data'
    serialPort.on("open", function () {
      console.log('Communication is on!');

      // when your app receives data, this event is fired
      // so you can capture the data and do what you need
      serialPort.on('data', function(data) {
        console.log('data received: ' + data);
      });
    });

In this example your app just receives data and log it to your terminal.

  [1]: http://www.arduino.cc/en/Serial/Write
  [2]: https://nodejs.org/
  [3]: https://www.npmjs.com/package/serialport


body:
I'm programming an arduino uno with attached screen to be a clock and have the code below. It counts up from zero the milliseconds, seconds, minutes and hours and when it hits 24 hours it starts again from zero.
Does anyone know how I can set the start time that it automatically starts at when it is reset? It will be a one off thing and I don't want it to interfere with the clock resetting to 0 hours after it hits 24. Thanks

    #include <Wire.h>
    #include <LiquidCrystal.h>

    #define MILLIS_OVERFLOW 34359738

    /**
     * Clock Variables
     */
    unsigned long currentMillis, previousMillis, elapsedMillis;
    int seconds, minutes, hours;

    LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

    void setup()
    {
        lcd.begin( 16, 2 );

    }

    void loop()
    {
        setClock();
        /**
         * After set clock now you have 3 int variables with the current time
         */
         //seconds
         //minutes
         //hours
         lcd.setCursor ( 0, 1);
         lcd.print(hours);
         lcd.print(":");
         lcd.print(minutes);
         lcd.print(":");
         lcd.print(seconds);
         lcd.print(":");
         lcd.print(elapsedMillis);

    }

    void setClock()
    {
        currentMillis = millis();
        /**
         * The only moment when currentMillis will be smaller than previousMillis
     * will be when millis() oveflows
     */
    if (currentMillis < previousMillis){
        elapsedMillis += MILLIS_OVERFLOW - previousMillis + currentMillis;
    } else {
        elapsedMillis += currentMillis - previousMillis;
    }

    /**
     * If we use equals 1000 its possible that because of the mentioned loop limitation
     * you check the difference when its value is (999) and on the next loop its value is (1001)
     */
    if (elapsedMillis > 999){
        seconds++;
        elapsedMillis = elapsedMillis - 1000;
    }

    if (seconds == 60){
        minutes++;
        seconds = 0;
    }
    if (minutes == 60){
        hours++;
        minutes = 0;
    }
    if (hours == 24){
        hours = 0;
    }

    previousMillis = currentMillis;
    }

title: Set start time for arduino uno clock

Answers: 1

body:
Assume you want the clock to start at 08:42:21, change

    int seconds, minutes, hours;
to

    int seconds = 21, minutes = 42, hours = 8;

Note that you should always also initialize (as in the second case above), and not only declare (as in the first case) all variables before you first read their values. Otherwise, for local variables you [cannot be sure][1] what their initial value is. (Global variables are [implicitly initialized][2] to zero if not explicitly initialized.)

  [1]: https://stackoverflow.com/a/11233616/143931
  [2]: https://stackoverflow.com/q/14049777/143931


body:
I currently have a standing desk at work, and I thought a fun way to learn Arduino would be to automate it, as it currently uses a hand crank.

I would love some help determining what I would need for this task.

What kind of motor should I use?
  -Stepper motor?
  -High/low rpm?
  -High/low torque?

What sort of power would I need?

Looking forward to hearing people's suggestions!

title: Arduino Stepper Motor Standing Desk help!

Answers: 2

body:
I think this might end up being more of a fun way to electrocute yourself, but let's find out...

Energy required to lift an object with mass "m" an upward distance of "h" in the Earth's gravitational field, on the surface...  E = mgh = m(9.8)h

So, to lift a 50kg desk one meter, we will need 50 x 9.8 x 1 = 490 Joules

How fast do you want to lift it? Let's say we want it to take 10 seconds - that will give us the power level we need. Power is in watts (Joules per second) - so if we want to lift the desk in 10 seconds we need 49 watts - let's call it 50.

Now, to produce 50 watts with a 12-volt battery, that would be 4.2 Amps. This is do-able, and it's not the high power level I expected for lifting a desk. Even if we throw in some efficiency losses, we're well within the safety zone and won't have to get out the high voltage equipment. So, I'm glad I did the math - my initial impression of this task was the joke at the beginning of the post.

So, you need a 50 watt motor... that's easy to find. Hell, why not go way over that and get a 100-watt motor... google that...

http://www.electricscooterparts.com/motors24volt.html - bang! Scooter motors! Nice!

So, that's an example of how you might figure out what parts to get - it all starts with basic physics and ends with Google (or Bing if you're one of *those* people). I simplified a lot, but you get the idea.

The other part of this task is to figure out the control system. I would probably not use Arduino to do this. I would have three switches - one "directional" switch to run the motor, and two sensor switches to disconnect the directions of the motor at each end of the track. I think that's how automatic power windows in cars used to work, which explains why if you didn't hold the button down long enough, it would immediately instead of continuing to the other end - it was still sitting on the sensor.

Sticking an Arduino in the mix and having it read the sensors would just waste power all day long, but you could do it that way. It's the same idea - just mount sensors on the track, which get tripped when the desk rolls up to that spot. Coding wouldn't be that tricky - when the user activates the "change button" or whatever, check which sensor is currently active, and move the desk the other way until the other sensor activates.

You're going to need a good power supply for that motor - a 24-volt **2**00-watt power supply if you like to over-engineer like I do. You'll need a relay to control the motor - it needs to handle 24 volts/200 watts. Then you'll need some kind of activation button, and two sensors. You want some kind of sensor that is definitely going to be activated when the desk is in position, or you risk over-running your target, binding the mechanics, and burning the motor, and possibly the office as well. So, I would choose some kind of mechanical sensor, not a light sensor or something like that.

This should get you started on finding those parts...
https://www.sparkfun.com/categories/145 - these are all kinds of buttons and switches - you should be able to find something that you can mount to the track which will activate when the desk runs into it. Search on this site for the other parts - they have the relays and stuff too.

Final warning though - this may be too complicated and dangerous for a first project. At 24 volts and 100 watts, we are getting into dangerous power levels. But, these are common power levels in consumer equipment. So, if you know what you're doing you should be safe. If you don't, I strongly suggest getting an experienced electrical engineer to look at your designs. Also, you probably can't install this device in an office - there is an insurance reason that it hand-cranks, your company isn't just being cheap.

What happens if someone bumps the desk and it becomes active when you're not around? What happens when the power goes out? What happens when the power comes back on? Do we have enough fuses in the right places to shut this system down before it catches fire? You need to consider all that.

body:
For initial playing,  and possibly for a final solution, battery powered electric drills with external powering are an excellent source of reasonable wattage well geared down motors. Drills are often discarded when the batteries die and may be available free or at lo cost.

For relatively low duty cycle use 9V drills operate OK on a small 12V battery and drills rated at up to 18V usually operate well enough on 12V.

Use of a 12V lead acid battery charged by a trickle charger makes high current peaks easy to accommodate. Almot any condition battery will do - one which is too dead for eg motorcyle use probably works well enough here. Floating 12V lead acid batteries at 13.7 V allows them to be permanenetly connected to the "charger".  A power pack can be used without a battery if enough current is provided.

Battery powered drills typically have a  two stage epicyclic gearbox giving typically hundreds of RPM output speed. If desired you can use the supplied switching which has a DPDT mechanical reversing switch. If you remove the mechanical reversing switch you can feed voltage directly to the motor. Changing polarity changes direction.

Dismantling the gearbox can be educational but may be a one way journey. Beware a flood of ball bearings.


body:
I have a two-relay system set up to a DC motor. So, if I close one relay, the motor moves on one way and if I close the second relay (and open the first) the motor goes on the other direction.

I compare two variables (target inclination and real inclination) if they are not the same I would like to open one of the two relays UNTIL the are the same value.

Both variables are calculated based on inclinometer input and some aritmethics.

I do know how to calculate the variables, how to close the relay based in the comparation of variables and which relay open.

But I don´t know how I can tell to open the relay because the motor has reached target inclination.

How I can recalculate and compare constantly target inclination and real inclination when the relay is closed and the motor moving?
Is this posible on Arduino? Is this multithreading?

Thank you very much, any ideas are welcome!

title: Relay feedback control

Answers: 2

body:
This is a classic system where PID will really pay off. Basically this will allow you to tune your system so that if you are off by 5 degree it will open the relays for 3 seconds. But if you are off by 1 degree it will open them for half a second. (Or whatever works for you). It might be tricky for you to get right but it will give you the smooth response that looks really good and feels natural.

Take a look here http://playground.arduino.cc/Code/PIDLibrary

body:
Answering my own question, I think I found some way to get the solar panel face the sun.

As said before, the inclinometer reads the position and makes some calculations using lookposition() function, then this happens:

    void lookforsun() {
      while ((targetElevation + 3) < realElevation | (targetElevation - 3) > realElevation) {

        Serial.println("Elevation is not correct");

        while (realElevation < targetElevation)
        { Serial.println("Moving to south");
          digitalWrite(south, LOW);
          lookposition();
        }
        digitalWrite(south, HIGH);

        while (realElevation > targetElevation)
        { Serial.println("Moving to north");
          digitalWrite(north, LOW);
          lookposition();
        }
        digitalWrite(north, HIGH);
      }

      while ((targetHourangle+3) < realHourangle |  (targetHourangle-3) > realHourangle  ) {

        Serial.print("Hour angle is not correct");
        while (realHourangle > targetHourangle)
        { Serial.println("Moving to east");
          digitalWrite(east, LOW);
          lookposition();
        }
        digitalWrite(east, HIGH);

        while (realHourangle < targetHourangle)
        { Serial.println("Moving to west");
          digitalWrite(west, LOW);
          lookposition();
        }
        digitalWrite(west, HIGH);
      }

As you can see I took the frightening way of nested while loops, but appears to work.

The first while measures if realElevation is between +-3 degrees of targetElevation, if realElevation is far away (target+-3) enters the second while loop, which determines if needs to go up or down.

I included the +-3 because the sensor is so very sensible.

Thank you very much  Russell McMahon and portforwardpodcast for your ideas!


body:
When Arduino was conceived AVR was very much the best 8-bit controller available. But we're 10 years on now, and still using the AVR, despite lots of better microcontrollers available, notably ARMs. In particular M0 and M0+ cores are a lot cheaper, yet are a lot faster and have many more features than AVR.
For instance the NXP LPC824 has more serial buses, more A/D channels and higher A/D resolution, is almost twice as fast as the AVR, yet costs 30% less. (Granted, it doesn't have EEPROM, but you can have that for 20 cents.)

So I was wondering if there are particular issues which prevent the use of more modern microcontrollers on Arduino.
One difference may be Vcc, which is 5V for AVR and 3.3V for ARM. But given that more peripherals work at 3.3V this seems more to be an AVR issue than an ARM issue.

PS: I'm aware of Arduino Due, but that one costs twice as much as a Uno. I'm talking about controllers which price-wise can compete with AVR.

title: What are possible issues when moving Arduino to another microcontroller?

Answers: 1

body:
There is NO *best* 8 bit or 16 or whatever bit uC (micro controller).
There always have been "better" ones and there always will be and better changes with your need as well as with time.

If you want or need a faster or more capable processor, use one.
For many tasks the existing AVR processors are very fine indeed.

A number of people are making Arduino-like uC's using ARM right now.
You can buy them 'off the shelf'.

Running "Arduino" code is where issues arise:
If you are willing to run 100% standard Arduino code applications will usually run well on the new uC.
If applications use precompiled libraries and you wish to use eg an ARM it will not run.
If you recompile the libraries and they are written in a compatible language flavor (C or whatever) then they MAY work for your new processor.
If they use assembler then they will not work in essentially all cases.

But, existing 'Arduino' hardware can use the high level language of your choice.
A new processor with a compatible compiler will compile eg C code that runs on Arduino hardware BUT port locations, register control methods etc need to be correctly allowed for.

It gets harder and harder as you try to fit the new giants into the old not-so-giant framework. Somewhere along the way it is easier to give up the attempt and use the Arduino for what it is good for and the 'new' processor where necessary.

**Whatever the Arduino did well when new it still does well.**

In most cases the speed, peripherals and memory capabilities are entirely fine for tasks that people who wish to use it wish to do.
The main issue is that an Arduino is not something it is not, just as a small family car is not a bus or a sportscar. Use the car where it is useful and use a bus or sportscar when necessary.


body:
I write a code to store patterns for LED blinking, but I got this error:

    led_basics:39: error: cannot convert 'char (*)[17][2]' to 'char*' in initialization

    led_basics:39: error: cannot convert 'char (*)[16][2]' to 'char*' in initialization

    led_basics:39: error: cannot convert 'char (*)[13][2]' to 'char*' in initialization

and so on for all pattern.
How can I fix it?
Here is the code:

    char nulla[17][2]={{0,127},{8,125},{9,121},{10,113},{12,97},{14,65},{24,67},{27,71},{28,70},{30,78},{32,76},{36,88},{40,80},{42,112},{48,96},{56,64},{68,0}};

    char egy[16][2]={{0,0},{9,4},{16,6},{18,2},{21,3},{27,7},{28,6},{30,14},{32,12},{36,24},{40,16},{42,48},{48,32},{51,96},{56,64},{68,0}};

    char ketto[13][2]={{0,98},{7,99},{8,97},{12,113},{14,81},{20,89},{21,88},{24,74},{27,78},{30,70},{32,68},{36,64},{68,0}};

    char harom[17][2]={{0,34},{7,35},{8,33},{10,41},{14,9},{17,73},{21,72},{24,74},{27,78},{30,70},{32,68},{36,80},{42,112},{48,96},{51,32},{56,0},{68,0}};

    char negy[17][2]={{0,7},{7,6},{8,4},{9,0},{10,8},{21,9},{24,11},{27,15},{28,14},{32,12},{36,24},{40,16},{42,48},{48,32},{51,96},{56,64},{68,0}};

    char ot[14][2]={{0,39},{8,37},{9,33},{10,41},{14,9},{17,73},{28,72},{30,64},{36,80},{42,112},{48,96},{51,32},{56,0},{68,0}};

    char hat[17][2]={{0,62},{7,63},{8,61},{9,57},{12,41},{14,9},{17,73},{21,72},{24,74},{30,66},{32,64},{36,80},{42,112},{48,96},{51,32},{56,0},{68,0}};

    char het[15][2]={{0,7},{8,5},{9,1},{24,3},{27,7},{28,6},{30,14},{32,12},{36,24},{40,16},{42,48},{48,32},{51,96},{56,64},{68,0}};

    char nyolc[15][2] = {{0,127},{8,125},{9,121},{12,105},{14,73},{24,75},{27,79},{28,78},{32,76},{36,88},{40,80},{42,112},{48,96},{56,64},{68,0}};

    char kilenc[13][2] = {{0,79},{8,77},{9,73},{24,75},{27,79},{28,78},{32,76},{36,88},{40,80},{42,112},{48,96},{56,64},{68,0}};

    char kettospont[6][2] = {{0,0},{9,4},{12,20},{18,16},{24,0},{68,0}};

    char *karakterek[11]={&nulla,&egy,&ketto,&harom,&negy,&ot,&hat,&het,&nyolc,&kilenc,&kettospont};

title: cannot convert error with pointers

Answers: 2

body:
karakterek is an array of char pointers.  It cannot be used to store pointers to char arrays.

I'm not sure it would be possible to store pointers to your 2 dimensional arrays since they are all of different dimensions.  Someone else might know a way to do that.

Here's how I would do it (using as similar as possible a structure):

    char nulla[]={0,127,8,125,9,121,10,113,12,97,14,65,24,67,27,71,28,70,30,78,32,76,36,88,40,80,42,112,48,96,56,64,68,0};

    char egy[]={0,0,9,4,16,6,18,2,21,3,27,7,28,6,30,14,32,12,36,24,40,16,42,48,48,32,51,96,56,64,68,0};

    char ketto[]={0,98,7,99,8,97,12,113,14,81,20,89,21,88,24,74,27,78,30,70,32,68,36,64,68,0};

    char harom[]={0,34,7,35,8,33,10,41,14,9,17,73,21,72,24,74,27,78,30,70,32,68,36,80,42,112,48,96,51,32,56,0,68,0};

    char negy[]={0,7,7,6,8,4,9,0,10,8,21,9,24,11,27,15,28,14,32,12,36,24,40,16,42,48,48,32,51,96,56,64,68,0};

    char ot[]={0,39,8,37,9,33,10,41,14,9,17,73,28,72,30,64,36,80,42,112,48,96,51,32,56,0,68,0};

    char hat[]={0,62,7,63,8,61,9,57,12,41,14,9,17,73,21,72,24,74,30,66,32,64,36,80,42,112,48,96,51,32,56,0,68,0};

    char het[]={0,7,8,5,9,1,24,3,27,7,28,6,30,14,32,12,36,24,40,16,42,48,48,32,51,96,56,64,68,0};

    char nyolc[] = {0,127,8,125,9,121,12,105,14,73,24,75,27,79,28,78,32,76,36,88,40,80,42,112,48,96,56,64,68,0};

    char kilenc[] = {0,79,8,77,9,73,24,75,27,79,28,78,32,76,36,88,40,80,42,112,48,96,56,64,68,0};

    char kettospont[] = {0,0,9,4,12,20,18,16,24,0,68,0};

    char* karakterek[]={nulla,egy,ketto,harom,negy,ot,hat,het,nyolc,kilenc,kettospont};

For starters, I'd make the char arrays single dimension.  Since the 2nd dimension is always a size of 2, you could index through your values reading index 0 into x0, index 1 to y0, index 2 to x1 and index 3 to y1 (I'm assuming these are x y co-ordinate pairs).

Secondly, I'd lose the hard-coded sizes for the arrays.  If you want to add or remove entries, you don't have to keep updating the sizes.

Finally, I'd lose the '&' from your array of array pointers.  Referring to an array simply by its name gives you a pointer to it.  I think '&<array_name>' gives you a pointer to the pointer, but I could be wrong.

body:
As the second dimension is always 2, you can do this:

    typedef char Tuple[2];

    Tuple nulla[17] = {{0,127},{8,125},{9,121},{10,113},{12,97},{14,65},{24,67},{27,71},{28,70},{30,78},{32,76},{36,88},{40,80},{42,112},{48,96},{56,64},{68,0}};
    Tuple egy[16]   = {{0,0},{9,4},{16,6},{18,2},{21,3},{27,7},{28,6},{30,14},{32,12},{36,24},{40,16},{42,48},{48,32},{51,96},{56,64},{68,0}};
    Tuple ketto[13] = {{0,98},{7,99},{8,97},{12,113},{14,81},{20,89},{21,88},{24,74},{27,78},{30,70},{32,68},{36,64},{68,0}};
    // etc.

    Tuple* karakterek[3] = {nulla, egy, ketto}; // etc.

(The `typedef` makes it easier.)


body:
I came across this [instructable][1] about using no external hardware but two pwm pins to control a motor in both directions. Usually you would use an H bridge. However, ever since I have had my Arduino I have heard that you are not supposed to connect a pin to another pin. So how does this circuit works. It looks like he sends a signal from one pin and in my experience it would fry the board. So basically, my question is this circuit ok with an Arduino Nano and if so how does it work? Below is a picture of the setup he gave:
![enter image description here][2]

  [1]: http://www.instructables.com/id/Simple-2-way-motor-control-for-the-arduino/
  [2]: https://i.stack.imgur.com/KPyz3.jpg

title: How does this Motor Circuit not ruin the Microcontroller

Answers: 3

body:
You are not supposed to connect one pin directly to another pin because the current will destroy the electronics connected to the pins. The motor provides a small impedance and limits the current flowing (although the amount of current will increase if the motor stalls).

As to the other reason you missed for the MCU possibly being damaged, the answer is that it is absorbed by the input protection diodes and subsequently the supply.

body:
This is a bad idea, but not because two pins seem to be connected directly. They're not; there is a load (the motor) between the pins, and that motor will take care of different levels between the pins. High and low will make the motor turn one way, low and high the other way, and the same level on both pins will stop the motor.

Why is this bad? An I/O pin can only supply a limited current, and even for a small motor that will peak rather high. If you run the motor for some time this way you will damage the I/O ports. An H-bridge, like you mention, is the solution.
Note that electric motors cause a lot of noise in the power supply, which may cause the microcontroller to reset all the time, so that your program doesn't work. (The motor may seem to start/stop all the time.) You need to decouple the power supply with capacitors.

body:
Another problem here is when running a motor you want to include a 'flyback diode' to prevent damage from voltage spikes, which is a problem with loads like motors.

See [this article][1] for details.

  [1]: http://www.nerdkits.com/videos/motors_and_microcontrollers_101/


body:
I need a help with this question. I'm trying to make a Wheatstone Bridge with Arduino, the main idea is read the two legs of the circuit with two analog inputs of Arduino, for the while I'm analyzing the values with 4 equal resistors as the Arduino reads (0 to 1023 bits). The problem is when I change one of the resistors (Rx), the voltage on A0 (first leg C) should not be changed, but it happens.

![enter image description here][1]

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

I've read something about the analog inputs of the Arduino suffer interference, but I don't know how to avoid this.

title: Accuracy reading two analog inputs on Arduino

Answers: 0


body:
I'm trying to send data saved on a txt file to arduino over serial connection. I wrote this simple sketch

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

    void loop(){
      while (Serial.available() > 0) {
        Serial.write(Serial.read());
      }
    }

When I try to send serial data from bash by typing `cat input.txt >> /dev/cu.wchusbserial1a1340` while the Arduino's serial connection window is open. It gives an error message "resource busy: /dev/cu.wchusbserial1a1340". Then I tried `cat input.txt >> /dev/tty.wchusbserial1a1340`. Now it hangs. Bash is busy, and it is not possible close Arduino IDE or serial connection window. What is wrong here?

title: Sending data from txt file over serial connection

Answers: 2

body:
I don't know the details of why the hang is occurring.  However, the problem stems from serial ports being available to one process at a time.  When the Arduino-environment's serial-port-monitor opens a serial port, that port becomes unavailable to bash.  (To close the hung Arduino IDE process and the SPM, say `ps aux |grep arduino` and `kill` *n*, where *n* is the PID shown by the `ps` and `grep`.)

Here is a python program you can run, that sends and receives data:

    #!/usr/bin/env python
    # Send data to an Arduino and report responses.
    from time import time, sleep, asctime, localtime
    from serial import Serial
    print 'Opening serial port'
    ser = Serial('/dev/ttyACM0', 9600, timeout=3)
    sleep(1)                      # Let board initialize
    while 1:
        txt = 'It is about ' + asctime(localtime()) + ' now'
        print 'Sending  "{}"'.format(txt)
        ser.write(txt)
        s = ser.readline()          # Get result from arduino
        print 'Readback "{}" at {}'.format(s, asctime(localtime()))
        sleep(1)

Here is some sample output from it, with your sketch runing in a Mega2650.  (I'm not sure why the readback is taking so long as it apparently is.)

    Opening serial port
    Sending  "It is about Fri May  8 16:48:41 2015 now"
    Readback "It is about Fri May  8 16:48:41 2015 now" at Fri May  8 16:48:44 2015
    Sending  "It is about Fri May  8 16:48:45 2015 now"
    Readback "It is about Fri May  8 16:48:45 2015 now" at Fri May  8 16:48:48 2015
    Sending  "It is about Fri May  8 16:48:49 2015 now"
    Readback "It is about Fri May  8 16:48:49 2015 now" at Fri May  8 16:48:52 2015
    Sending  "It is about Fri May  8 16:48:53 2015 now"
    Readback "It is about Fri May  8 16:48:53 2015 now" at Fri May  8 16:48:56 2015

body:
As noted by jwpat7 the port can be accessed by one application at a time, so when the serial monitor is open no other application can access it.

The hang might happen because when first connecting to an arduino port the arduino gets reset and waits for a second or so for programming data (that's how a new sketch is updated). I don't know for sure, but this might mess up with `cat` and make it to hang up.

Best option might be to make a script like jwpat7's that would wait a second after opening the port and then send the file contents in.


body:
I'm on a project to sense any amounts of methane in the home. I have bought the popular MQ-4 methane sensor from SparkFun: https://www.sparkfun.com/products/9404

I've looked online for any sample code, but I am confused as to whether the input from the sensor is already given in parts per million, or it is just a voltage. To be specific, here is the sample code the data sheet for the sensor gives:

    int sensorValue;

    void setup()
    {
      Serial.begin(9600);      // sets the serial port to 9600
    }

    void loop()
    {
      sensorValue = analogRead(0);       // read analog input pin 0
      Serial.println(sensorValue, DEC);  // prints the value read
      delay(100);                        // wait 100ms for next reading
    }

I have also used a breakout board for these sensors: https://www.pololu.com/product/1479
The sensor is soldered on it, along with a 20K ohm load resistor, like how the spec. sheet specifies.
However, I am confused on the readings I am getting. It's always something that ranges between 259 and 261. Is this ppm of methane in my home? If it is, shouldn't the normal level be 0? I currently have no methane based heating. Or is the 259 - 261 voltage?

Thanks for any help.

title: Sensing concentration of methane with MQ-4 methane sensor?

Answers: 2

body:
Actually, you are getting raw data from the sensor. A little bit of math should be done in order to calibrate it and based on the chart in datasheet, measure the real value in PPM.

The calibration basically helps you find R0, which is an internal resistance (along with RS form a voltage divider) that could be derived by doing calibration in a clean environment. After that, you use R0 to calculate a ratio and then look at the datasheet's chart to measure whatever gas you want since there is a curve describing it.

Please refer to this [tutorial][1] for more information. I have developed a similar application using MQ-4 before.

It is related to MQ-2, you may have noticed that all theses sensors have similar features and principle applications.

  [1]: http://sandboxelectronics.com/?p=165

body:
The values you're reading relate to the voltage measured by the AD converter, that is, the voltage over the load resistor. Arduino's AD converters have 10 bit resolution and measure against a 5V reference, so you can use the following line to convert it to millivolts:

`VRL = map(sensorValue, 0, 1023, 0, 5000);`

Once you have the voltage, you can compute the resistance of the sensor using the formula

Rs=(Vc/VRL-1)×RL

with Vc the circuit voltage (5V), VRL the voltage over the load resistor, and RL the resistance of the load resistor in Ohms.

The tricky part is to convert this to a concentration in ppm CH4. The curve in the datasheet gives you a starting point, but the values it gives are not absolute, but relative to the reference of 1000 ppm. The value of that reference depends on various factors, like temperature, humidity, other gases in the environment and how long the sensor has been running (the longer, the more reliable are the results).

If you really need exact ppm values, you'll need to calibrate your setup in an environment where you can exactly control the CH4 concentration. You'll also have to measure temperature and humidity along with the sensor readings.

Otherwise you'll get only a qualitative estimate of CH4 concentration, which is actually sufficient for many use cases.


body:
Not able to upload sketches to standalone arduino on breadboard (with Atmega328 bootloaded with blink LED program). Searched on the internet but there is no solution. Help ?

error :
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00

OS: Ubuntu 14.04 LTS

title: Unable to Upload

Answers: 2

body: Make sure the board selected and port selected are correct. I face this problem many time but they disappear after I remove my other circuit connection and reconnect my arduino board to pc

body: Make sure the RX, TX pins are not connected to any other circuit when uploading sketches.


body:
I'm trying to program my ATtiny 13 - 20PU. An it seems to work, but there is no action upon the "delay" command. If on the sketch below I comment out the "High" line, my led is off all the time and whenever I have a `Pin 4 High`, it's on all the time! Basically this seems to be a frequency/fuse/bootloader problem and made me think the upload was broken.

I added a led between the tiny's pin 3 (digital pin 4) and ground with a 1k current limiting resistor. This one is for testing with the attached sketch.
I also tried [this breadboard circuit][3], which gives exactly the same results.

Upon upload to the tiny I get this:

    Sketch uses 380 bytes (37%) of program storage space. Maximum is 1,024 bytes.
    Global variables use 8 bytes of dynamic memory.

(Everybody warns about 2 errors occuring upon a proper upload - I don't get those).

My boards.txt look like this:

    menu.cpu=Processor
    menu.clock=Clock

    attiny.name=ATtiny
    attiny.bootloader.tool=arduino:avrdude
    attiny.bootloader.unlock_bits=0xff
    attiny.bootloader.lock_bits=0xff
    attiny.build.core=arduino:arduino
    attiny.build.board=attiny
    attiny.upload.tool=arduino:avrdude

    attiny.menu.cpu.attiny45=ATtiny45
    attiny.menu.cpu.attiny45.upload.maximum_size=4096
    attiny.menu.cpu.attiny45.build.mcu=attiny45
    attiny.menu.cpu.attiny45.build.variant=tiny8

    attiny.menu.cpu.attiny85=ATtiny85
    attiny.menu.cpu.attiny85.upload.maximum_size=8192
    attiny.menu.cpu.attiny85.build.mcu=attiny85
    attiny.menu.cpu.attiny85.build.variant=tiny8

    attiny.menu.cpu.attiny44=ATtiny44
    attiny.menu.cpu.attiny44.upload.maximum_size=4096
    attiny.menu.cpu.attiny44.build.mcu=attiny44
    attiny.menu.cpu.attiny44.build.variant=tiny14

    attiny.menu.cpu.attiny84=ATtiny84
    attiny.menu.cpu.attiny84.upload.maximum_size=8192
    attiny.menu.cpu.attiny84.build.mcu=attiny84
    attiny.menu.cpu.attiny84.build.variant=tiny14

    attiny.menu.clock.internal1=1 MHz (internal)
    attiny.menu.clock.internal1.bootloader.low_fuses=0x62
    attiny.menu.clock.internal1.bootloader.high_fuses=0xdf
    attiny.menu.clock.internal1.bootloader.extended_fuses=0xff
    attiny.menu.clock.internal1.build.f_cpu=1000000L

    attiny.menu.clock.internal8=8 MHz (internal)
    attiny.menu.clock.internal8.bootloader.low_fuses=0xe2
    attiny.menu.clock.internal8.bootloader.high_fuses=0xdf
    attiny.menu.clock.internal8.bootloader.extended_fuses=0xff
    attiny.menu.clock.internal8.build.f_cpu=8000000L

    attiny.menu.clock.external8=8 MHz (external)
    attiny.menu.clock.external8.bootloader.low_fuses=0xfe
    attiny.menu.clock.external8.bootloader.high_fuses=0xdf
    attiny.menu.clock.external8.bootloader.extended_fuses=0xff
    attiny.menu.clock.external8.build.f_cpu=8000000L

    attiny.menu.clock.external16=16 MHz (external)
    attiny.menu.clock.external16.bootloader.low_fuses=0xfe
    attiny.menu.clock.external16.bootloader.high_fuses=0xdf
    attiny.menu.clock.external16.bootloader.extended_fuses=0xff
    attiny.menu.clock.external16.build.f_cpu=16000000L

    attiny.menu.clock.external20=20 MHz (external)
    attiny.menu.clock.external20.bootloader.low_fuses=0xfe
    attiny.menu.clock.external20.bootloader.high_fuses=0xdf
    attiny.menu.clock.external20.bootloader.extended_fuses=0xff
    attiny.menu.clock.external20.build.f_cpu=20000000L

    #################################################
    attiny.menu.cpu.attiny13=ATtiny13
    attiny.menu.cpu.attiny13.upload.maximum_size=1024
    attiny.menu.cpu.attiny13.build.mcu=attiny13
    attiny.menu.cpu.attiny13.build.variant=core13

    attiny.menu.clock.internal96=9.6MHz (internal)
    attiny.menu.clock.internal96.bootloader.low_fuses=0x7A
    attiny.menu.clock.internal96.bootloader.high_fuses=0xff
    attiny.menu.clock.internal96.build.f_cpu=9600000L
    ################################################

    attiny.menu.clock.internal48=4.8MHz (internal)
    attiny.menu.clock.internal48.bootloader.low_fuses=0x79
    attiny.menu.clock.internal48.bootloader.high_fuses=0xff
    attiny.menu.clock.internal48.build.f_cpu=4800000L
    ################################################

And I choose the settings: Board ATtiny, Processor ATtiny13, Clock 9.6 MHz (internal), Port Arduino Uno (same as when I upload the ISP sketch), Programmer Arduino as ISP. I upload by clicking "Upload using Programmer".

Arduino Software is 1.6.4, the programmer Arduino is an Uno SMD edition.
I used this [programmer][1] and this [tutorial][2] for smeezkitty core13.

I'm trying to upload this sketch:

    // Blink sketch to test ATtiny Chips

    //       ATMEL ATTINY13 / ARDUINO
    //
    //                 +-\/-+
    // ADC0 (D 5) PB5 1|*   |8 Vcc
    // ADC3 (D 3) PB3 2|    |7 PB2 (D 2) ADC1
    // ADC2 (D 4) PB4 3|    |6 PB1 (D 1) PWM1
    //            GND 4|    |5 PB0 (D 0) PWM0
    //                 +----+

    const int LED_PIN = 4; // digital pin
    const int DELAY_TIME = 1000; // time between blinks [ms]

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

    void loop() {
      digitalWrite(LED_PIN, LOW);
      delay(DELAY_TIME);
      digitalWrite(LED_PIN, HIGH);
      delay(DELAY_TIME);
    }

Trying to burn a bootloader with the same settings as uploading to the tiny and then tools -> burn bootloader, get's me the error:

    "efuse" memory type not defined for part "ATtiny13"
    Error while burning bootloader.

Skimming through the data sheet I noticed that the tiny13 - 20PU (the 20) stand for 20 MHz,... theoretically one should be able to downclock them to the ordinary 10 MHz, but maybe this is my problem?

  [1]: https://arduinodiy.wordpress.com/2015/03/31/1256/#comment-907
  [2]: https://arduinodiy.wordpress.com/2015/04/26/installing-attiny13-core-files-in-arduino-ide-1-6-x-and-1-7-x/
  [3]: http://highlowtech.org/?p=1706

title: Program ATtiny13 - 20PU

Answers: 2

body:
There was some mistakes in the boards.txt it seems. After finding a very detailed and extensive boards file [here](http://forum.arduino.cc/index.php?topic=89781.msg2235877#msg2235877), I modified it to have neat and tidy categories and is easier to use to become a working boards.txt. I had to burn the bootloader once to set the fuses right. After that everything works like a charm for 3 ATtiny13! No warnings or errors. This is used with Arduino 1.6.4. The folder tree is `~Arduino/hardware/attiny/avr/cores/core13` and `~Arduino/hardware/attiny/avr/boards.txt`

    # boards.txt for Arduino 1.6.4

    menu.flag=GCC Flags
    menu.cpu=Processor
    menu.clock=Clock

    attiny13.name=ATtiny13
    attiny13.upload.tool=arduino:avrdude
    attiny13.upload.using=arduino:usbtiny

    attiny13.bootloader.tool=arduino:avrdude

    attiny13.menu.cpu.attiny13=ATtiny13
    attiny13.menu.cpu.attiny13.upload.maximum_size=1024
    attiny13.menu.cpu.attiny13.upload.maximum_data_size=64
    attiny13.menu.cpu.attiny13.build.mcu=attiny13
    attiny13.menu.cpu.attiny13.build.core=core13
    # attiny13.menu.cpu.attiny13.build.variant=core13

    #################################################
    ############## clock speeds #####################
    #################################################

    #### 9.6 MHz
    ############
    attiny13.menu.clock.t13_9M6=9.6MHz (internal clock, Preserve EEPROM, BOD disable)
    attiny13.menu.clock.t13_9M6.bootloader.low_fuses=0x3A
    attiny13.menu.clock.t13_9M6.bootloader.high_fuses=0xFF
    attiny13.menu.clock.t13_9M6.upload.speed=57600L
    attiny13.menu.clock.t13_9M6.build.f_cpu=9600000L

    #### 9.6 MHz - 2.7V
    attiny13.menu.clock.t13_9M6_bod=9.6MHz (internal clock, Preserve EEPROM, BOD - 2.7V)
    attiny13.menu.clock.t13_9M6_bod.bootloader.low_fuses=0x32
    attiny13.menu.clock.t13_9M6_bod.bootloader.high_fuses=0xFB
    attiny13.menu.clock.t13_9M6_bod.upload.speed=57600L
    attiny13.menu.clock.t13_9M6_bod.build.f_cpu=9600000L

    #### 4.8 MHz - 2.7V
    attiny13.menu.clock.t13_4M8_bod=4.8 MHz (int 4.8 MHz clock, Preserve_EEPROM, BOD - 2.7V)
    attiny13.menu.clock.t13_4M8_bod.bootloader.low_fuses=0x31
    attiny13.menu.clock.t13_4M8_bod.bootloader.high_fuses=0xFB
    attiny13.menu.clock.t13_4M8_bod.upload.speed=57600L
    attiny13.menu.clock.t13_4M8_bod.build.f_cpu=4800000L

    #### 1.2 MHz
    attiny13.menu.clock.t13_1M2=1.2 MHz (int 9.6 MHz divided by 8,Preserve_EEPROM, BOD - 2.7V)
    attiny13.menu.clock.t13_1M2.bootloader.low_fuses=0x2A
    attiny13.menu.clock.t13_1M2.bootloader.high_fuses=0xFB
    attiny13.menu.clock.t13_1M2.upload.speed=9600L
    attiny13.menu.clock.t13_1M2.build.f_cpu=1200000L

    #### 600 kHz
    attiny13.menu.clock.t13_0M6=600 kHz (int 4.8 MHz divided by 8, Preserve_EEPROM, BOD disable)
    attiny13.menu.clock.t13_0M6.bootloader.low_fuses=0x29
    attiny13.menu.clock.t13_0M6.bootloader.high_fuses=0xFF
    attiny13.menu.clock.t13_0M6.upload.speed=9600L
    attiny13.menu.clock.t13_0M6.build.f_cpu=600000L

    ## 128 kHz
    attiny13.menu.clock.t13_128k=128 KHz (internal watchdog oscillator)
    attiny13.menu.clock.t13_128k.bootloader.low_fuses=0x7B
    attiny13.menu.clock.t13_128k.bootloader.high_fuses=0xFF
    attiny13.menu.clock.t13_128k.upload.speed=250
    attiny13.menu.clock.t13_128k.build.f_cpu=128000L

    ## 16 kHz
    attiny13.menu.clock.t13_16k=16 KHz (internal watchdog oscillator, Preserve_EEPROM, BOD disable)
    attiny13.menu.clock.t13_16k.bootloader.low_fuses=0x2B
    attiny13.menu.clock.t13_16k.bootloader.high_fuses=0xFF
    attiny13.menu.clock.t13_16k.upload.speed=250
    attiny13.menu.clock.t13_16k.build.f_cpu=16000L

    ##-----------------------------------
    ##--------- compiler flags ----------
    ##-----------------------------------

    attiny13.menu.flag.Os=Default
    attiny13.menu.flag.Os.compiler.c.extra_flags=
    attiny13.menu.flag.Os.compiler.c.elf.extra_flags=
    attiny13.menu.flag.Os.compiler.cpp.extra_flags=

    attiny13.menu.flag.Os_flto=Default -flto
    attiny13.menu.flag.Os_flto.compiler.c.extra_flags=-Wextra -flto
    attiny13.menu.flag.Os_flto.compiler.c.elf.extra_flags=-w -flto
    attiny13.menu.flag.Os_flto.compiler.cpp.extra_flags=-Wextra -flto

    attiny13.menu.flag.O1=-O1
    attiny13.menu.flag.O1.compiler.c.extra_flags=-O1
    attiny13.menu.flag.O1.compiler.c.elf.extra_flags=-O1
    attiny13.menu.flag.O1.compiler.cpp.extra_flags=-O1

    attiny13.menu.flag.O1_flto=-O1 -flto
    attiny13.menu.flag.O1_flto.compiler.c.extra_flags=-O1 -Wextra -flto
    attiny13.menu.flag.O1_flto.compiler.c.elf.extra_flags=-O1 -w -flto
    attiny13.menu.flag.O1_flto.compiler.cpp.extra_flags=-O1 -Wextra -flto

    attiny13.menu.flag.O3=-O3
    attiny13.menu.flag.O3.compiler.c.extra_flags=-O3
    attiny13.menu.flag.O3.compiler.c.elf.extra_flags=-O3
    attiny13.menu.flag.O3.compiler.cpp.extra_flags=-O3

    attiny13.menu.flag.O3_flto=-O3 -flto
    attiny13.menu.flag.O3_flto.compiler.c.extra_flags=-O3 -Wextra -flto
    attiny13.menu.flag.O3_flto.compiler.c.elf.extra_flags=-O3 -w -flto
    attiny13.menu.flag.O3_flto.compiler.cpp.extra_flags=-O3 -Wextra -flto

body:
The "efuse error"  on burning the bootloader is described in the article you refer to and a solution is given there as well.
It occurs when the attiny13 is defined in the same group as the attiny25/45/85 as the former has no efuse and the latter do.

Giving the attiny13 its own menu entry in the IDE -as described in that article- should solve that.


body:
I need to display some dynamic Chinese characters to 12864 using Arduino. What to show is transported from my web server. The character is stored as a 16x16 dot matrix, needing 16*16/8=32 byte. And I need to show some sentences, which contains more than 100 Chinese characters.

The problem is that I can't storage all the dot matrix data in Arduino because it has too small memory.

* If I get the dot matrix data from web server, I need to have 100*32B memory, but SPAM with EEPROM have only 3k. So that failed.
* If I save the dot matrix "library" in the Flash memory, I need 3500*32B (There are 3500 Chinese frequent-used characters), but there is only 32K Flash. Saving the "library" means that I should storage the dot matrix data of all the 3500 chars in Flash, then the server only need to send the Unicode of characters, and I can get the matrix of the char.

Any help is appreciated!

title: How to increase Arduino's memory to save Dot Matrix Library?

Answers: 2

body:
1. Use a different [Arduino](http://www.arduino.cc/en/Main/Products) or [Arduino-clone](http://playground.arduino.cc/Main/SimilarBoards#goArdComp) with [more flash memory](http://www.arduino.cc/en/Tutorial/Memory)

2. Store the character bitmaps in external EEPROM ([example](http://www.hobbytronics.co.uk/arduino-external-eeprom))

body:
The basic EEPROM write, each 1 byte, as is mentioned in the above answer.

http://www.hobbytronics.co.uk/arduino-external-eeprom

The PAGE WRITE which is suitable for this situation. One can easily read 32 bytes for a dot matrix.

http://www.hobbytronics.co.uk/eeprom-page-write


body:
A Pro Mini needs to be placed in a 100mmx50mmx25mm, no holes but not air tight ABS plastic enclosure, with a 12v power supply connected to the raw input. It will be consuming max 40mA, ambient temperature 30-32C, and needs to be run 24/7. Upon prototyping in open air, I tried to touch the regulator MIC5205, after 30 seconds upon powering on with my bare fingers and it was too hot to touch. The rest of the components were cool to touch. I would use a buck converter to step down to 5v, however there isn't space for it in the current setup.

I used to run a Mega 24/7 on 12v, consuming much more current about 700mA, the onboard regulator malfunctioned after 1 year of use, which I believe was due to the excessive heat, as the PCB around the regulator turned a little brownish.

Despite being hot to touch, I understand that electronics run in heat all the time like computers, routers, etc for 24/7. Therefore, I would like to know if 12vx0.04A=0.48w will be too much heat/feasible to run in the above mentioned setup, without damaging the regulator in the long run?

title: Running Pro Mini Continuous on 12v w/o Damaging Regulator

Answers: 1

body:
**Summary:**

**Simple, effective, low cost solution - choose any 3:**
A series resistor in the regulator input, of properly designed resistance and wattage will greatly reduce regulator temperature and increase overall reliability. Reason and design details given below.

**Detail:**

Assuming a 5V processor dissiaption in the regulator is
(Vsupply - Vregulator_out) x Current
= (12-5)x 0.040 = 280 mW - usefully less than the 480 mW if you are dissipating all the power in the regulator.
For a 3V3 processor dissipation is (12-3.3)* 0.040 ~= 350 mW

"Too hot to touch" is a minimum of 55C and probably hotter - say 70C for now.
At 30C ambient delta T = (70-30) = 40 C.
Thermal resistanc = dT/Watts =40/0.280 = 140 C/W or 114 C/W at 3V3.

Both of those thermal resistances are very high. You do not describe what heatsinking is on the regulator but that suggests PCB copper only and not much of it. Even adding a very rudimentary heat sink should help immensely. If there is no obvious way to add a formal heat sink then adding a 'flag' of copper or brass by soldering should be doable.

Using Mark William's 220C/Watt figure (see datasheet for conditions).
Say 300 mW (see above).
Delta t = 220 C/W  x 0.3 W = 66 C rise.
Ambient is 30-32 so allow 35 for very minor safety factor.
66 C rise + 35 C ~= 101C - water boils.
And temperature inbox will rise mildly from energy dissipated so hotter again.
BUIT a series resistor inside the box or external  will make an immense difference.

**An easy and effective solution:**

The regulator needs some "headroom" - some voltage above the Vout value to allow some dropacross the internal switch. Check the data sheet, but a modern LDO probably allows as little as 1V headroom. So, for 5V out you need 6V in. The extra 6v from 12V to 6V is not "needed" by the regulator. So, it can be dissipated in a low cost high reliability resistor.
Determine

 - Vsupply_minimum - the absolute lowest value supply will assume.

 - Vreg_in_minimum  I'll use 6V to start.

 - I_load_maximum - you said 40 ma. This must be abs_max or if of very short duration must be able to be supported by capacitors.

Then

Rmax = V/I = (V_supply_min-Vregin_nax) / Imax
= (12 - 6 )/.040 = 150 Ohm.
This is the absolute maximum resistor that meets the specification. A slightly smaller value will be safer. Say 120 R in this case.
Then
Pmax in R = I^2R = .04^2 x 120 = 192 mW.
A 500 mW resistor would be "safe enough" and a 1 watt one very safe.
Pregulator max = (6-5) x 0.040 = 40 mW, 14% of the 280 mW initially.
A  W resistor with adequate cooling will be very safe. Safest is probably a purpose built air cooled wire wound.

Note that the dissipated energy will raise internal ambient. A resistor is still an effective solution.

Place a suitable decoupling capacitor at the regulator input. Even if not normally used here it is needed due to the series input resistor raising the supply resistance.

._______________________________________

**Temperature rise inside box due to heat dissipation.**

**Summary:** Using pessimistic assumptions for box thickness, available area and power dissipation an internal temperature rise of under 15 degrees C can be expected. As the regulator is now dissipating under 15% of the original dissipation due to the series resistor it will have a far longer operating lifetime.

Notes:

Temperature rise (assuming no air transfer occurs) is limited by heat transfer through the plastic. This is controlled by the thermal conductivity of th e plastic, its thickness and its area.  Obviously:
 - Thicker plastic leads to higher temperature rise.

 - More surface area leads to lower temperature rise.

 - Higher thermal conductivity of the plastic leads to lower temperature rise

So given Thermal conductivity = Ktc

 - **Delta T = Watts x thickness / (Ktc x area)**

So Ktc = Watts x thickness /(Delta_Tx area)
So units of Ktc must be Watts/metre/degree_C
Which is indeed how Ktc is usually expressed.

This table of [**Thermal properties of plastic materials**](http://www.professionalplastics.com/professionalplastics/ThermalPropertiesofPlasticMaterials.pdf) lists Ktc for ABS as 0.17 W/m/K
This means that 170 mW will cause a 1 degree K (or C) rise when plastic ratio of thickness to area is 1.

Assume thickness of box = 5mm = much higher than is likely.
Box area for a box L x W x D = 2 x (LW + WD + DL)
Here  = L D W = 100mm x  50mm  25 mm or 0.1 x 0.05 x 0.025m
Area = 0.0175 m^2.
Use a smaller more pessimistic area of 0.01 m^2
Use a pessimistic heat dissipation of 0.5 Watts

Using the formula - **Delta T = Watts x thickness / (Ktc x area)**  from above

**Temperature rise = 0.5 x 0.05 / (0.17 x 0.01) ~= 15 degrees C (or K)**
This is based on a thicker than likely box, smaller than actual area, and higher than expected energy dissipation. A 15C rise is bearable and actual is lower, and as the regulator now dissipates under 20% of original it will survive very well.


body:
When I compile my code, the Arduino IDE returns the binary sketch size in byte.

Is there a good way to find out (approximately) what function or what part of my code takes up how much memory in flash, so that I get a feeling what feature takes most of precious flash memory or where I may be wasting flash and should start optimizing?

title: Overview of compiled code size

Answers: 1

body:
One approach is to look at the assembly listing of the program.

1. After compiling the program (via the Verify or Download button) locate the directory where the .cpp, .hex, and .elf files for the program have been stored.  (If you have trouble finding them, briefly turn on verbose compile options in the arduino IDE and look at the directory names in the output.)

2. In that directory, run `avr-objdump -S ` *fn.cpp.elf* `> listing.txt` where *fn.cpp.elf* is the name of your sketch with `.ino` taken off and `.cpp.elf` added on at the end.  For example, with sketch `serialecho.ino`:

    avr-objdump -S serialecho.cpp.elf > listing.txt

3. View the `listing.txt` file, and subtract each function's starting address from its ending address, using hex arithmetic.  For example, with `setup` code

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

in the listing we will see

    00000144 <setup>:
    ...(6 lines snipped)...
     144:   26 e0           ldi     r18, 0x06       ; 6
     146:   40 e8           ldi     r20, 0x80       ; 128
     148:   55 e2           ldi     r21, 0x25       ; 37
     14a:   60 e0           ldi     r22, 0x00       ; 0
     14c:   70 e0           ldi     r23, 0x00       ; 0
     14e:   80 e1           ldi     r24, 0x10       ; 16
     150:   92 e0           ldi     r25, 0x02       ; 2
     152:   db c1           rjmp    .+950           ; 0x50a <_ZN14HardwareSerial5beginEmh>

    00000154 <loop>:

The calculation 0x154–0x144 = 0x10 shows this portion of `setup` is 16 bytes long.

These examples were generated on a linux system.  I think the approach is the same on a MSWindows system except you may need to say `avr-objdump.exe` instead of `avr-objdump`, and may need to specify its path.  See, eg, the [Assemler results, where?](http://forum.arduino.cc/index.php/topic,3537.0.html) thread at forum.arduino.cc.


body:
I currently connected 5 sensor via a multiplexer (I must connect them to a multiplexer because they are I2C devices but they cannot been allocate more then 2 addresses so I use a multiplexer to solve the addressing problem).

However the sample rate is a shame , it is about 6.5Hz . I wish I could improve the sample rate by using some tricks.
In my loop() function, multiplexer will loop through channel 0-4 , and read each of these channel's sensor value and print it by using Serial.print()

Is there any tricks I could use to improve my sampling rate faster ? Thanks...

Here is my multiplexer class :

    class MUX {
    public:
    //mux control pins:
    int s0 = 22;
    int s1 = 24;
    int s2 = 26;
    int s3 = 28;

    //SIG pin (not necessary WHEN sig is connect to 5V)
    //int SIG_pin = 0;

    //array to store channel :: muxChannel[channel numbers ][4 digit channel representation]
    int muxChannel[16][4] = {
      {0, 0, 0, 0}, //channel 0
      {1, 0, 0, 0}, //channel 1
      {0, 1, 0, 0}, //channel 2
      {1, 1, 0, 0}, //channel 3
      {0, 0, 1, 0}, //channel 4
      {1, 0, 1, 0}, //channel 5
      {0, 1, 1, 0}, //channel 6
      {1, 1, 1, 0}, //channel 7
      {0, 0, 0, 1}, //channel 8
      {1, 0, 0, 1}, //channel 9
      {0, 1, 0, 1}, //channel 10
      {1, 1, 0, 1}, //channel 11
      {0, 0, 1, 1}, //channel 12
      {1, 0, 1, 1}, //channel 13
      {0, 1, 1, 1}, //channel 14
      {1, 1, 1, 1} //channel 15
    };

    void setupMux() {
      pinMode(s0, OUTPUT);
      pinMode(s1, OUTPUT);
      pinMode(s2, OUTPUT);
      pinMode(s3, OUTPUT);

      digitalWrite(s0, LOW);
      digitalWrite(s1, LOW);
      digitalWrite(s2, LOW);
      digitalWrite(s3, LOW);
      Serial.println(F("Multiplexer initialized"));
    }

    void selectChannel(int channel) {
      int controlPin[] = {s0, s1, s2, s3};
      for (int i = 0; i < 4; i++) {
        digitalWrite(controlPin[i], muxChannel[channel][i]);
      }
    }

title: Improve sampling speed while using a multiplexer

Answers: 2

body:
It's hard to offer much more than speculation without knowing more about the sensors and your current code, but here is one possibility:

If the bulk of your loop time is the sum of the conversion times, is it possible to cycle through the sensors twice, once to start each conversion (so they will convert nearly simultaneously), wait one conversion-time (or for the first sensor to complete), then cycle through them again to read back each converted value?

    for each sensor,
      setup mux;
      send start conversion command;
    end

    for each sensor,
      setup mux;
      while conversion not done,
        ;  // wait
      read and store value;
    end

For 16 sensors and assuming the conversion time the majority of the time spent, that could speed your sample rate to ~100Hz. Expect maybe half of that, since mux-setup and communication times are probably not negligible.

body:
The technique suggested by @JRobert (starting all the conversions in one loop, then running another loop to wait for completions and read results) looks reasonable.

Here are a couple of ways to shorten the code shown in the question:

First, instead of four `int` declarations to set the value of `s0 ... s3`, use an `enum`.  An `enum` is used to declare integer constants.

    enum { s0 = 22, s1 = 24, s2 = 26, s3 = 28};

Second, don't bother with the lengthy, tedious, and unnecessary `muxChannel` array.  Delete the declaration of `muxChannel` and replace `selectChannel` with the following:

    void selectChannel(int channel) {
      int controlPin[] = {s0, s1, s2, s3};
      for (int i = 0; i < 4; i++) {
        digitalWrite(controlPin[i], channel & 1);
        channel /= 2;
      }
    }

The expression `channel & 1` picks off the least-significant-bit of `channel`.  The statement `channel /= 2;` divides `channel` by 2, which moves the next bit of `channel` into place for output.  You could instead say `channel >>= 1;` or `channel = channel/2;`, etc. if you prefer.

You might also look closely at your sensor boards to see if there is any way to add jumpers to get another bit or two of I2C device addressing, allowing you to avoid multiplexing.


body:
I need to pass a 16-bit long address (for an external EEPROM) to a function (`twi_writeTo`) in a buffer.
I am currently doing this

    byte buffer[2];
    buffer[0] = (byte)(eeaddress >> 8);
    buffer[1] = (byte)(eeaddress & 0xFF);
where `eeaddress` is an `unsigned int` with the address.

I then do

    int8_t ret = twi_writeTo(eeprom_i2c_addr, buffer, 2, 1);

Before I tried

    int8_t ret = twi_writeTo(eeprom_i2c_addr, (uint8_t*)&eeaddress, 2, 1);

but that returns garbage. Probably the byte order is swapped. Is that the case?
And if so, is there a better way than copying the two bytes to a buffer?

title: Big endian or little endian?

Answers: 1

body:
If it's the byte order that causes a problem that's likely compiler specific and I don't think one can change it. Even if it were possible, changing the global endianness might break libraries that depend on it, so you likely can't escape using a function to swap the variable.

If you know you only need one value at a time you could write something like the following code, with a global buffer (untested but in principle should work (and I know global variables are evil, but should work for an Arduino project)):

    byte buf[2];

    byte* reverse(int val) {
        buf[0] = (byte)(val >> 8);
        but[1] = (byte)val;
        return buf;
    }

So you could use it like:

    int8_t ret = twi_writeTo(eeprom_i2c_addr, reverse(eeaddress), 2, 1);


body:
I am looking for (reasonably easy to use and well tested) alternatives to the `Wire` library. `Wire` works very well, but: I only need the Arduino to act as I2C master and the `Wire` library seems to be a real waste of resources:

My goal is to send out data en bloc (e.g. 32 or 64 bytes). This data is already sitting in an array in SRAM. Now when you use the `Wire` library, you call the `TwoWire::write` function which copies your data into a 2nd buffer. Afterwards, `Wire` makes use of the `TWI` library where `twi_writeTo` copies the data again into a 3rd buffer. That's a bit clunky, isn't it?

I have seen the [DSSCircuits / I2C-Master-Library][1] but I am not sure how mature it is because there hasn't been any commit after the initial commit which is 3 years old now.

  [1]: https://github.com/DSSCircuits/I2C-Master-Library

title: Alternatives to Wire library for I2C

Answers: 5

body:
I don't see any objection to using [DSS Circuits I2C Master Library](http://dsscircuits.com/articles/arduino-i2c-master-library).

It may not have been updated for a couple of years, but if it works it doesn't need to be. It's not as if libraries for micro-controllers have to support new printer drivers, video drivers, etc.

If it works, it works.

The chip hasn't changed, and the only real reason for updates these days is if the IDE changes (or the compiler changes) in such a way that it introduces compile errors. Such things have happened fairly recently with things like PROGMEM having tighter rules, for example.

body:
[Cosa][1] [TWI][2] class is a very different approach to I2C device driver support. It does not use any extra SRAM for buffers at all. If a device driver is non-blocking it must handle the necessary buffering. Also the Cosa TWI class supports typical interaction with I2C devices such as master/slave, "write register-read data"-patterns, and transactions when using multi-threading.

A software and hardware [Arduino-TWI][3] library is available. It uses the Arduino-GPIO library and can be used on AVR and SAM based boards.

Some examples: [TWI Scanner][4], [DS3231 Real-Time Clock/Calender][5], [I2C LCD Adapter with PCF8574][6].

  [1]: https://github.com/mikaelpatel/Cosa
  [2]: https://github.com/mikaelpatel/Cosa/blob/master/cores/cosa/Cosa/TWI.hh
  [3]: https://github.com/mikaelpatel/Arduino-TWI
  [4]: https://github.com/mikaelpatel/Cosa/blob/master/examples/Tools/CosaTWIscanner/CosaTWIscanner.ino
  [5]: https://github.com/mikaelpatel/Cosa/blob/master/libraries/DS3231/DS3231.hh
  [6]: https://github.com/mikaelpatel/Cosa/blob/master/libraries/DFRobot_IIC_LCD_Module/DFRobot_IIC_LCD_Module.hh

body:
Also [Procyon AVR library][1] worth be checking. It is a bit old now but very professional and kinda minimalistic. Not much dependencies, should be fine to use just I2C module only. There is hardly anything new in AVR I2C part since.

  [1]: http://www.procyonengineering.com/embedded/avr/avrlib/

body:
I made 2 libs myself for easier use and consistant calls:

one for AVR targets:
[cI2C](https://github.com/SMFSW/cI2C)

another using the same functions for all other targets (which basically is a wrapper for Wire library):
[WireWrapper](https://github.com/SMFSW/WireWrapper)

Both are available within the IDE library manager.
They both work as master without using interrupt and are tested on different targets with different slaves:
- UNO, Nano for cI2C
- Zero, Due & ESP8266 for WireWrapper

body:
You can use completely different approach to the top question. Asking for alternatives you have given reason to this: getting rid of unused code in the binary. You can achieve removal of unused code without actually using alternative library. Please keep in mind, that you can instruct the compiler and linker to exclude unused code from the compiled binary. Just use compilation flags:

    CFLAGS += -Wl,-static
    CFLAGS += -ffunction-sections
    CFLAGS += -Wl,--gc-sections

Rach function will be in its own section.

    LDFLAGS += -Wl,-gc-sections

This tells GCC to send the -gc-sections flag to the linker which will remove
unused sections. And voilla! Unused sections are removed.


body:
I am looking for a way to listen for received text messages on multiple numbers. When I came across the Arduino and its shields, I thought to myself this might be the perfect way to do just that.

One of the modules / shields I found on the internet by watching a youtube video is the TC 35 GSM.

I have been reading multiple questions here regarding the "stacking" of shields, and the usual reply is "check what pins / if they are using the same pins". Though these questions were not GSM module specific, and did not include stacking the **same** shields.

So I am very curious if this is possible. Let's say I want to listen to 10 SIM cards at once for received messages, will this be possible by stacking the modules on one Arduino?

Thanks!

title: Multiple GSM shields on one Arduino

Answers: 3

body:
The [data sheet for the Siemens TC35](http://www.robotshop.com/media/files/pdf/datasheet-gsm-tc35.pdf) says *"The  data  interface  is  implemented  as  a  serial  asynchronous  transmitter  and  receiver conforming  to  ITU-T  RS-232  Interchange  Circuits  DCE.  It  operates  at  CMOS  level  (2.65V).
All RS-232 signals on the ZIF connector are low active."*

this is actually a low-voltage  equivalent of "RS232" serial. Real RS232 uses -12V and +12V signalling for binary 0 and 1 but most modern devices work with logic levels, often inverted (e.g. 0V and ~3.3V).

Most Arduinos support in hardware only a single logic-level serial interface. A few Arduinos, like the Arduino Mega, will support up to four logic-level RS232 interfaces.

Using a software library, you can emulate a serial port over the digital IO pins but the Arduino will quickly run out of processing power if you try to emulate several RS232 interfaces.

> **will this be possible by stacking the modules on one arduino?**

Almost certainly not. I doubt the daughterboard ("shield") designers made provision for that. At the least you'd have to re-route the serial interface to nonstandard pins and check that the power requirements don't exceed what the Arduino can supply.

If you can find a module that communicates over I2C or SPI there might be a better chance of getting it to work.

body:
Not directly stacking, no. You could do a dirty trick where you bend the serial pins out sideways, letting the stack handle all the power and ground and wakeup pins and stuff. Then handle the serial communications with each module separately.

The Uno and similar only have a single UART (serial port) each, but you can emulate more with "software serial", aka "bit-bang" techniques. These are full of caveats and I wouldn't wish them on a newbie.

The Mega2560 has four UARTs, so you're getting closer. You'd need to use wires coming off those sideways-bent pins to bring the signals down to the different tx/rx pins per UART, but I could see it working.

You can also add UARTs over SPI/I2C, but that's getting into a good bit of program complexity. Look at the SC16IS750 or the MAX3100 for starters.

(There's also a horrible, horrible hack emerging in my mind: Connect a single transmit line to a demux chip, so you can pick a single TC35 to talk to at any given moment. Bus all the receive lines together with resistors/diodes. Hope you never end up in a situation where two are talking at once.)

body:
The short answer is, no, you can't just stack them, but yes, it is possible (though not trivial) to connect ten or more of these to a single Arduino board and have it monitor all of them.

Note that the following explanation is simplified, possibly over-simplified, in the interests of brevity and giving you a general idea of what you're in for if you try this. Many of the details (as I mention below) could easily be one or several questions of their own.

You didn't give the [datasheet](https://en.wikipedia.org/wiki/Datasheet) for the board you're considering, so I'll work from the description of a similar board (though not an Arduino shield) using the same chip, the [Cytron Technologies TC35 GSM Development Board](https://docs.google.com/document/d/1Nmkcos20_gqYwU-mR7i0QlRpGSKiNO6yEP1d-Kf2b2o/edit).

Arduino shields connect various pins of their chips to pins on the Arduino board. In many (perhaps most) cases you can't have two different devices connected to the same Arduino pin, so if you were just going to plop another board on it would have to have special support for changing the pins it's using (often via [jumpers](https://en.wikipedia.org/wiki/Jumper_(computing))) or being able to have several boards communicating on the same pins. The GSM chip you're considering uses two dedicated pins for [serial communication](https://en.wikipedia.org/wiki/Serial_communication) transmit and receive; these are the pins you'll need to rewire if you're going to use multiple boards on a single Arduino.

What kind of rewiring you'll need to do depends on how many you really want. The Arduino Uno has 14 digital I/O pins, two of which are usually used for the USB serial interface to the computer, giving you six devices if you dedicate a pair of pins to each device. Since the communication rate with the boards is quite slow (9600 [bps](https://en.wikipedia.org/wiki/Data_rate_units), see below) you could multiplex many of these on one pair of Arduino pins via a number of different techniques (such as using shift registers); this alone is complex enough that a different question could be devoted just to considering the possible choices, with further questions on the details of implementing each choice. You should consider, if you're interfacing with a PC, using multiple Arduino microcontrollers each with only one or a few GSM chips talking to them, talking to a PC via USB, and doing further processing on the PC.

If you're using a lot of boards you'll need to make sure you can supply enough power to them; you may need to use a power source outside the Arduino board itself. An Arduino powered from its USB interface can pull no more than 500 milliamps (because that's the USB limit). If you're using a separate power supply and the Arduino's on-board regulator, the limitation will be based on the electrical and thermal limitations of that regulator; [this blog post](http://www.electricrcaircraftguy.com/2014/02/arduino-power-current-and-voltage.html) is one detailed discussion of that.

There's also the issue of level shifting; Arduino boards usually do digital I/O at 5 volts or 3.3 V; this chip looks like it talks at 2.65 V and you or the board you're using will need to handle that. If the board you're using doesn't do appropriate level conversion there are other questions (such as [this](https://arduino.stackexchange.com/questions/17734/can-i-safely-integrate-3-3v-sensor-with-5v-arduino-uno-how/17739#17739)) that discuss the details of particular level-conversion solutions.

Once you have pins connected to the devices you'll need to talk to them; this involves the lower level "framing" parts of the serial protocol and the higher-level command set.

For framing the GSM chip appears to use the [low-speed serial protocol framing](https://en.wikipedia.org/wiki/Serial_port#Settings) that's standard in the computer world; aside from the voltage level difference it's the same as used in RS-232 communications between a computer and a modem or other "serial" device. The setting from the data sheet I used is "9600bps, 8-1-N, No Flow Control" which is slow enough that the microcontroller itself can easily communicate with quite a number of these without any extra hardware using [bit banging](https://en.wikipedia.org/wiki/Bit_banging). A 16 MHz Arduino executes something approaching 16 million instructions per second (most instructions are one clock cycle), giving you over 1500 instructions per bit-time to read a bit from every attached device, do the processing to turn the bits into bytes, and process the resulting messages. If you're careful with your programming, and depending on what you're doing, it shouldn't be too hard to deal with even up to a couple of dozen GSM chips, though this is almost certainly not a trivial programming job that you're going to do with standard Arduino libraries.

The higher level command set is also pretty much the same as old-fashioned computer-modem comunication; the GSM chip (and thus pretty much any board that uses it) talks standard PC-style serial protocol at 9600 bps using the [AT command](https://en.wikipedia.org/w/index.php?title=AT_Commands) set. You'll see messages such as

    +CMGR: "REC READ","+60125651453",,"12/07/31,10:0702+32"
    Hello

when you receive an SMS and similar ones when you send an SMS.


body:
I'm trying to write a faster `shiftOut` function, which does not use the slow `digitalWrite`. In my code I have the original `shiftOut`, the new shiftOutFast, and the same as shiftOutFast, but inline. The three blocks are separated by delays to tell them apart on my scope. Here's the code:

    #define CLR(x,y) (x &= (~(1 << y)) )
    #define SET(x,y) (x |= (1 << y) )

    void shiftOutFast(uint8_t dataPort, uint8_t dataBit, uint8_t clkPort,
                      uint8_t clkBit, uint8_t bitOrder, uint8_t val) {
      for (uint8_t i = 0; i < 8; i++)  {
        if (bitOrder == LSBFIRST) {
          if (val & 0x01) {
            SET(dataPort, dataBit);
          } else {
            CLR(dataPort, dataBit);
          }
          val >>= 1;
        } else {
          if (val & 0x80) {
            SET(dataPort, dataBit);
          } else {
            CLR(dataPort, dataBit);
          }
          val <<= 1;
        }

        CLR(clkPort, clkBit);
        SET(clkPort, clkBit);
      }
    }

    #define dataPin 4
    #define clockPin 5
    #define dataPort PORTD
    #define dataBit PORTD4
    #define clockPort PORTD
    #define clockBit PORTD5

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

    void loop() {
      shiftOut(dataPin, clockPin, LSBFIRST, 0x55);
      delay(1);

      shiftOutFast(dataPort, dataBit, clockPort, clockBit, LSBFIRST, 0x5C);
      delay(1);

      bool bitOrder = LSBFIRST;
      uint8_t val = 0x5C;

      for (uint8_t i = 0; i < 8; i++)  {
        if (bitOrder == LSBFIRST) {
          if (val & 0x01) {
            SET(dataPort, dataBit);
          } else {
            CLR(dataPort, dataBit);
          }
          val >>= 1;
        } else {
          if (val & 0x80) {
            SET(dataPort, dataBit);
          } else {
            CLR(dataPort, dataBit);
          }
          val <<= 1;
        }

        CLR(clockPort, clockBit);
        SET(clockPort, clockBit);
      }
      delay(1);
    }

The problem is that calling `shiftOutFast` doesn't do zilch. Absolutely nothing. It doesn't seem to be the logic, because when I do the same inline it works. Any ideas?

title: Why doesn't my code work in a function, yet works inline?

Answers: 2

body: You should declare `volatile` the port parameters of your function. Otherwise, to the compiler, their write accesses seem useless, and they get optimized out.

body:
The problem is that you are passing the value of the ports to the function, not the address of the ports.

You need to either pass "by reference" or as a pointer, so that modifying the port variable modifies the *actual* port variable not the copy of the value that you pass.

The simplest way is to modify your function to be:

    void shiftOutFast(volatile uint8_t &dataPort, uint8_t dataBit,
                      volatile uint8_t &clkPort, uint8_t clkBit,
                      uint8_t bitOrder, uint8_t val) {
    ....
    }

That way, instead of passing whatever is in the port at the time to the function (pass by value) it instead creates a new variable which is located at the same address as the variable that you are passing (pass by reference) so modifications of one variable modifies the other.

Note that only the "port" variables need to be passed by reference, all the others remain as pass by value.  Also they should be, as Edgar says, flagged as *volatile*.


body:
Is it possible to send OTA updates to Arduino via nRF24L01+ module?

Here are my findings:

[Here](http://www.instructables.com/id/Wireless-upload-program-to-Arduino-without-USB-cab/) is an instructable explaining how to program Arduino wirelessly but this thing uses a BT module which shows up on PC as a COM port.

[Here](http://www.instructables.com/id/Arduino-Wireless-Programming-with-XBee-Series-1-or/?ALLSTEPS) is something similar using Xbees.

However, these use another arduino attached to a PC on the other end. In my case, I am planning to use rPi hooked to another nRF24L01+ rather than PC.

This is an excerpt from the datasheet of Atmega chip:

> In ATmega88A/88PA/168A/168PA/328/328P the Boot LoaderSupport provides
> a real Read-While-Write SelfProgramming mechanism for downloading and
> uploading program code by the MCU itself. This feature allows flexible
> application software updates controlled by the MCU using a
> Flash-resident Boot Loader program. The Boot Loader program can use
> any available data interface and associated protocol to read code and
> write (program) that code into the Flash memory, or readthe code from
> the program memory.

Here is what I planned as a strategy.

Master programmer = Raspberry Pi + nRF module.

Slave arduino = Arduino + nRF24L01 + external EEPROM

Once I have to upload a new code, I can transmit the compiled code to the arduino (I can do that, right?) and Arduino will save it in the external EEPROM for the time being.

When the transfer is complete, I will send a signal which will make the arduino reset and copy the code from EEPROM to its flash memory.

My questions:

Is the strategy correct and feasible?

How should I proceed to achieve it?

Any other suggestions which you might have are welcome.

title: OTA updates for Arduino using nRF24L01+

Answers: 5

body:
Your best strategy would be to write your own bootloader.

The existing bootloader receives data through the serial port and writes it, a page at a time, to the flash.  Your custom bootloader, instead, would receive the data through the nRF module and write it to flash, a page at a time.

You could use the source code for the existing bootloader (maybe use optiboot?) as a starting point and remove the UART code, replacing it with nRF code.

Of course, you still need a way to enter the bootloader when you want to program it - the easiest way is to ensure that is added into any sketch you upload so you can send an instruction to that sketch to enter the bootloader.

You would also need to create a program on the Pi to do the programming over the air - or modify an existing one like avrdude.

It may, in the long run, be simpler to have a pair of other Arduinos (maybe something small like an ATTiny based board) to act as bridges between UART and the nRF modules so they become a transparent wireless serial link.

body:
It's definitely feasible and it's been done. Look at [Low Power Labs site](http://lowpowerlab.com/blog/category/moteino/wireless-programming/) where Felix did the same thing, but with a RF69 radio and an external flash chip. You do need a modified bootloader as he uses, one that would detect the new sketch in the external flash and will upload it to the Arduino on reset. Radio difference aside this should work well for your purposes.

Given the flaky nature of the radio communication I think it's a good idea to store the program separately rather than create a highly modified bootloader which will read the radio stream - it might be that for programming you need a constant stream of bytes which the radio can't always provide (though I'm not 100% sure about this); another reason being that the extra code you would need to access the radio will make for a larger bootloader.

body:
If you're working with remote sensor nodes, perhaps consider the MySensors library.

It's got support for two methods of delivering OTA updates - one using a node.js controller running on a rPi; and another third-party solution with a .NET front-end.

Failing that, you could borrow the bootloader code from the library and customise to your own needs.

body:
There is an [Arduino optiboot fork][1] for this now, which seems to handle what you want.

You would use a PC, RPi or whatever that could run `avrdude` to send the update to an Arduino acting as the update server, which transmits the code to the client.

The instructions on the page seem quite comprehensive.

  [1]: https://github.com/balrog-kun/optiboot

body:
As per @Majenko and @Kurt suggestions:

Please check out me blog post, it is exactly about that!

https://www.2bitornot2bit.com/blog/arduino-bootloader-with-ota-over-the-air-support-over-nrf24l01

I have made a complete tutorial about this issue and also modified the suggested code above so debugging will be easier.

The basic idea is to have a local station which forwards the new sketch from the **computer->uart->spi->rf24** to a remote Arduino running a custom bootloader which listens on the **rf24->spi** instead of the UART. This bootloader does everything as usual (expecting protocol commands as part of the stk500 protocol and so on) but, instead of getting them over UART the packets arrive from the RF24 module through SPI.

During boot, the bootloader will have to initialize the RF module registers and then parse the incoming bytes if any; after a timeout, it will quit and run the sketch currently there in a loog as usual

In [my blog][1] you will see some notes about the Hardware configuration for the local station: you need a 10uF capacitor between the **RESET** and **GND** pins to avoid flashing the local station while trying to flash the remote station.

That post also incldues the commands needed to use AVRdude to flash the bootloader and then to flash the remote station (which has the new bootlaoder) through the local station running the "flasher" sketch (station with the capacitor).

Basic commands are:

    avrdude -C "C:\Users\Ben\Downloads\avrdude\etc\avrdude.conf" -b 19200 -c usbtiny -p m328p -v -e -U efuse:w:0xFD:m -U hfuse:w:0xDA:m -U lfuse:w:0xFF:m -F
    avrdude -C "C:\Users\Ben\Downloads\avrdude\etc\avrdude.conf" -b 19200 -c usbtiny -p m328p -v -e -U flash:w:optiboot_atmega328_new_bootlader.hex -U lock:w:0x0F:m

You can find the code on my blog and links to other sources and tools needed
(such as an AVR programmer).

  [1]: https://www.2bitornot2bit.com/home/arduino-bootloader-with-ota-over-the-air-support-over-rf24