text:
32u4 timer 4 pwm frequency help
I have extracted the following code from the multiwii project. It generates a ~490-500hz pwm signal on pin 6 which is used to drive an esc.
I want to change this frequency down to 50Hz to drive a servo instead. But ive had next to no experience at this level of avr programming, and dont want to loose anymore days to it, if its a dead end. (ie not possible) (i have tried reading various websites on the topic)
void setup() {
    pinMode(6, OUTPUT);
    TCCR4E |= (1<<ENHC4); // enhanced pwm mode
    TCCR4B &= ~(1<<CS41); TCCR4B |= (1<<CS42)|(1<<CS40); // prescaler to 16
    TCCR4D |= (1<<WGM40); TC4H = 0x3; OCR4C = 0xFF; // phase and frequency correct mode & top to 1023 but with enhanced pwm mode we have 2047

    TCCR4C |= (1<<COM4D1)|(1<<PWM4D); // connect pin 6 to timer 4 channel D

}

void loop() {
    //write out
    int value = 1500;
    TC4H = value>>8;
    OCR4D = (value&0xFF);
}

here is the new code so far working off the solution provided below:
void setup() {
    pinMode(6, OUTPUT);
    TCCR4B &= ~(_BV(CS43) | _BV(CS42) | _BV(CS41) | _BV(CS40));
    TCCR4B |= _BV(CS43) | _BV(CS41);
    TCCR4D &= ~(_BV(WGM41) | _BV(WGM40));
    TC4H = 624 >> 8; // B10 0x2
    OCR4C = 624 & 0xff;//B1110000 0x70
    TCCR4C |= (1<<COM4D1)|(1<<PWM4D);
}
void loop() {
    //write out
    //30 - 60 gives 1000 to 2000 us, but that only allows 30 increments between ??
    int value = 30;
    TC4H = value >> 8;
    OCR4D = value & 0xff;
}

the wave form i want:

Yeah... sometimes it's easier to scrap what's already there and start fresh.
We need to:

Pick a suitable prescaler to get close to the desired cycle length
Fine-tune the value in TOP in order to get an exact value

Assuming this is a 16MHz Leonardo, and we have Fast 10-bit PWM (PWM4x = 1, WGM4x = 0b00) available:
16MHz / 50Hz / (1 << 10) = 312.5
Therefore we need a prescaler of 512 (CS4x = 0b1010).
16MHz / 50Hz / 512 = 625
Therefore we need a TOP of 624 (OCR4C = 624).
TCCR4B &= ~(_BV(CS43) | _BV(CS42) | _BV(CS41) | _BV(CS40));
TCCR4B |= _BV(CS43) | _BV(CS41);
TCCR4D &= ~(_BV(WGM41) | _BV(WGM40));
TC4H = 624 >> 8;
OCR4C = 624 & 0xff;

And then you set COM4xn and PWM4x to appropriate values for whichever pin(s) you want to output PWM on, and set OCR4x to a value between 0 and 624 (using TC4H appropriately; see the datasheet for details) to control the duty cycle.

ok, its working but i think we 'overlooked' something important i forgot to mention... i need the duty cycle to suit a servo, so between 1 and 2 milliseconds. the duty im getting from your example is much bigger 2ms to 19.2 ms its like 10x too much, maybe we dropped a decimal ? (but the frequency is correct)

ive added the code i have put together from your help above into the question. if i use a value between 30 and 60 it gives me the correct duty, but this only allows 30 steps .. ?

@HaydenThring: 50Hz means a 20ms period. If that's too long then use a higher frequency. The Arduino libraries use 490Hz.

i have added a screenshot of the waveform i want, it needs to be 50hz, which is what im getting from your code, but there is a lack of resolution in the settable values to get that duty.

@HaydenThring: If you need that resolution at that low a frequency then you'll need to use timer 1 or 3 instead, in wavegen mode 14.

firstly thanks again for your reply. i thought this might be the situation, as the code they use to generate the 50hz on the other pins uses those timers and is markedly different. i will add it to my question for reference, (though i have not got it working, its all the related code to it i can find to extract)

To get finer resolution use Timer 1 - as Ignacio Vazquez-Abrams suggested.
void setup ()
  {
  pinMode (10, OUTPUT);   // OC1B on the Leonardo / Micro
  TCCR1A = 0;   // stop Timer 1
  TCCR1B = 0;   //     ditto

  // set up Timer 1
  TCCR1A = bit (COM1B1) | bit (WGM11) | bit (WGM10);  // toggle OC1B on Compare Match
  TCCR1B = bit (WGM13) | bit (CS11);   // PWM phase correct, prescaler of 8
  OCR1A = 20000;  // frequency: 50 Hz
  OCR1B = 1000;   // duty cycle - 1 ms
  }  // end of setup

void loop ()
  {
  // whatever
  }  // end of loop

As you can see from the scope output, the pulse width is 1 ms, which extremely conveniently corresponds to the duty cycle of 1000. Thus, therefore, the duty cycle figure is exactly related to microseconds.
Also you can see that the frequency is 50 Hz.

This uses a prescaler of 8 to give high resolution. It takes two pulses to make one "cycle" (one on, one off) and thus it effectively divides the system clock by 16. Since the system clock is 16 MHz, that is why one "unit" is 1 µs.
The OCR1A figure is arrived at easily:
 1000000 / 50 = 20000  (1 MHz / 50 Hz)

Now you can just tweak your desired pulse width knowing that each unit is 1 µs. So for 2 ms OCR1B would need to be 2000.

I cant use this on pin D6 though can i ?

On the arduino micro can i use 3 pins using this code? if yes which ones?

@HaydenThring - nope, you cant use D6 for this if you are not using Timer 1 as suggested


text:
QRPrint library characters limit
I am trying to use this library to print QR codes using Arduino. There is a limit on the number of characters allowed in the string to be printed.
printQR("This is the string to be QR encoded !!! Tralalala. Some other random characters !!!");

When I scan the generated QR code, the string seems to be truncated. Did anyone run into this before? Or is there any way to get around this issue by raising the number of characters allowed in the string?
Thank you.

What is the limit, exactly? 47?

The code in the library truncates to 47 characters for some reason:
void printQR(String message) {

...

  // create QR code
  message.toCharArray((char *)strinbuf,47);
  qrencode();

The buffer is actually 116 bytes, oddly.
unsigned char strinbuf[116];

It's a little unclear why the limit of 47, or 116, was chosen.
You could try changing that line in qrprint.cpp to increase the number from 47 to at least 115.

Edit
After reading some of the comments, I doubt that will help. The QR code looks like it is generated into an internal array, which would have to have some size limits due to the amount of RAM available. The current array size is:
unsigned char qrframe[600];

That is already 1/3 of the available memory on a Uno.

Does the library actually support version 10 or larger QR codes though?

Also, the 116 limit is for pure numeric codes (115/3*8=48).

I think I've identified why the string is truncated. The reason (for 47) is a bit more obscure. I couldn't find any documentation about which version they library produces, and therefore whether that is in fact the upper limit. See Information about QR codes. Version 2, ECC level L, alphanumeric, has a limit of 47 characters.

This is also a reason why I dislike "magic numbers" in the middle of code. Why 47? Why not 46 or 48? A comment on that line explaining why the number 47 is there would be very useful.

Thank you @NickGammon for the clarification. The thing is that I am using this library in order to convert larger strings into printed QR codes. I tried increasing the numbers in the source code but that generated odd QR figures that are neither scannable nor compliant to QR standards. I would like to know if anyone ran into this before and what is the correct way to generate version 7 QR codes or higher. If it could be of help the library is build on top of https://github.com/tz1/qrduino . Thank you

Judging by what I read about higher version QR codes, they are more complex. For one thing they have more "locator" boxes in them. A version 7 code would be 45 x 45 modules (2025) which could hardly be stored in the RAM, unless you stored a bit at a time, in which case they might fit. The library might need complete reworking - try asking the author. The alternative would be to print something short (like a web page link) and have that link provide more information.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
How to connect new OV7670 FIFO to Arduino?
I bought a new OV7670 FIFO camera to connect to my Arduino UNO a few days ago.
The picture of the cam board:

I found this forum, it is nice try but it looks chaotic and confusing with about 50 pages, where you can't find where the questions and where the answers are.
I also found this library which is for non-FIFO board and could not apply to my project. I also read the OV7670_FIFO and OV7670 and AL422 datasheets and I read I2C protocol and basics; and there are many success story on the internet but there is no schematic on them.
The problem is, I can't find any simple example for FIFO with schematic to start with. I don't know if this camera is so new or it is so hard to understand, this problem getting so serious that somebody wrote a book named "Beginning Arduino ov7670 Camera Development" about it, but I think it is a matter of an Arduino to FIFO cam schematic and example code. I ask if there is a such schematic and code for it on the web or how can I connect them?

I'm only on my phone so can't provide a full answer right now, but despair not, with a FIFO, things are a lot easier than they could be. With camera modules, usually it involves sending and receiving complicated and fast signals, on the edge of what an arduino is capable of handling. A FIFO, is a buffer, you can kind of think of it like RAM, and the way it works is you can take a picture, and instead of trying to receive it directly on the arduino, the data gets sent to the FIFO. Then, you can read the FIFO from your arduino, as fast, or as slow as you want.

So the two things you need to accomplish are, How do I send a command to the camera to take a picture? and How do I read the data from the FIFO? For the first, as far as I can tell all it is is connecting via i2c, so just the SDA and SCL pins (A4 and A5 respectively on the Uno) to their corresponding pins on the camera. For the FIFO, it is a parallel data bus, so it just means connecting the D0-D7 pins to digital pins on the arduino.

Are you 100% sure it's the FIFO version? I see no SPI or I2C (or are they labelled differently?).

The AL422B, as shown in the photo, is, to quote from the data sheet: ...a First-In-First-Output
(FIFO) video frame memory used to buffer
audio/video/graphic data...

I just received this exact model, QIFIO v1.0, exactly as yours. I am very interested in use this camera in full resolution, max sensitivy, with my dccduino UNO. I will try to get this camera working, I'm a very experienced programmer, but my fear is to burn it with a excessive voltage in signal pins. I wired the vcc to 3.3v, but I don't know if I must use 10k resistances in the rest of the signals (SIOC, SIOD, VSYNC, HREF, etc.). Thanks in advance

I recently brought this book off Amazon "Beginning Arduino ov7670 Camera Development".  I'm loathed to recommend it, because it has a nice 80 page introduction to the Arduino and OV7670 and the rest of the 250 pages are just double space annotated code.  That said, it does appear to be a very good introduction, with example code, for a OV7670-FIFO (the title of the book is incorrect).
It might be possible to find the code on the net and then you can decide if you want to buy the book or not.  Oh and I am not Robert Chin, I do not know him and I have nothing to do with the book, other than owning a rather new and once read copy of it.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Set Bluno Beetle to Broadcast mode
I recently purchased Bluno Beetle (basically a smaller Arduino with a BLE chip). It is based on the Bluno: Wiki I know that its Bluetooth Chip, the TI CC2540, supports the Broadcast mode: Official page
However I can't find any AT commands that would allow me to set it to this mode, does anyone of you have an idea? I am trying to relay the messages they are sending (sensor readings), essentially building an interconnected network.

It looks like the Bluno only supports the Central and Peripheral roles (i.e. not the Broadcaster and Observer roles.) Keep in mind AT commands are a feature of the firmware, not the actual chip. As such, even if the chip supports a particular mode or role, that doesn't necessarily mean the firmware makes the feature available.

That's what I was afraid of :-/ Thanks for your answer though!


text:
Standard Length Messages over RS-485
I am a bit confused. So I want to send messages between two arduinos over RS485, but these are not fixed length, naturally, I have to send the length of the message or add a delimiter to understand that my message has ended.
Suppose, now I create a placeholder for the message, and both ends communicating are receiving the placeholder, rather than the message itself. This placeholder is x bytes long always, and each arduino can look it up from its memory what message corresponds to the placeholder.
Lets say I create a message.h file with contents like this
#define A "First Message"
#define B "Second Message"

When the two devices are communicating, they send each other A or B, and the Arduino looks it up in its .h file what A and B mean.
My question is when the Arduino recieves the A, it recieves a character 'A', but how can I use this to fetch the value assigned to variable A in memory?

Seems you #define A you arduinos will see the stuff in the " " and not just A

There is no "variable A" - there is only a macro called "A" which gets replaced by the contents of the #define for "A" at compile time.
You have to remember that the "A" that the Arduino receives is just a number.  It is only us humans who choose to associate that number with the letter A, and write software that takes that number and display it as an A.  The letter A is number 65.  The mapping between numbers and letters is called ASCII - or American Standard Code for Information Interchange.
What you do with that number is entirely up to you.  If you want to use it to display pre-defined messages, then there's a number of ways you could do it.  You could:

Use a series of if statements to compare the number you have
Use a switch/case construct in a similar way
Store the messages in an array and use the received number as the index

For string constants the last option is tricky to get right on an Arduino where there is very limited RAM - you have to ensure that you use PROGMEM and access it properly, and doing that from an array is not as trivial as it would otherwise be.
The best method would probably be the switch/case option:
switch (letter) {
    case 'A': Serial.println(F("First Message")); break;
    case 'B': Serial.println(F("Second Message")); break;
}

I have a write-up about RS485 including a small library to handle this situation.
It can be downloaded from http://www.gammon.com.au/Arduino/RS485_protocol.zip.

Library features

Handles "packets" of between 1 and 255 bytes.
Uses a "begin packet" character (Start of Text, STX, 0x02) to reliably indicate that a packet is starting.
Uses an "end packet" character (End of Text, ETX, 0x03) to reliably indicate that a packet is ending.
Each data byte (other than STX/ETX) is sent in a "doubled/inverted" form. That is, each nibble (4 bits) is sent twice, once normally, and once inverted. Thus the only valid values for each nibble are:
0F, 1E, 2D, 3C, 4B, 5A, 69, 78, 87, 96, A5, B4, C3, D2, E1, F0

The inverse (ones complement) of 0 is F, hence 0 becomes 0F. The inverse of 1 is E, hence 1 becomes 1E. And so on.
This guards somewhat against "bursts" of noise. A burst of either 0s or 1s is unlikely to corrupt a byte preserving this normal/inverse relationship. Also there are only 16/256 valid combinations, so noise has only a 6% chance of becoming a valid byte.
Because of this, also, the STX and ETX characters cannot appear in ordinary data (they are not one of the 16 valid values).
Each packet is followed by a CRC (cyclic redundancy check). This is a further test that the packet was received completely. It guards against noise, or possibly some bytes just becoming missing.

More details on the linked page, but basically you provide a few functions to:

test if a byte is available for reading
read a byte
write a byte

These could be with SoftwareSerial, HardwareSerial, or whatever you choose.
Then you either send or receive a "packet" which is the data you want transmitted to the other end.
There is a "blocking" and "non-blocking" version. The blocking version (when reading) waits for an entire packet to arrive. The non-blocking one lets you do other things while waiting for the entire packet.


text:
How to disable Due USB power?
I need my Arduino Due to work only from external power supply, not from USB power. Is there any way to modify the circuit to allow this? I still need to keep USB communication, but it should happen only when external power is on. Thanks

Disabling USB power is slightly tricky, as the incoming USB power is not only used for potentially powering the system, but it is also used by the various USB interfaces to indicate the presence of a connection.
The best way, looking at the schematics of the Due, would be to remove one or both MOSFETs that switch the USB power - that's T1 for the native port and T2 for the ATMega interface.  That will isolate the USB power from the 5V system while keeping it connected to the VBUS pins of the relevant microcontrollers.

Thanks, I removed the MOSFET and now it works exactly as I want!

There is four ways I know of you can do to achieve exactly this :

You can remove the usb polyfuse from your board, which will make the usb behave exactly as you need it to. Between the 2 two usb connections in this picture  is a smd component marked 501V. This is your polyfuse. Disabling this cuts the +5v line to the board from the usb but leaves the data lines open.
If you dont want to physically modify your board, then there is 2 other solutions you could use instead. You can buy a data-only usb cable, but they will probably be expensive and difficult to find.
Modify your usb cable. It has 4 pins used by the board, +5v, GND, and the 2 data comms pins. All you have to do here is cut out or block the +5v. The GND pin is still needed as the data pins still draw power off the board.
The arduino boards auto select a power source(the usb usually) if you have both usb and external power connected at the same time. A way to force the board into switching to the external power source instead, while supplying power to the data lines on the usb is to make sure the dc supply is greater than 6.6v.

Edit: That last one is for the 5v arduino boards, I just remebered the due works on 3.3v instead so this probably won't work on your board

Thanks  a lot for your detailed comment, I already got this working by removing the MOSFET. I'll keep these methods in mind though.

@ruffles Removing the polyfyses or otherwise killing the incoming USB power is a bad idea since that would isolate the incoming USB power from the VBUS pins of the ATMega and/or the SAM3X, which it needs to know if there is a USB connection for it to work with.


text:
How to change LDR output in simulator 123D Circuits?
I used simulator 123d.circuits.io to create simulation of basic circuit with LDR: LDR is connected to 5V and via 10K resistor to GND. Wire between LDR and resistor is connected to analog pin where I read ADC values and display them using serial monitor. This works fine. But I would like to how to change lighting level of LDR in simulation because this way LDR shows still the same value. I tried putting LED or light bulb near LDR but it doesn't seem to have any influence. Any ideas?

Ok, so I found it myself. You can click on LDR during simulation and bar to adjust lighting appears above it.

Please use the edit link on your question to add additional information. The Post Answer button should be used only for complete answers to the question.

It is complete answer to the question.


text:
Arduino Uno - Analog Circuit Simulator
I control an analog circuit with Arduino Uno. I want to simulate an Arduino Uno with operational amplifiers (741). Can I simulate Arduino with SPICE?

No, there is no SPICE model for an Arduino. But then given that an ATMega328 doesn't have any DAC capabilities you would only need to feed in a digital stimulus to your simulation.

Here is the one which is closest to be useful for your question
Link: https://markmegarry.github.io/AVR8js-Falstad/
Try it out for yourself
It is very slow though.

You could use https://en.wikipedia.org/wiki/Ngspice.
From what is written there, the Xspice part could be used for creating a simple model of the Arduino, for checking how the analog part of your circuit interacts with the uC.
Unfortunately the main site () is down, atm, as many other projects hosted on SourceForge. But it might be worth having a look, once it's back online.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Read OUTPUT pin value in Arduino Due
I am trying to read the value of an output pin. online forums say that digitalRead(pinNum); should work, but that is not the case here. digitalRead always returns 0 (LOW).
This is the code:
int pin = 22; // or 13, or 3 ...
void setup()
{
  Serial.begin(9600);
  pinMode(pin,OUTPUT);
}
void loop()
{
  digitalWrite(pin,HIGH);
  delay(100);
  Serial.println(digitalRead(pin));
  delay(100);
  digitalWrite(pin,LOW);
  delay(100);
  Serial.println(digitalRead(pin));
  delay(100);
}

printed values:
0
0
0
...

That method only works on AVR based systems.  It exploits a "feature" whereby the IO pin, when in OUTPUT mode, is also in INPUT mode at the same time, and reading the pin reads the value that the pin is being driven to by the digitalWrite function.
The same is not true of the Due, which is an ARM based system.  The IO pins function completely differently and the same "feature" cannot be used.
You will have to remember the state of the pin yourself.

I cannot upvote yet, but thank you!

Majenko's answer basically explains the cause - apparently on the SAM3X8E reading the input data register will not show the state being driven on output lines in the way it would on some other devices like the AVR.
However the conclusion that "you will have to remember the state of the pin yourself" is not correct.
According to the data sheet, the output data state can be read from the relevant port's PIO_ODSR register.   That the Arduino libraries don't do this could be an oversight, but probably is an efficiency decision, as they would need to examine the direction of each pin to determine the register to read for its state.
It would not be hard to make your own functions or macros to read the PIO_ODSR - you could model them on the digitalInput() ones.

try editing...
Serial.println(digitalRead(pin));

to .....
Serial.println(digitalRead(pin), DEC);

This works on my arduino Leonardo.

No.  The actual issue has already been explained.  This question is about a Due and arrises from differences between that and more classic AVR Arduinos.

Feed the output to a (spare) input pin and digitalRead() that pin!

Actually the output data can be read in software, it just needs to be read from a different register than the input data.


text:
Arduino restarts problem
I want to assign -1 to count variable again when count == 16 but when I have assigned -1 inside the if condition I have marked below in the code, the Arduino restarts.
Can anyone guess what is wrong here?
#include <LiquidCrystal.h>
#include <avr/pgmspace.h>
#include <hid.h>
#include <hiduniversal.h>
#include <usbhub.h>
#include <Usb.h>
#include <usbhub.h>
#include <avr/pgmspace.h>
#include <hidboot.h>
#include <SPI.h>
#define DISPLAY_WIDTH 16

// initialize the LCD library with the numbers of the interface pins
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);

USB     Usb;
USBHub     Hub(&Usb);
HIDUniversal Hid(&Usb);
HIDBoot<HID_PROTOCOL_KEYBOARD>    Keyboard(&Usb);

int count = -1;
char drawNo[4];
int m = 0;
int turn;
class KbdRptParser : public KeyboardReportParser {
    void PrintKey(uint8_t mod, uint8_t key);
protected:
    virtual void OnKeyDown(uint8_t mod, uint8_t key);
    virtual void OnKeyPressed(uint8_t key);
};

void KbdRptParser::OnKeyDown(uint8_t mod, uint8_t key) {
    uint8_t c = OemToAscii(mod, key);
    count++;

    if (c)
    { OnKeyPressed(c); }
}

/* what to do when symbol arrives */
void KbdRptParser::OnKeyPressed(uint8_t key) {
    static uint32_t next_time = 0;      //watchdog
    static uint8_t current_cursor = 0;  //tracks current cursor position

    if (millis() > next_time) {
        lcd.clear();
        current_cursor = 0;
        delay(5);    //LCD-specific
        lcd.setCursor(0, 0);
    }//if( millis() > next_time ...

    next_time = millis() + 200;  //reset watchdog

    if (current_cursor++ == (DISPLAY_WIDTH + 1)) {    //switch to second line if cursor outside the screen
        lcd.setCursor(0, 1);
    }

    int keys = (int) key;

    if (count == 4 | count == 5 | count == 6 | count == 7) {
        turn++;
        drawNo[m] = (char)keys;
        //lcd.print(drawNo[m]);
        Serial.print(drawNo[m]);
        Serial.print(m);
        ++m;
    }

    if (count == 16) {
        Serial.println("Counter equals 16 NOW");
        printScreen();
        delay(200);
        count = -1; /* <<<<<<<<<<<<<<<<<<<<<<<<<<<<Here is the problem*/

        for (int i = 0; i < sizeof(drawNo);  i++) {
            drawNo[i] = (char)0;
        }
    }
}
void printScreen() {
    int j;
    lcd.print(" DRAW NO : ");

    for (j = 0; j < 4; j++) {
        lcd.print(drawNo[j]);
    }
}
KbdRptParser Prs;

void setup() {
    Serial.begin(115200);
    Serial.println("Start");

    if (Usb.Init() == -1) {
        Serial.println("OSC did not start.");
    }

    delay(200);
    Hid.SetReportParser(0, (HIDReportParser *)&Prs);
    // set up the LCD's number of columns and rows:
    lcd.begin(DISPLAY_WIDTH, 2);
    lcd.clear();
    lcd.noAutoscroll();
    lcd.print("Scan Your Code");
    delay(200);
}

void loop() {
    Usb.Task();
}

int m = 0;
...
    drawNo[m] = (char)keys;
...
    ++m;

No other references to m in your code. Therefore m keeps increasing and you are writing outside the bounds of the array drawNo, corrupting memory.

I doubt it is the count. Did you try moving it to above the serial print so that you can be sure of the report?
if (count == 16) {
        count = -1; /* <<<<<<<<<<<<<<<<<<<<<<<<<<<<Here is the problem*/
        Serial.println("Counter equals 16 NOW");
        printScreen();
        delay(200);

        for (int i = 0; i < sizeof(drawNo);  i++) {
            drawNo[i] = (char)0;
        }

No problem still exists.. any other idea?

Before you must see "Counter equals 16 NOW" now with the changed code do you see "Counter equals 16 NOW"?

@ Visual Micro Ya it prints "Counter equals 16 NOW" on serial Monitor,and also I have printed the value of count and it also proved that count is -1 now. ! but why is that board restart??

What Nick has said is right. It's because ++m is never reset

Thank you very much for your contribution. problem solved.


text:
Software I2C - ATmega8
I am using ATmega8 with 12MHz crystal, on my breadboard. I can use SDA and SCL pins with default arduino library wire.h, and it works. But I want another pins to use I2C protocol.
I tried this library, even on real SDA and SCL pins, but it doesn't work.
I have pull up resistors, I tried with 10k and 4.7k without any success. (But those resistors worked with hardware I2C | TWI)
What am I doing wrong? (All connections is fine, because hardware TWI works but software does not.) Thank you for your help.
(Fuses are ok, because the Atmega won't respond if I remove the crystal oscillator, the LED blinking duration is ok.)
What i want to run (that doesn't work):
#define SDA_PORT PORTC
#define SDA_PIN 4
#define SCL_PORT PORTC
#define SCL_PIN 5

//#define I2C_TIMEOUT 100

#include <SoftI2CMaster.h>

uint8_t ADDR  = 0x68;

void setup(void) {

  Serial.begin(19200);
  Serial.println("Initializing ...");
  i2c_init();

  if (!i2c_start(ADDR | I2C_WRITE)) Serial.println(F("Device does not respond"));
  if (!i2c_write(0x00)) Serial.println(F("Cannot address reg 0"));
  i2c_stop();
}

void loop (void) {
  unsigned int low0, high0, low1, high1;
  unsigned int chan0, chan1;
  unsigned int lux;
  int state1;
  int state2;

  delay(1000);
  i2c_start(ADDR | I2C_WRITE);
  i2c_write(0x00);
  i2c_rep_start(ADDR | I2C_READ);
  low0 = i2c_read(false);
  high0 = i2c_read(false);
  low1 = i2c_read(false);
  high1 = i2c_read(true);
  i2c_stop();
  Serial.print(low0);
}

And the code with hardware TWI that works:
#include "Wire.h"
#define DS3231_I2C_ADDRESS 0x68
// Convert normal decimal numbers to binary coded decimal
byte decToBcd(byte val)
{
  return( (val/10*16) + (val%10) );
}
// Convert binary coded decimal to normal decimal numbers
byte bcdToDec(byte val)
{
  return( (val/16*10) + (val%16) );
}
void setup()
{
  Wire.begin();
  Serial.begin(19200);
  pinMode(13, OUTPUT);
  pinMode(5, INPUT);
}
void readDS3231time(byte *second,
byte *minute,
byte *hour,
byte *dayOfWeek,
byte *dayOfMonth,
byte *month,
byte *year)
{
  Wire.beginTransmission(DS3231_I2C_ADDRESS);
  Wire.write(0); // set DS3231 register pointer to 00h
  Wire.endTransmission();
  Wire.requestFrom(DS3231_I2C_ADDRESS, 7);
  // request seven bytes of data from DS3231 starting from register 00h
  *second = bcdToDec(Wire.read() & 0x7f);
  *minute = bcdToDec(Wire.read());
  *hour = bcdToDec(Wire.read() & 0x3f);
  *dayOfWeek = bcdToDec(Wire.read());
  *dayOfMonth = bcdToDec(Wire.read());
  *month = bcdToDec(Wire.read());
  *year = bcdToDec(Wire.read());
}

Schematic is the same as: https://www.arduino.cc/en/main/standalone.
Except instead of 16MHz, I use a 12MHz and ch210x serial.
Arduino's bootloader works well, I compiled it from source.

It would help if you posted code and schematics of both situations (hardware and software I2C attempts). Also, to debug I2C effectively, you'd need a logic analyzer or at very least an oscilloscope.

What do you get on the serial output?

Initializing ...
Device does not respond
Cannot address reg 0
SDA - SCL 0 0
Raw values: chan0=65535 SDA - SCL 0 0

actually i should get the ohur:minute:second day/month/year that i can get in hardware twi,

i ve removed some of code, just before he stop function , i get the pinstate to whats happening, so that output is showed

OK let me cry till morning...
i was having this issue during day, but the solution was sooo easy
i need to pay attention more ...

i2c_start(addr | R/W-bit)
  Initiates a transfer to the slave device with the (8-bit) I2C address addr.

what i was trying is to push 7 bit address.
i hope this might help some others.
Thank you for help.


text:
Having issues with Arduino + Bluetooth
I am working with a combination of Teensy++ 2.0 and Sparkfun Bluetooth Modem.
The Arduino program, inside the loop, continuously reads a sensor value. If the value read is above a threshold, the Arduino transmits a "CHARACTER" over Bluetooth for any receiver.
So, inside the same loop, I check for the availability of data, and print the received character. The problem is, the received character is not what is transmitted. The received character is some garbage value.
Please let me know what is going wrong here.
#include <SoftwareSerial.h>

#define bluetooth Serial1

#define BAUDRATE 9600

// Analog read 0 is pin 38
int sensorValue = 0;
int SENSOR_ANALOG_READ_PIN = 0;
int LED = 17;

char toPrint = '\0';
bool sent = false;
char state = ' ';

void setup()
{

// put your setup code here, to run once:

  pinMode(LED, OUTPUT);

  Serial.begin(BAUDRATE);

  bluetooth.begin(BAUDRATE);

}

void loop() {

  // put your main code here, to run repeatedly:

  sensorValue = analogRead(SENSOR_ANALOG_READ_PIN);

  if(value > 500)

  {
      //Serial.println("HIGH");

      digitalWrite(LED, HIGH);

      bluetooth.write(state);

      bluetooth.flush();

      sent = true;

      digitalWrite(LED, LOW);

  }

  else

  {

      delay(100);

  }

  ///////////////////////////////////////////////////////////
  if((bluetooth.available()) && (sent == true))

  {

        Serial.println("printing : ");

        toPrint = (char)bluetooth.read();

        Serial.println((char)toPrint);

        sent = false;

   }

}

Output:
printing :
1
printing :
ˆ
printing :
Ì
printing :
¦
printing :
È
printing :
Ì
printing :
Ì
printing :

The code is really hard to read as it is right now - namely because it's not formatted. Could you go through your code and ensure it's properly formatted? It would make it much easier for us to help you.

@Mlagma The code is now formatted by Gerben .

Try without the sensor value first by sending known exact values (so you only test the bluetooth connection.

Is the device on the other side of the bluetooth connection running at 9600 baud too ?
You say you transmit the state of the sensor - which BTW is only ever a space ' ', and never changes.
So that value gets written out via the bluetooth connection.
But then you read data in from the other party to the bluetooth communications.
It sounds like you expect the data written to the bluetooth output serial line to also be echoed back from the bluetooth input.  The serial transmit and receive are separate channels.  You are receiving on the bluetooth.read() whatever the device connected to it is sending, not what you write yourself.
What you are sending goes only to the other side of the conversation.  The remote device would need to echo whatever it sees back for it to work how you describe.

The default baud rate for HC-05 is 38400 bauds. I was trying to set it to 9800.  For some reason, that was not accepted by HC-05.
Solution:
I changed the line
#define BAUDRATE 9600

to
#define BAUDRATE 38400

This solved my problem.

Are you sure you have defined your pins properly? I don't see anywhere where you define SENSOR_ANALOG_READ_PIN as an input. If this is the Tx/Rx pin (I forgot the pin configuration), you can define the input pin to be somewhere else to test using the SoftwareSerial library.
This is what I did and it worked for me, hope it helps.
This link isn't for your module but the concept should be the same: Arduino AND Bluetooth HC-05 Connecting easily.


text:
Perfect copy of Yun with Micro SD
My Yun has a micro SD card with shared file system using ExpandingYunDiskSpace.
I would like to copy my Yun/SD card data perfectly onto my backup Yun/SD card. Because I have made many changes to the filesystem, just re-running the whole process manually would take a long time.
What methods can I use to transfer my Yun's data onto my other Yun?
My other Yun is brand new (never plugged in), and I have a brand new SD card in there. If I can do a 'bit-perfect' transfer for Yun and Micro SD in one shot that would be ideal.

Copying an SD card (cloning) is easy enough to do.  On Windows you can use Win32DiskImager.  On Linux and OS X you can either use dd from the command line:
(read)
$ dd if=/dev/sdb of=MySD.img bs=32k

(write)
$ dd id=MySD.img of=/dev/sdb bs=32k

For OS X the device names will be different, also in Linux you need to check which /dev/sd?? it is.
Also in Linux and OS X there are GUI applications that can do it for you - the Disk Manager in OS X, and "Gnome Disks" in Linux.
That is only good for the actual SD card contents though.  If you need to clone the actual Yún itself then it becomes more tricky.
Fortunately there are tools available to help you.
Details on how to create and restore a backup of an OpenWRT system (which is what the Yún is) can be found on the OpenWRT Wiki: http://wiki.openwrt.org/doc/howto/generic.backup
Note that again it requires a Linux or OS X (preferably the former) system to do it since it relies on the standard Unix scripting tools and commands that are lacking on a Windows system.
You may be able to do all the above on a Windows system if you make it look like a Linux system by installing Cygwin.


text:
How to display a number using SevSeg library on 4 digit 7 segment LED display
I am getting error with this. It is displaying those segments which are not to be displayed, i.e., 3.141 is dark and other segments are red.
#include "SevSeg.h"

SevSeg sevseg; //Initiate a seven segment controller object

void setup() {
    byte numDigits = 4;
    byte digitPins[] = {2, 3, 4, 5};
    byte segmentPins[] = {6, 7, 8, 9, 10, 11, 12, 13};
    sevseg.begin(COMMON_ANODE, numDigits, digitPins, segmentPins);
    sevseg.setBrightness(1000);
}

void loop() {
    sevseg.setNumber(3141, 3);
    sevseg.refreshDisplay(); // Must run repeatedly
}

Are you sure you have the right type of common for your display?

There are two main types of seven segment display:

Common Anode
Common Cathode

The common refers to the fact that one end of the LEDs within a digit are linked, and need to be connected to either Vcc or GND, depending on the type of the display (see below). The other end of each led (one per segment) is used to switch them on, and it is these that go to the Arduino pins, or LED controller.
Common Anode

The common end is connected to the Vcc line. If you wish to light a segment, then the input pin for that segment needs to be pulled LOW.

Source: Four multiplexed 7-segment COMMON ANODE LED
Common Cathode

The common end is connected to the GND line. If you wish to light a segment, then the input pin for that segment needs to be pulled HIGH.

It sounds as if you have the logic inverted, so the wrong segments are lit, when they should be dark, and vice versa.
Either that, or you need to invert the logic in your code, and for example if you are currently pulling a pin LOW to light up a segment, then you need to change your code to pull the pin HIGH.

Image sources:
Electronics-Tutorials
Common Anode/Cathode 7-segment displays

You could try the following:
#include "SevSeg.h"

SevSeg sevseg; //Initiate a seven segment controller object

void setup() {
    byte numDigits = 4;
    byte digitPins[] = {2, 3, 4, 5};
    byte segmentPins[] = {6, 7, 8, 9, 10, 11, 12, 13};
    sevseg.begin(COMMON_CATHODE, numDigits, digitPins, segmentPins);
    sevseg.setBrightness(1000);
}

void loop() {
    sevseg.setNumber(3141, 3);
    sevseg.refreshDisplay(); // Must run repeatedly
}


text:
Prevent hardware and library examples from showing in the Sketchbook menu
I have various subdirectories in {SKETCHBOOK}/hardware/ and {SKETCHBOOK}/libraries/ that contain an examples/ subdirectory. These examples are showing up in File | Sketchbook | hardware and File | Sketchbook | libraries. Is there any way I can prevent them from showing up in that menu without moving them under the system-level Arduino directory?

Looking at the code it is scanning all folders and there is no option to change that behavior. Also looking at the code, it looks like it dumps them into a sub-menu, hiding them away a little further, if the folder is named anything except "examples", which could be an alternative option for you.
The final option would be to fork your own version and come up with some exclusion logic, maybe with some kind of ".ignore" kind of logic where you can specify folders to exclude form the menu.

Interesting. I think that the proper fix would be to modify Base.addSketches(JMenu, File) to skip "important" directories, since there shouldn't be user sketches in there regardless. But thank you for pointing this out,


text:
About Making Library
There is a tutorial in the Arduino website on how to create a library. The tutorial gives the following codes for the header:
class Morse
{
  public:
    Morse(int pin);
    void dot();
    void dash();
  private:
    int _pin;
};

My questions are:

What is the purpose of this line: Morse(int pin);
If any, what is the name of this line?

For looking further: note that the code you have isn't a library, it's a class (which can be put into a library). There are some really good articles on classes in C++ online that will go into detail about how they are written.

Your a penguin sir. @AnnonomusPenguin I'm a big fan of Tux.

What is the purpose of this line: Morse(int pin);

It is the method that is called when you create an object of class Morse when only passing a single int:
Morse somemorse(1);

If any, what is the name of this line?

It has multiple names, depending on what aspect you care about:

It is a constructor for the class Morse.
It is a forward declaration for the method Morse::Morse(int).

Morse(int pin);

is the constructor for the class, Morse.
The name of this line, and all of the other lines between the curly braces{ and } are declarations of the members of the class Morse.
So, the line
Morse(int pin);

is the declaration of the constructor, to answer both of your questions in one line.
Constructors are required pieces of code for Object Oriented Programming. When the constructor is called, it creates an object which is an instance of the class Morse. In this constructor is where all of the initialisation of the oblject goes. In the case of Morse it just initialises pin, which is specified in the parameter pin, by setting it to be an OUTPUT.
It is declared here, as a "signpost" if you will, for other parts of the code to know that it exists and is available to be called.


text:
Finding connectors for push button component
What type of connectors would I use for these buttons?:
http://www.adafruit.com/product/1477
They sell wires with the connectors already crimped on, but I only need the connectors.
I found https://www.jameco.com, but i'm not sure which connector would be right, or what to look for specifically.

Go down to your local (decently-stocked) hardware store and ask for "quick connect terminals". From the dimensional drawing you'll need 2mm or 5/64" terminals.

You may not have to go to a hardware store for this as they can also be found online

These are also called "Quick Disconnect" connectors. Here is the category on Digikey and Mouser. Jameco also sells them, but doesn't have a very easily filterable category for them.

Try the local automotive supplier. They should have crimp kits with those connectors included.


text:
USB Device not Recognised - Custom Wattuino Nanite 841
What I have done:
I have made a custom Nanite 841 which uses an ATTINY841 microcontroller.
I have used the schematics from Wattuino to design my circuit, my PCB was made using a router with all excess copper removed.
I have built the circuit and have ensured that every component and track does not short circuit.
I have successfully uploaded the Wattuino bootloader using ISP.
The Problem:
The problem that I am getting is when the microcontroller is connected to any computer I get an error message saying...

"USB device not recognised"

The device status shows this...

Windows has stopped this device because it has reported problems.
  (Code 43)
A request for the USB device descriptor failed.

I hope you can help as this is a bit of a bummer after just building my new device. Thank you for your time.

Is it a double sided board? I don't see any traces going from the USB to the VCC and GND pins of the attiny. Without power the chip won't run (per see)

-1 Your PCB does not match your schematic.  In addition to the ground problem,  it shows a 14 pin IC while the MCU you show has pins up to 16 and then a pin 20.  This question is not answerable due to its self contradictions, so it needs to be closed.

According to Github: micronucleus/micronucleus
 :

Windows machines will need to install the libusb drivers found in the /windows_drivers folder.  Clean Micronucleus devices without uploaded userprogram will not time out and allow sufficient time for proper driver installation. Linux and OS X do not require custom drivers.

Make sure you have installed the device drivers.

Also you need to attempt an upload shortly after reset:

The bootloader allows uploading of new firmware via USB. In its usual configuration it is invoked at device reset and will identify to the host computer. If no communication is initiated by the host machine within a given time, the bootloader will time out and enter the user program, if one is present.

See the troubleshooting page Code 43: Windows has stopped this device because it has reported problems from Microsoft.

You should be able to use a spare Uno or similar device to check the chip response. See Sketch to detect Atmega chip types.
Possibly you have the "divide clock by 8" fuse set. You could clear that if so.


text:
Arduino nano stopped working
After programming Arduino Nano with the DIY Headtracker code, after trying to plug the Arduino to the receiver and some time, the LED stops flashing and now it's not recognized by the computer anymore.
When I plug it, it only lights the power LED.
The worst thing is that I've already tried with another Nano and it bricked also, can't use them any more. Anyone know any fix to this?
This is the error given when trying to upload the blink sketch to the board...
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xb8
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xb8
avrdude: stk500_recv(): programmer is not responding

I suggest you visit the page Have I bricked my Arduino Uno? - whilst you have a Nano and not a Uno, it is the same processor and most of the remarks there will apply.
As the Arduino Nano page says:

It has more or less the same functionality of the Arduino Duemilanove, but in a different package.

If you have another Uno or similar lying around you could conduct the "chip detector" test described on that page. You could also perform the loopback test.
It is possible on the FTDI chip (underneath) is damaged in which case there would be alternatives to using that.

If you have access to an AVR ICE MKII or an AVRDragon, you could try High Voltage programming. It is, AFAIK, the ultimate way to revive a bricked device. There might be some alternative method to perform HV programming without any of the devices I mentioned (for example with another AVR), but I'm not aware of it, if it exists.

It's not really practical with a chip soldered to the board to do high-voltage programming, because you would send 12 V via the /RESET pull-up resistor to the +5 V pins, which would damage the chip.

@NickGammon: I wonder if there is any relatively simple way to cut a track or two and place jumpers on them. A bit like the procedure to make USB-reset optional for the UNO when enabling debugWire.
First thing that comes to my mind is to desolder the pullup, use the pads to wire/solder a male pin header and attach the resistor to a female pin header.

If was desperate, I would consider doing that. The other thing is that you have a whole lot of wires to connect (as the chip is soldered in). I've got a post about high-voltage programming which shows that you have around 20 wires to connect. I'd be a little surprised if it came to that. Either the chip has been hopelessly damaged, or you can recover with ICSP programming.

@NickGammon the 12v is going through a 1k resistor. The 5v would rise by no more than a volt. Now for the math (correct me if I'm wrong); The 328 uses at least 5mA (5v @8Mhz), which is equivalent to a 1k resistor (R=V/I). So together with the 1k on the reset line, it would create a voltage divider, giving 6v at the VCC point. 6v is just with the maximum ratings. If there is anything else in the circuit using current, it would be even lower than 6v. Or just add a 2.5k resistor between vcc and gnd to get exactly 5v. Pretty interesting point you made. Quite a brain-breaker to figure out.

Yes, that might work. I think I like the idea of the 2.5 k resistor in case the processor uses less power at some point. Indeed, the fluctuations in power during programming mode (if there are any) might be amplified by this 12 V effect. You also would need to solder onto XTAL1 which is not broken out to a pin. Again, though, I would try ICSP programming first. Much simpler to do, and there is no real proof at this stage that whatever-it-is that is wrong could be fixed by high-voltage programming but not ICSP programming.

If it comes to the high-voltage programming I would cut the trace to the resistor. That would be safest. In any case the chip has an internal pull-up. You would have the issue of the reset button not working afterwards, though. The suggestion by @IgorStoppa about the male header is probably a good compromise.

https://www.sparkfun.com/news/1629
Maybe your windows update has installed new drivers for your FTDI chip.
You can check that your usb device PID is set to 0x0000
(You probably have the "Gravitech Nano V3.0" (with FTDI chip on the back)? I have, and this worked for me.)
In this case, you should download M_PROG from FTDI
And then check for the chip, when found, you set the PID to FTDI default (0x6001).
Then simply press program, and it will re-set your device PID.
Also, you should download the "CDM-v2.12.00-WHQL-Certified.zip" drivers.
Another source


text:
Leonardo sketch and bootloader hex file combination
Can I combine Leonardo sketch hex file with the Leonardo bootloader hex file?
I would like to program blank Atmega32U4 with one shot.

Yes you can, and there are programs available to download that will allow you to combine .HEX files.  Ask google. The magic term is "Intel I8HEX". or "Intel HEX"


text:
Where are the Arduino Due registers?
Having most of my experience on ATmega chips, and just starting up with Arduino (to reduce hardware development time) I'm happy to see that the usual registers such as TIMSK0, PCICR, TCNT1H and others can be used from the Arduino IDE just as they appear in the Atmel datasheet.
Migrating to the Arduino Due, however, came with a shock: the registers specified in the datasheet of the Cortex-M3 are not recognized by the Arduino IDE (although I downloaded the extension necessary for being able to select the Due). I wanted to do something very simple, like configuring a timer. I found TC_CMR0 in the datasheet, but the Arduino IDE doesn't recognize it. I found an example using the Arduino Due with timers in an obscure forum, and they used REG_PWM_CMR0. I tried it in the Arduino IDE, and it was accepted by the compiler.
I searched the Arduino and other forums, and couldn't find any hint whatsoever about the naming of the registers. Why are the names of the registers different? And can I find a conclusive documentation about the register names, or am I doomed to research each and every one of the hundreds of registers individually?

When I read the title I thought "like all the microcontrollers, they are just there, inside the package"

There are a few files in the Arduino Due core that you should have a look at. They give great insight into the SAM register set up; variant.h, variant.cpp and chip.h
After that you can dive into the libsam and the many components (include/source).
The SAM code has a very different structure and style compared to AVR.
Cheers!

I found almost everything I needed to know from the CPUs datasheet here.  I got the link from the Due page on the Arduino website.
For all the registers I was interested in, in my case the Parallel IO registers, it seems to be the case that the Arduino library names them the same as the datasheet, but prepended with "REG_" so PIOC_OWDR (Output Write Disable Reg for PIO port C) becomes REG_PIOC_OWDR.
In addition to finding the register names, the datasheet obviously contains a lot more useful information about how the CPU works and how to get the most out of it.
I also found the header files in the Arduino library (arduino\hardware\sam\1.6.4\system\CMSIS\Device\ATMEL\sam3xa\include\instance\instance_pioc.h for the example above) to be good places to look up what the registers are called.

i used the same datasheet you linked, and I also realized that the Arduino names are usually prepended with "REG_", but that's not always the case. For example, the TC_CMR didn't become REG_TC_CMR

I'd suggest looking in the folder I mentioned then to find the include file relevant to the timers to get clues for what you are looking for.

This is where a recursive grep -R of the arduino installation directory can be really handy...

The Arduino Due files you are after are located here on a Windows PC:
 C:\Users\name\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.11\system\CMSIS\Device\ATMEL\sam3xa\include\component


text:
Issues with Stacking Ethernet shield and USB Host shield
I want to stack Ethernet shield and USB host together with my Arduino MEGA 2560.
Each of these shields works fine separately.
Is it necessary to contact bootloader pins with each shield and arduino board?
I have connected and tried, but the problem exists.
only one shield works fine at once.(always the sheild that directly connect to the Arduino board).
How do I resolve this problem ? I want to work all 2 shields at once.
these are the sheilds I have used.

Circuits At Home USB Host Shield v2.0
Ethernet Shield v5.0

Thank you

Both shields are SPI devices, and both shields seem to be hard-wired to use D10 as the chip select line.
In order for you to use both shields at once you will have to either modify one of them or connect the shield via jumper wires.
You will need to change the chip select connection on one of the shields from D10 to some other pin that is not currently used, and then modify your software (or the library) accordingly.

Do I have to Modify D10 from one of the shields and as well as change the library? can't I resolve it just by changing the library.

You HAVE to somehow re-route D10 on one of the shields.  You also HAVE to inform the software that it's no longer using D10 but some other pin.  Some libraries provide the ability to pass the CS (or SS if you prefer) pin when constructing the object, and some are hard coded.  If the former you just change the pin number in your sketch. If the latter then you need to change the pin number in the library itself.

Also, I think that there is an hardware bug on the USB Master shield: IC3, the 3-state buffer which converts MISO to 5V, is always active... The enable pin of this 74LVC1G125 (pin 1) should be connected to the pin ss_3V3. Then you can stack this shield with another one.


text:
USB and UART simultaneous power to Arduino?
I am connecting an Arduino Mega (Crius) to a Intel Embedded processor (Minnowboard) via the following to Peripherals:

Minnowboard USB            -> Arduino      (to flash the micro-controller)
Minnowbaord Highspeed UART -> Arduino UART (to communicate)

Now both the peripherals are supplying +5V Vcc to the Arduino from the Minnowbaord but via different ports. Both the channels shall always remain connected.
Is it safe to power +5V from different ports to the Arduino (because i am technically bypassing all the voltage regulators available on board) ?
Will this cause any problems for the Arduino in regards to difference in voltage levels?

A UART connection does not normally provide power.  Some particular cables like those often found on FTDI USB converters might, but that's not actually part of the UART connection, but rather something passed through from the USB.

That's perfectly fine.  As it's the same 5V source the voltage should be the same and it'll just combine them together as if you had 2 wires in parallel.  However, if there are things like diodes in the path of one connection that causes the voltage to be slightly lower then the increased voltage imposed on the lower voltage side would reverse bias those diodes and end up cutting off that one source, so only one would be used.
So no, it's nothing to concern yourself over.


text:
5V+ Voltage to the arduino analog
If I connect a 12V / 12V+ battery to the arduino (uno) analog, will it be damaged ? What if I connect 230-240V to it ? Don't worry I haven't tried it yet. :D
Thanks in advance.

Yes, it will be damaged.  Especially if you connect mains direct to it.
The Arduino is designed to take up to 5V on any of its IO pins.  Any more than that is asking for trouble.  A slight amount above (as in say 5.5V) is usually tolerated OK, but anything more than that WILL cause irreparable damage.
And with mains, maybe even death.
For low DC voltages, like +12V, you can use a voltage divider to reduce the voltage to a 0-5V range.
For mains you will need to first reduce it down massively to a safe level (for example through a transformer) then re-scale and adjust it from there.  Note that mains is AC not DC so it has a negative value of voltage as well, so you will either need to rectify and smooth it to create a DC voltage or, if you are interested in the waveform itself, reduce the voltage even more and add a DC offset into it to move the mid-point of the AC waveform up to around 2.5V.

The inputs have clamping diodes, so you can put more that 5.5v on them, but you have to limit the current of the diodes will burn up. Adding a high value resistor between the higher voltage and input will do this. However, every voltage higher than 5v will give the same analog value as 5v does.

@Gerben More than 5.5V violates the absolute maximum ratings. Lack of Death is not guaranteed. . > 5V when operating violates the operating conditions - walking funny until powered off and on again may happen.

For the 12 V battery, let's assume it might get up to 15 to 20 V when charging, so we need a voltage divider to divide that down.

The zener diode is there to clamp the input to no more than 5.1 V in case of spikes or other damaging things on the input.
The voltage divider will divide down to 25% of the input, ie.
output = R2 / (R1 + R2) = 10 / (30 + 10) = 0.25

So now if you measure 5 V on the analog input you know you have 20 V on the battery. Thus you can scale your calculations appropriately.
(A more common value would be a 33 k resistor, in which case redo the calculation and scale accordingly).

For 240 V I strongly advise against trying something like that with bigger resistors. For one thing, 240 V RMS will have 240 * sqrt (2) = 340 V peak to peak. And that is both negative and positive.
A suitable approach would be to run through a small transformer, which will reduce the voltage and also isolate you from (almost) certain death.
In addition to that you would need to rectify the resulting voltage (say, 12 V) so that you don't put negative voltages into your input pin. And on top of that filter it so smooth out the peaks and troughs.


text:
Bluetooth not transmitting refreshed sensor values
I have a 9 DOF sensor attached to a BLE chip and Arduino Uno. I want to send the position measurements (i.e. x, y and z coordinates) from the sensor to my iPhone app (Bluefruit LE). The code below starts off well and I am able to see the coordinates on the iPhone. But after showing 6 sets of x-y-z coordinates on the phone all it prints are the x-coordinates. The y and z coordinates do not get shown on the phone at all. I have put the code below (likely not the most efficient code). Any suggestions on how to fix it will be very helpful. thanks in advance.
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BNO055.h>
#include <utility/imumaths.h>
#include <SPI.h>
#include "Adafruit_BLE_UART.h"

/* Set the delay between fresh samples */
#define BNO055_SAMPLERATE_DELAY_MS (100)

#define ADAFRUITBLE_REQ 10
#define ADAFRUITBLE_RDY 2
#define ADAFRUITBLE_RST 9

Adafruit_BNO055 bno = Adafruit_BNO055(55);
Adafruit_BLE_UART BTLEserial = Adafruit_BLE_UART(ADAFRUITBLE_REQ,     ADAFRUITBLE_RDY, ADAFRUITBLE_RST);

void displaySensorDetails(void)
{
sensor_t sensor;
bno.getSensor(&sensor);
Serial.println("------------------------------------");
Serial.print  ("Sensor:       "); Serial.println(sensor.name);
Serial.print  ("Driver Ver:   "); Serial.println(sensor.version);
Serial.print  ("Unique ID:    "); Serial.println(sensor.sensor_id);
Serial.print  ("Max Value:    "); Serial.print(sensor.max_value);
Serial.print  ("Min Value:    "); Serial.print(sensor.min_value);
Serial.print  ("Resolution:   "); Serial.print(sensor.resolution);
Serial.println("------------------------------------");
Serial.println("");
delay(500);
}

/*
Arduino setup function (automatically called at startup)
*/

int x = 0;
int row = 0;
void setup(void)
{
Serial.begin(9600);
Serial.println("Orientation Sensor Test"); Serial.println("");
Serial.println("CLEARDATA");
Serial.println("LABEL,x,y,z");

/* Initialise the sensor */
if(!bno.begin())
{
/* There was a problem detecting the BNO055 ... check your connections */
Serial.print("Ooops, no BNO055 detected ... Check your wiring or I2C ADDR!");
while(1);
}

delay(1000);

/* Display some basic information on this sensor */
displaySensorDetails();
bno.setExtCrystalUse(true);

BTLEserial.begin();

}

aci_evt_opcode_t laststatus = ACI_EVT_DISCONNECTED;

void loop(void)
{

BTLEserial.pollACI();

/* Get a new sensor event */
sensors_event_t event;
bno.getEvent(&event);

/* Display the floating point data */

Serial.print("X: ");
Serial.print(event.orientation.x, 4);
Serial.print("\tY: ");
Serial.print(event.orientation.y, 4);
Serial.print("\tZ: ");
Serial.print(event.orientation.z, 4);
Serial.println("");

/* This is the code that sends x, y and z coordinates to BLE */
  uint8_t sendbuffernew_x[20];
  char buff_x[20] = "";
  String xorient = "";
  dtostrf(event.orientation.x, 4, 1, buff_x);  //4 is mininum width, 6 is precision
  xorient += buff_x;

  xorient.getBytes(sendbuffernew_x, 20);
  char sendbuffersizenew_x = min(20, xorient.length());

  // write the data
  BTLEserial.write(sendbuffernew_x, sendbuffersizenew_x);
  memset(sendbuffernew_x, 0, sizeof(sendbuffernew_x));

  uint8_t sendbuffernew_y[20];
  char buff_y[20]= "";
  String yorient = "";
  dtostrf(event.orientation.y, 4, 1, buff_y);  //4 is mininum width, 6 is precision
  yorient += buff_y;

  yorient.getBytes(sendbuffernew_y, 20);
  char sendbuffersizenew_y = min(20, yorient.length());

  // write the data
  BTLEserial.write(sendbuffernew_y, sendbuffersizenew_y);
  memset(sendbuffernew_y, 0, sizeof(sendbuffernew_y));

  uint8_t sendbuffernew_z[20];
  char buff_z[20]="";
  String zorient = "";
  dtostrf(event.orientation.z, 4, 1, buff_z);  //4 is mininum width, 6 is precision
  zorient += buff_z;

  zorient.getBytes(sendbuffernew_z, 20);
  char sendbuffersizenew_z = min(20, zorient.length());

  // write the data
  BTLEserial.write(sendbuffernew_z, sendbuffersizenew_z);
  memset(sendbuffernew_z, 0, sizeof(sendbuffernew_z));

delay(1000);

delay(BNO055_SAMPLERATE_DELAY_MS);
}

Voting to close as this has sat for over a year without any effort on your part to clarify or work the issue.  The problem could be so many things; if you find yourself wanting to solve it, it would be good to obtain a distinct USB-serial converter and connect the transmit data line from the Arduino to the BTLE to the receive line of that, as well as connect the grounds (do not connect the other serial line).  Then you can use a terminal or the serial monitor to see what the Arduino is actually sending, and so determine if this is an Arduino problem, a BTLE problem, or maybe even an iOS one.

That's an incredibly complex way of outputting a floating point number as a string. You may possibly be fragmenting RAM with your use of String, and those String additions. Try replacing:
  uint8_t sendbuffernew_x[20];
  char buff_x[20] = "";
  String xorient = "";
  dtostrf(event.orientation.x, 4, 1, buff_x);  //4 is mininum width, 6 is precision
  xorient += buff_x;

  xorient.getBytes(sendbuffernew_x, 20);
  char sendbuffersizenew_x = min(20, xorient.length());

  // write the data
  BTLEserial.write(sendbuffernew_x, sendbuffersizenew_x);
  memset(sendbuffernew_x, 0, sizeof(sendbuffernew_x));

  uint8_t sendbuffernew_y[20];
  char buff_y[20]= "";
  String yorient = "";
  dtostrf(event.orientation.y, 4, 1, buff_y);  //4 is mininum width, 6 is precision
  yorient += buff_y;

  yorient.getBytes(sendbuffernew_y, 20);
  char sendbuffersizenew_y = min(20, yorient.length());

  // write the data
  BTLEserial.write(sendbuffernew_y, sendbuffersizenew_y);
  memset(sendbuffernew_y, 0, sizeof(sendbuffernew_y));

  uint8_t sendbuffernew_z[20];
  char buff_z[20]="";
  String zorient = "";
  dtostrf(event.orientation.z, 4, 1, buff_z);  //4 is mininum width, 6 is precision
  zorient += buff_z;

  zorient.getBytes(sendbuffernew_z, 20);
  char sendbuffersizenew_z = min(20, zorient.length());

  // write the data
  BTLEserial.write(sendbuffernew_z, sendbuffersizenew_z);
  memset(sendbuffernew_z, 0, sizeof(sendbuffernew_z));

by:
  char buff[10];

  dtostrf(event.orientation.x, 4, 1, buff);
  BTLEserial.write(buff, strlen (buff));
  dtostrf(event.orientation.y, 4, 1, buff);
  BTLEserial.write(buff, strlen (buff));
  dtostrf(event.orientation.z, 4, 1, buff);
  BTLEserial.write(buff, strlen (buff));


text:
Powering 30+ LEDs and flickering one at random
I'd like to power 30+ LEDs, while having a single LED (at random) flicker every 10-15 seconds.
Is this possible to do using an Arduino? I totally new to this so please bear with me.
This is the type of flicker effect I'm hoping to achieve: https://www.youtube.com/watch?v=753-lkao8l0
Many thanks

Yes, it is. How much money and board space are you willing to throw at it?

@IgnacioVazquez-Abrams Preferably <$100. Space isn't an issue.

Do you mean have 29 LEDs on, and the 30th flicker? Or 29 LEDs off, and one flicker (but only one at a time)?

@NickGammon Thanks for the extremely detailed reply. I mean 29 LEDs on, while the 30th flickers.

OK, that was what my test did. The code I presented had a rather simple flicker effect, but if you worked through an array of on/off times you could probably have quite complex flickering.

Yes, it is possible, but it's harder than making one LED light up, and then doing the other 29 the same.
An LED typically draws 20mA, which is within the limit for an Arduino pin (40mA); however, there is also a 200mA limit for all pins together, so you cannot power more than 10 LEDs off the same arduino. Also, the Arduino only has 13 digital pins, and 5 analog pins, a total of 18 pins. This includes 2 pins used for programming your Arduino.
If you want to run lots of LEDs, the easiest way is running it through an external chip. You can buy a pre-made board e.g. https://www.adafruit.com/products/1429 (24 channel, these can be daisy-chained together for more than 24 LEDs).
Alternatively, you can save yourself some money if you can just buy the chip - a DIP chip, or through-hole, will slot directly into a solderless breadboard, and can be soldered onto veroboard later to make your project more permanent.
There are a number of chips that will do the job, you want an "LED PWM driver" chip - for example, the TLC5940. There is a tutorial for this at http://tronixstuff.com/2013/10/21/tutorial-arduino-tlc5940-led-driver-ic/ - PWM just means you can control the brightness of each LED (individually).
If you want to make your project more permanent, you can solder a board of your own - find someone who can solder (your local makerspace/hackspace will be glad to help, I'm sure!) to teach you the basics, don't burn yourself. The easiest way is to use stripboard (aka Veroboard), this also means you can solder the resistors on to the same board (the LEDs too, if you like!). It sounds very intimidating, but it's not hard to learn. You can then buy PWM chips (make sure you get through-hole, aka "DIP" chips - https://en.wikipedia.org/wiki/Dual_in-line_package ) rather than "surface mount" chips. The chips are sensitive to heat, so to start you might want to solder on sockets (see same wiki page), then you can slot the chips in later.
You should consider very carefully your power supply - find out how many milliamps (or amps) it can provide - every (lit) LED will draw 20 milliAmps, and the Arduino is rated for 200mA, so if you want more than 9 LEDs, you will want an external power source, with an appropriate rating - 500mA = 0.5 amp will drive 24 LEDs. In this case, do NOT use the 2.1mm jack on the Arduino to power it; the transformer will overheat.
P.S. - you will be able to control the exact brightness of each LED independently. Also, if you use RGB leds, and use 3 pins on the IC to drive each LED, then you will be able to control the exact colour of each LED too!
Good luck!

I've successfully set up a flickering test with 32 LEDs, based on Using a 74HC595 output shift register as a port-expander.

Demo of the overall speed (but not the flickering effect): Vimeo - Shift Register Demo with 32 LEDs
That uses 4 x 74HC595, 32 LEDs, and 32 resistors, plus some decoupling capacitors.
Test sketch which does flicker one and leave the rest alone:
#include <SPI.h>
const byte LATCH = 10;
const byte numberOfChips = 4;
byte LEDdata [numberOfChips];  // initial pattern

void refreshLEDs ()
  {
  digitalWrite (LATCH, LOW);
  for (byte i = 0; i < numberOfChips; i++)
    SPI.transfer (LEDdata [i]);
  digitalWrite (LATCH, HIGH);
  } // end of refreshLEDs

void setup ()
{
  SPI.begin ();
}  // end of setup

void showPattern (unsigned long patt)
  {
  LEDdata [0] = patt & 0xFF;
  LEDdata [1] = (patt >> 8) & 0xFF;
  LEDdata [2] = (patt >> 16) & 0xFF;
  LEDdata [3] = (patt >> 24) & 0xFF;
  refreshLEDs ();
  } // end of showPattern

const int whichFlicker = 12;  // which LED to toggle
unsigned long pattern = 0xFFFFFFFF;  // pattern for other LEDs

void loop ()
{
  pattern ^= 1UL << whichFlicker;
  showPattern (pattern);
  delay (100);
  pattern ^= 1UL << whichFlicker;
  showPattern (pattern);
  delay (20);
}  // end of loop

The flickering is quite fast, but it isn't PWM. If you make the delays lower, the flickering just becomes a duller light, so I think by getting the timing right you could get flickering going fine.
The wiring (in part) is:
The rest is similar. Of course, you need current-limiting resistors for the LEDs (one each).
You can get the 595 chips from eBay for around $US 1.70 for 20 of them. LEDs are cheap. Resistors are cheap.

The other answers use other components to achieve more LEDs. Part of an led is its a diode. You can use this property to link 2 LEDs together and use a high or a low signal to light one. This has a limitation that you can't light both at the same time. But with lighting both for 50% of the time with a short time between each cycle will illuminate both of them. ( though obviously not as bright as if they were powered 100% of the time. )
This idea can be extended into a grid to get more LEDs per pin
Though not an ardiuino its the same chip using the technique mentioned here
http://www.nerdkits.com/videos/ledarray2/

Here is an example of a project that simultaneously drives 40 individually controllable LEDs directly connected to an ATTINY...
http://ognite.com
The same technique would also work directly connecting LEDs to the Arduino IO pins.


text:
How to mimic soft-power button in inexpensive toys & flashlights?
My kids have a few odd inexpensive toys with a soft push-button that will turn on the toy, and subsequent pushes change the toy's mode of operation in some fashon.  A flashlight comes to mind, where the button is pushed once and it turns on, push again and it blinks, and a 3rd time and the light turns off.
I've looked inside one of these flashlights, and there's a small blob covering some IC, what looks to be a diode, and the usual connections for the batteries and lights.
How do these circuits "work" without immediately draining the batteries?  I'm looking to mimic this behaviour on a battery powered arduino Uno (or possibly Pro Mini).
What comes to mind is that the button is on an interrupt line, which wakes the system up from some sleep state..  when the button cycles around to an "off" state, the system goes back to sleep.

I have a lengthy write-up about saving power at Power saving techniques for microprocessors.
One of the sample sketches on that page (Sketch J) does what you ask:
#include <avr/sleep.h>

const byte LED = 9;

void wake ()
{
  // cancel sleep as a precaution
  sleep_disable();
  // precaution while we are doing other things
  detachInterrupt (0);
}  // end of wake

void setup ()
  {
  digitalWrite (2, HIGH);  // enable pull-up
  }  // end of setup

void loop ()
{

  pinMode (LED, OUTPUT);
  digitalWrite (LED, HIGH);
  delay (50);
  digitalWrite (LED, LOW);
  delay (50);
  pinMode (LED, INPUT);

  // disable ADC
  ADCSRA = 0;

  set_sleep_mode (SLEEP_MODE_PWR_DOWN);
  sleep_enable();

  // Do not interrupt before we go to sleep, or the
  // ISR will detach interrupts and we won't wake.
  noInterrupts ();

  // will be called when pin D2 goes low
  attachInterrupt (0, wake, FALLING);

  // turn off brown-out enable in software
  // BODS must be set to one and BODSE must be set to zero within four clock cycles
  MCUCR = bit (BODS) | bit (BODSE);
  // The BODS bit is automatically cleared after three clock cycles
  MCUCR = bit (BODS);

  // We are guaranteed that the sleep_cpu call will be done
  // as the processor executes the next instruction after
  // interrupts are turned on.
  interrupts ();  // one cycle
  sleep_cpu ();   // one cycle

  } // end of loop

According to when I tested that, it used 0.116 µA when asleep (116 nA). That is well below the rate at which batteries self-discharge.
Basically that code does what you described. It sleeps, when pin D2 goes low it wakes and flashes an LED.
I should point out though that any "development board" Arduino with a voltage regulator, USB interface, and power LED on it will consume considerably more power because of the current drain they consume.
For low-power applications you need the bare chip (with appropriate supporting circuitry, like decoupling capacitors).

Long time fan of your powersaving page, have posted it as an answer to many a question here :)

Thanks! I actually improved the above code today. First, I changed the LOW interrupt to FALLING, as we now know that a FALLING interrupt will wake the processor. And FALLING is better because if you hold the button down you don't get multiple interrupts. Also, I re-measured the idle power. My page had it as 0.35 µA, but with better testing equipment I now measure 0.116 µA. That's pretty low. :)

Wow, thanks!  Quite a comprehensive write-up on your site.  I'll do some learnin' on using a bare chip, instead of the Pro Mini or other boards.  Thanks again!

I have made a circuit in the past that does more or less this:

There are two switches in the diagram - the one on the top right turns the circuit on, and the one lower-middle turns it off. Once turned on, it will stay on until the bottom switch is pressed.
The two resistors bottom left, and the switch at the bottom, represent your Arduino.
Note that, this diagram is OUTSIDE the arduino - it provides power TO the Arduino (and any other components relating to your project). That is, the bottom of the 1MOhm resistor, and the bottom of the left transistor, connect to the power pin on the Arduino. Those two resistors don't literally, exist.
It works as follows: The transistors do pretty much all the work. Both transistors work as switches. At the start (as shown in the diagram), both transistors have the same voltage at the base, and the emitter (the top one +5v between top and center/left; the bottom one 0v between center/right and bottom). This turns both switches off, and preserves the status quo, and consuming nearly no power.
As soon as the switch at the top is closed, the base (center/right) of the lower transistor is pulled up to +5V, switches this transistor on, and power can flow from this collector to the emitter. This means power can flow through the TOP transistor from emitter (top) to base (center/left), switching on the TOP transistor. This allows power to flow from the emitter (top) to collector (bottom). This takes over from the pushbutton, keeping the bottom transistor on. This is the other stable state.
At this point, power goes to the Arduino (bottom two resistors, representing load, and bottom switch, which is one of the pins on the Arduino. This pin should be set to "high impedance" until the Arduino wants to switch itself off, then it should go low.
I built the top part of the circuit, with an LED for the bottom half (both switches were just wires), and it worked, but I'd have to consider what would happen if the arduino pin is high or low while the top button is being pressed.

Interesting. Can you measure the idle power consumption?

Don't know how. All the power for everything runs through the top transistor, so I guess it would be the leakage on an transistor at cutoff? On the other side of it, when powered up, it should run emitter -> collector through the top transistor, then through the base of the lower transistor, so there should be no resistance. I don't know how it would work in practice when switching on/off, and what happens when both switches are closed - I guess the resistor at the top would protect it?

The disadvantage of this technique is that it requires an external signal to activate it, since the arduino (or whatever else) gets NO power at all until fired up.

Don't know how. - set the whole thing up, then instead of connecting your power supply to the 5 V input point, connect via your multimeter in milliamps range. If you aren't sure of the technique, Google how to do current measurements - you don't want to blow the fuse in your meter.

I know how to measure power consumption, and I will try it, but my simulator shows in the picoamps. I guess the leakage of the top transistor at cutoff? I will experiment with my simulator when I get a chance. My simulator says the above circuit (off) leaks 15pA.

I should point out that the question was about a single button. Still, it's always interesting to experiment with low-power techniques. :)

Let us continue this discussion in chat.


text:
How do I make/get a odometer for a lunch box sized robot?
Say I have given the robot a map of the place, it needs to navigate it. I need a odometer to keep track of its current position in the map. I need it to be precise up to a cm.
Can I simply use the motor's RPM and the diameter of the wheel to calculate how much distance the robot has travelled, or is there any catch?
I searched Google and could not find any odometer small enough for my robot. Most of them are for bicycles.

Seems to work pretty well here: https://youtu.be/tZ3fpZFWHDM?t=453 (7:33)

I had the idea to use a computer mouse (optical) to do this - cheap, easily available. You would need two, if you want to be able to measure turning rate, one on the left and one on the right.
You don't even need the whole mouse - if you pull it apart you can ditch the case, the buttons, and about half the circuitry. You will need to do some hacking to figure out how it works, but I doubt you'll find a cheaper odometer that is anywhere near as accurate.
Note: I pulled one apart, then got distracted on another project, but I can't think of a reason why it wouldn't work.

This is brilliant! If I had 15 reputation I would have given a thumbs up.

Good idea. Saves using a wheel at all. :)

Would this be tracking the ground the same way your mouse tracks the desk in order to move the cursor?

Yes, tracking the ground. I don't know how it would work on uneven surfaces - the lens of a mouse is a little way off the desk, there doesn't seem to be more than 1mm leeway in that.

The circuitry for controlling this might be difficult. I've used photointerrupters with tabs on an axle to track RPM, but that doesn't account for slippage it's true. Dead reckoning is always tricky!

I think the catch is that the wheel will slip, particularly when starting up. The slightest slip and you are counting a rotation that didn't move the robot forwards. Also if it skids when stopping that is more movement that you didn't detect.
You are probably best off with a non-powered wheel (stuck out the side perhaps?) which has the task of only detecting movement. Perhaps put a rubber tire on it to get a good grip. You could connect a rotary encoder to the axle which could count the amount it has turned. There are rotary encoders which do not have friction (eg. optical or magnetic).
If the robot has some non-powered wheels (like a rear wheel) then that could be a good place to measure turns, as it wouldn't slip as much because it isn't under power. You might be able to detect the amount it has turned, for example if it had suitable holes that you could shine a light-detector through.
Alternatively if the area is small enough use a distance sensor (like a sonar) but that probably wouldn't be accurate enough.

I am thinking of using a sonar to calibrate the odometer every half a minute or so. The robot will use a pair of landmarks to determine its position then reset the odometer.


text:
How much numerical precision can the ESP8266 achieve?
Background: I am trying to port this solar tracker code by Gabriel Miller to run on the ESP8266. Now I'm not a particularly great coder, but I'd like to give it an honest try.
As of recently, the ESP8266 can be natively programmed using the Arduino IDE and code base. Which is pretty convenient.
SO. The solar tracker code written by Gabriel works on the Arduino Uno and the Arduino Mega. The Mega version of the code has a high-precision calculation library called 'BigNumber' to calculate the Sun's position in the sky to a pretty precise degree. My question is:
From what I've read, the ESP8266 is supposed to be a 32-bit microprocessor, so (I assume?) it should be able to handle high-precision numbers without using the BigNumber library; so, how do I check what's the highest numerical precision that the ESP8266 can support? That way I could theoretically just copy the equations over to the ported program rather than having to rewrite the BigNumber library.

If anyone with a better grasp of C code and Arduino and such wants to give it a shot, be my guest. Give a shoutout to the code author Gabriel Miller for creating a pretty awesome bit of Arduino code.

I ported the BigNumber library to the Arduino in 2012. The BigNumber library is based almost entirely on the GNU "bc" library. What it does is store numbers with arbitrary precision (ie. as large as you like, and with as many decimal places as you like).
For example, on the Uno you can calculate 3160 like this:
3^160 = 21847450052839212624230656502990235142567050104912751880812823948662932355201

Or, the square root of 2 to 100 decimal places:
sqrt(2) = 1.4142135623730950488016887242096980785696718753769480731766797379907324784621070388503875343276415727

It's up to you how many decimal places you want. However the trade-off is RAM and speed. The more precision, the more RAM and the slower it is.
A normal precision float (like on the Uno/Mega) has around 7 decimal digits of precision. A double float has around 16 decimal digits of precision. See Wikipedia - Floating point.
If the ESP8266 has a C++ compiler then you could probably convert the BigNumber library without too many issues. However if it supports double-precision floats you may not need to.

How do I check what's the highest numerical precision that the ESP8266 can support?

You may want to ask on the ESP8266 Community Forum - they may be able to give you a more helpful answer.

Reference

Arbitrary precision (big number) library port for Arduino
Source on Github

Hey, Nick, thanks for your reply! I believe it is a C++ compiler since it uses the Arduino code base, but I don't know the C language well enough to effectively port the library on my own. I tried including the BigNumber library in an empty arduino sketch and compiling and it put out about 8 errors in a single file “numbers.c” saying "undefined reference to ‘exit'" and “undefined reference to ‘ctype_ptr’”. That's all of the errors. I'm not sure how to clear that up.

I've posted in the ESP8266 forums. Waiting for a reply.

I asked at the ESP8266 forums and somebody got it working. All good! But, according to the creator of a solar tracker code, it might not really be necessary if the ESP8266 compiler is built to handle double-precision numbers. At any rate: Success!

There's not really any difference in numerical precision.  What you do get with 32-bit though is faster operations on larger data types.
For instance, to add two 32-bit numbers together (uint32_t) would take many operations on an 8-bit CPY, whereas on a 32-bit CPU it would just take a couple (only one to do the actual addition - a couple to load/save the values to memory).
One key difference, though, is that (to save space) the AVR system has double precision float values turned off and aliased to single precision float values.  This is purely a software feature and has nothing really to do with the hardware.  On 32-bit systems that is normally not done, so you can use double instead of float to increase precision.
However: While double is more accurate than float, it is still not precise.  All floating point values, regardless of precision, are only ever an approximation.  For that reason it is often preferred to use integer mathematics, and that is where libraries like BigNumber come in handy.  They allow you to (as the name suggests) work with much bigger numbers, which is good when dealing with integers when you want a high precision.
For instance, you could measure distance in km.  Say something is 18.329846283746km away.  You could store that as a single precision floating point value and it would end up as 18.329845428467.  As a double precision it would end up as 18.3298462837, which is closer, but still not right.
So you could represent it as meters instead of km.  So your 18.329846283746km would be 18329.846283746m.
How about if you represented it as mm instead?  18329846.283746mm
Say, why don't we go smaller?  Micrometers? 18329846283.746µm
I don't like that decimal point still.  What's smaller than µm? nanometers of course!  That would be 18,329,846,283,746nm.
Oh look, we have an integer value.  However that integer value is too big to fit in a 32-bit number even, which has a maximum of 4,294,967,295.  You could try using a 64-bit number (uint64_t) if the compiler you have supports it, which on both 8-bit and 32-bit systems would need multiple operations to work with (though less on the 32-bit), or you could use a library like BigNumber to deal with it all for you.
By using that method you start out by stating "I want to work in this fixed resolution and I want 100% precision within that resolution", rather than saying "I want to work with these values and I hope you'll get it vaguely right", which is far from ideal.
Also working with integer values is generally considerably faster than working with floating point values unless the CPU has a floating point unit available to do the heavy work for you.
So the difference between an 8-bit and a 32-bit system has nothing to do with the precision that is available to you, but everything to do with how fast operations at different precisions take to perform.

Clearly my learning material was lacking. This makes sense, I'd never thought about it like this. I generically assumed more bits = more precision which I guess is technically true but clearly not as simple as I thought. Thanks.


text:
SimpleAudioPlayer + sleep function
I have tested the SimpleAudioPlayer example.
https://www.arduino.cc/en/Tutorial/SimpleAudioPlayer
This works fine, but when I add a sleep(1000) at the end of the loop() function, the music sounds dismembered (second run).
void loop()
{
    // ... source from the example

    myFile.close();
    Serial.println("End of file. Thank you for listening!");

    sleep(1000);
}

Does anyone have any idea on how to resolve this?

sleep() is something different. You are probably want to use delay(1000) instead.
sleep() comes from libsam and is not very well documented for use within the Arduino environment. There is probably a conflicting timer or interrupt between sleep() and the Audio.h library. So sticking with delay() is probably your best option.


text:
How to send keyboard signals to two separate computers (arduino due)
The arduino due has 2 micro-usb ports that you can connect to two separate computers. I need to send different keyboard signals to each computer. How would I do this?

possible duplicate of Can the 2nd MCU on the UNO R3 be used for keyboard emulation?

Guess what the other USB connector on the Due is connected to. That's right, a ATmega16U2.

@IgnacioVazquez-Abrams except that is not what he is asking. He's asking "How to send keyboard signals to two separate computers" of which he has a theory that because it has two USB ports, this should be possible. Even if this isn't the case, the other answer doesn't answer his question.

@JakeC: It actually does. The answer is "reprogram the '16U2 to act as a keyboard". Communication between the SAM3X and the '16U2 is left as an exercise for the reader.

@IgnacioVazquez-Abrams But because it doesn't specifically address multiple computers, it doesn't fulfill the criteria of a duplicate question.

While the Arduino Due has two separate USB ports, only one of them is a native port accessible to the processor. The second port is only usable for programming, and is connected to a different and much smaller chip that handles the programming task.
To connect to multiple computers from an Arduino Due, you have two options:

You can reprogram the second MCU to allow it to connect to the computer as a keyboard. This method is tricky because it requires an external programmer for it to work.
You can use a software USB implementation such as V-USB to use regular digital pins to connect to the computer. This is also tricky because it requires a little electronic know how a few extra components to make this work.

Both options require a little something else to make it work, so you will have to pick based on what you feel more comfortable doing.

For one of them, use Keyboard as you normally would.
For the other, do whatever Can the 2nd MCU on the UNO R3 be used for keyboard emulation? tells you to do to reprogram the ATmega16U2 connected to the other USB connector.


text:
Newbie need help to make a motor run for a laser scanner and some questions
I am trying to make a laser scanner consisting of a webcam and a line laser scanner. I have tried to use a manual scanning (by hand) and has worked, but would now like to consider automating the laser rotation (upwards and downwards) as a higher accuracy entails a slow and smooth rotation.
I came across arduino a few weeks back and realised it could possibly help to make this a reality. From my limited readings so far, I have obtained an Arduino Uno and a motor shield that seems to be the essentials for my purpose.
I have a few queries that hopefully someone can help:

Do I need a stepper motor for slow rotations, instead of a normal brushed motor?
Do I need to connect the Arduino to computer to make it run? Can I run it off battery, if so, does it have an 'ON' button?
How long will a standard 9V battery last?
For the code, I thought of using the simple one here: Arduino Motor Shield Tutorial.
Would it be able to allow me to control the amount of rotation, speed and the ability to reverse its rotation?

Look at the rotating muktisided mirror and LASER unit from many LASER printers - avaialable at little cosr of free from junked machines. These do more or less exactly what you want. You may need to exchange their LASER with your but they have dome the mechanical work for you.

A servo motor would have a lot more control than a normal motor. You usually command them to go to one of the predefined steps (stops) by using a function call in the servo motor library.
You can run independently of the computer. Many people do this. Certainly you can run off a battery. It doesn't have an ON button, you normally would have this between your battery and the Uno (eg. built into the battery pack). Like this:

A 9 V battery? I wouldn't use one, especially to drive a motor. It won't last long. Get something like 3 x AA batteries in a battery holder.

To show you the idea, I have this servo motor (SG-5010) I got from Adafruit.
I measured it using about 200 mA of power when operating. Now, I looked up a typical Alkaline 9 V battery, and found that, consuming 200 mA, it lasts for around 400 mAh. Thus, you could say it would be good for two hours at that rate. Plus, the Arduino will take around 50 mA, so maybe less than two hours.

A smallish servo motor won't need a motor shield. The pictures on the linked page show ordinary brushed motors. A servo motor has 3 leads:

Power (eg. 5 V)
Gnd
Data

Make sure you connect the grounds together, but the power could go to a separate power pack. A bit depends on how much power your motor will use. The data goes to the Arduino for the information about which rotation point to step to.
You should be able, in code, to change the rotation position, forwards and backwards.

Are you confusing stepper motor with something else? Stepper motors typically have 4 leads, two for each coil. Perhaps you are thinking of a servo? Or perhaps a stepper with a built in controller?

Quite right. I had a brain fade then. A servo motor has 3 wires as I described. I've amended the post to correct that. Thanks. :)

Nick gives some great advice, I am trying to answer your questions more directly.

Do I need a stepper motor for slow rotations, instead of a normal brushed motor?

Many kinds of motors can be made to work.  I advise starting with the same type as in the Instructables you mention below.  You can change the speed with gears if the motor speed range is not good enough.

Do I need to connect the arduino to computer to make it run? Can I run it off battery, if so, does it have an 'ON' button?

You only need to connect the Arduino to a computer to load or change the program. The motor is probably your biggest battery user, I would connect it to a separate battery from the Arduino. One advantage of the servo motors Nick mentions is that they are used by model car and airplane enthusiasts and there are lots of motors, batteries and battery chargers available.

How long will a standard 9V battery last?

Not long!

For the code, I thought of using the simple one here: Arduino Motor Shield Tutorial. Would it be able to allow me to control the amount of rotation, speed and the ability to reverse its rotation?

I looked through this code and it should work well as long as you use the same type of motor. You may have to modify things if you need the stop and start points to be very precise, but this will get you started and is a big step beyond scanning by hand.