text:
Real Time Clock Module Reset
I just had a pretty simple question about the RTC Clock Modules, more specifically the DS3231 RTC. Once calibrated and running on my Arduino if I were to unplug it and plug it back in, will the time and everything reset and require another calibration, or will it work like a computer that, even when reset, retains the correct time and date. Thanks!

It depends if your module has a battery backup or not. A bare chip, by itself, will loose everything. That's why many breakout boards will have a small lithium cell on them to retain everything when the power is removed.

So it will be attatched to a breadboard and then attatched to the Arduino. If the main power supply to the Arduino, which is a external 5V battery source, you are saying it would be wise to also have another backup source just in case?

Like I said, it depends on your module. If you are building it from components, then yes you should provide a battery backup - like it shows you in the datasheet.

This is the module I will be using

That is what you have? Do you know what that big round silver thing is in the picture?

Brilliant. Sorry, long day. Thanks for the help.


text:
Peristaltic Pump Project
I am designing a peristaltic pump and need some advice for parts. I am using an Arduino Leonardo and also have an UNO and am planning on adding a temperature and pH sensor as well. I have two questions:
1) I am planning to use a Stepper Motor but am unsure if I should use the NEMA 17 or 23 or some other motor. I need a relatively "high" amount of torque maybe around 1 to 3 N-m.
2) Should I go with a Motor Shield or Motor Driver. I am currently looking at the Big Easy Driver or A4988 Bipolar Driver or the simple Arduino Motor Shield.
Does anyone know which of these would be best or have any suggestions? Thank you very much!

A lot of people like the Pololu stepper motor drivers. Especially in the DIY 3D printer scene. They are probably cheaper than an entire shield.

The specifications for each stepper motor varies, with the larger models having the greater torque. With great torque comes the requirement of great power. A quick search for nema 17 stepper motors finds the torque figures on the low side of your request, while the nema 23 motors display a greater range, including your figures.
The additional power requirements may exceed the capabilities of the Arduino Motor Shield (2a per channel, 4a max), while the A4988 board specifies up to 2a per coil. Also note that to achieve the use of the higher power levels, these boards will require heat sinks.
If you expect to require the higher figure for torque, consider to research for a driver board that has a greater power limit, "just in case".

Rule of thumb: work out your power requirement, double it, then add a bit :) You can never have too much headroom.

"NEMA 17"  etc. only designates the mechanical mounting specification, not the strength or other electrical specifications of the motor.

Thanks a bunch. I think I will go with a driver board like you said just to be safe.

source: Stack Exchange

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

sort: votes


text:
Port Not Being Found
Hey everyone I know this is a pretty common question, and I have read/tried almost everything on all the other posts here and on the arduino.cc forums, but I have been unable to fix my problem. Basically I have been using my Arduino Leonardo for a little over a month now for all sorts of things and have never had this issue with the Arduino not showing up under the port tab on the menu. I have no idea why this just started happening to me, I am using the same cable, etc, and was hoping someone could help me out. I am on a MacBook Pro by the way.
Thanks in advance.

Does the port appear for a few seconds when you press the reset button?

Okay I just tried, and no it does not.

Does the LED on the board "throb" (fade in and out) when you press reset?

Yes it does fade in and out.

Have you tried a new cable? Or tried the existing cable with another device? How about someone else's computer?

I have not, but I will right now. If it is any help, the "ON" LED is indeed shining bright, so there is a connection being made, it just seems that there is some error with the serial communication?

The ON LED just shows that there is power. USB has 4 wires - power and ground (fat wires) and two data wires (thin wires). It's more common for the thin data wires to break than the fatter power and ground wires.

Yeah so I just tried the connection on a Windows computer, and it the power came on again but the device was never registered. So is this a cable problem then, most likely?

Most likely - the cable is more fragile than the Arduino generally. Try the cable with your phone or something - or dig out a spare cable (you really should have a pile of them, everything needs them now).

Let us continue this discussion in chat.

If you have uploaded a sketch that doesn't use the serial port, then after a couple of seconds, the Leonardo won't show up in the ports list.
To upload a new sketch you need to press and release Reset a moment after the upload to the board starts.

I've been using Leonardos and other ATmega32U4 based boards for years and have never experienced anything like that.

@per1234 - I must admit that I can't reproduce it.

Try this...
Go to your Arduino IDE.
Under the Tools tab, go to "Board" and select Arduino Leonardo.
Then in the Tools tab, go to Port and check to see if a port is selected.
Use this link to try and find which Serial Port you should have: https://www.arduino.cc/en/Guide/MacOSX
Try plugging in the cable in different USB ports on your computer and see if the port number changes automatically.
Also, could you please say what peripherals or other things are connected to the arduino? Because for example, I know what using a Bluetooth slave with the Arduino while connected with the cable to your computer, doesn't let you upload your program. There could be similar problems to this.

Yeah so I have the Wireless SD Shield connected to it, but no XBEE Wifi Module. Other than that there is nothing.

I guess you should try disconnecting that before connecting the Arduino to your computer. And try all the USB ports on your computer to make sure they are working.

Just tried, still nothing. Also, my restart button no longer flashed the "L" LED, it simply lights it up as long as the button is depressed but no longer... @Majenko

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


text:
Is the C++ STL fully supported on Arduino?
I don't yet own an Arduino board to run code on, and as the title says, I'm curious if the C++ STL is fully supported on Arduino and already part of the Arduino IDE. The STL is probably the most efficient, fully tested, and resource-minimal (which is a slightly redundant phrase, as I already mentioned efficiency) publicly available C++ code out there, and would make life much easier to code for Arduino.
If the STL is not a part of Arduino IDE, then how to include specific libraries such as <algorithm> and <utility>? (I'm very tempted to ask "why isn't it included?" but that seems too broad.)

The problem with "efficient" is that it doesn't specify just how efficient it is; will it run well on a 16MHz device with only 2kiB of RAM?

and already part of the Arduino IDE - last time I looked it wasn't. Personally I like the STL, and think it should be included. Whether or not you can tolerate the overhead is surely a decision for the end-user? I installed the Maniacbug library fairly recently, and it seemed to work OK.

The STL is not a part of Arduino IDE.
Although efficient by desktop standards, the consensus is it doesn't fit comfortably in an Arduino's limited space.  That said, here's someone who seems to have done it:
https://github.com/maniacbug/StandardCplusplus
Check out the forks, they seem more up to date
01JUL24 UPDATE
Years later, I'd like to point out compelling alternatives:

etl https://github.com/ETLCPP/etl
my own estdlib https://github.com/malachi-iot/estdlib

I'm against this consensus :p so it's not really a consensus anymore? ;p it should be used wisely, but can be very powerfull/usefull. Not everything of it may work as well. But we used std::queue to create a message-queue which the Arduino would clear. In theory it could get overrun, but it's usually more space efficient as setting an fixed buffer. Because one needs to set the buffer big enough, but will end up always "using" the full memory of the buffer.

@Paul Could you please explain why you have a different perspective? I'm sure it's interesting/educational.

@Paul do you use the maniacbug version or a different flavor?  Please share.  STL looks interesting to me but its slight lean towards dynamic allocation and rtti shied many (including myself) from using it for AVR scenarios

I've edited my reply, basically making a fixed buffer for your storage is less space efficiënt as using a dynamic storage. You'll only get in trouble when you run out of memory though, and since dynamic, can be hard to predict. But in general should fail later.

It was actually in my seconden year, we used the GNU-GCC toolchain with, I believe AVR-GCC, avrdude and eclipse. But I don't know how we got stl, it seemed easy at that time

A thread with some other STL options & thoughts: https://forum.arduino.cc/index.php?topic=360116.0

I lost the toolchain, since I got a new laptop. Which I pity very badly, but I do have the code from that project. I'll check with some classmates, if they can find the document for setting up GCC for AVR with STL

But, I think it's worth trying, especially with the newer microcontrollers, with more ram. If you try it, it may actually work very well.

Even with limited RAM, if you try writing your own linked-list you may well find that you don't do a better job than the STL does.

Years later, but I'd like to point out compelling alternatives: etl (https://github.com/ETLCPP/etl) and my own estdlib (https://github.com/malachi-iot/estdlib)

The STL is not a part of Arduino IDE.
Another answer is mentioning https://github.com/maniacbug/StandardCplusplus although this library doesn't seem to be maintained anymore.
Maybe a better idea could be to try https://github.com/mike-matera/ArduinoSTL
It's a port of uClibc++ packaged as an Arduino library.

I've been using Mike Matara's Arduino STL and it has been working fine on my AVR based boards. However I just entered the ESP8266 world and no fun ... plenty of compile errors with a warning that says it's "compatible with AVR and SAMD but may be incompatible with ESP8266" Doh!.

STL is efficient on the platform it was designed for, which is personal computers and similar-scale devices, where allocating a single byte in the heap consumes a 4k memory page (that's several times as much as ALL Arduino RAM), and where array indexes can be efficiently replaced by pointers (8-bit microcontrollers need at least two commands to deal with a pointer). So no, it's not efficient with Arduino.
Think of quicksort algorithm - it performs very well on large lists, but is easily beaten by a simple sort if you need to sort an array of 5 elements. Being asymptotically efficient doesn't mean being efficient in every case.

Unless the library is re-written for AVR. In theory it will be better/more efficient as me trying to program a queue or priority queue in C. If you really need the behavior, you should atleast consider or try it.

I would personally use an AVR port of C++ STL which is on GitHub, and bother the people on GitHub if you've got a better implementation, this way we can make it work, instead of everyone choosing to create his own implementation ;) And since it's on GitHub (and may even have multiple contributors) and is aimed on AVR. It should perform reasonable and be reviewed by multiple. Which is probably better/faster as some self written code. But I agree on the part: "use with care". But not "don't use because the PC version will be no good.".

@Paul If STL were to be rewritten for AVR, it would automatically lose it's "fully tested / mature" status, wouldn't it?

Well, if you were to implement it yourself, it would automatically lose it's fully tested status aswell :p and if you collaborate on github, it's more fully tested as when you're doing it alone? (:

Plus, on stl being fully tested; yes it is, for PC. (:

The STL is not part of Arduino and no support for libstc++ from AVR.
My "answer" differences from Malachi at one point though, as explained in the comments.
I don't think you shouldn't, just because "most people say" that you shouldn't. There are a lot of people that even think you shouldn't use C++ at all.
The problem is that C++ (and C++ standard library) are very powerful and may be ported in a non-efficient way.

Why use libstdc++?
I think, however, that if you use it with care, it can be very usefull.
Let's say we've got two buffers, a send buffer and a receive buffer.
With C, you would store them in a fixed char array. In C++ you can use dynamic containers.
So in C, you'll use 2x 256 bytes of memory to save your messages. Any longer message won't fit.
In C++ you'll use only whatever bytes are needed at one point (plus some extra probably). And if you get a longer message, it will simply scale up.
If the C++ thing works for you, and just test it very very well, why not use it? On average, it will use less memory, since you don't assign all of it when it's not used. You will have a problem when your messages get too big, since your memory will overflow, often causing the microcontroller to reset. But if more buffers in your program are dynamic, one may leave some space for the other, etc. Effectively using the memory more efficient!
But, without dynamic allocation, it might be a little safer, since you've already claimed those pieces of memory, there is no way you can't use those pieces. Any message that is bigger, simply won't fit, but you can easily check on that. Another thing is that the C++ stl's you find, might not be as well optimalised for your architecture/microcontroller.
Also, creating your very own dynamic storage in C may cause even more problems than the C++ stl ;). And it's not like you have to use dynamic storage for everything, simply being able to do so is nice.

Current microcontrollers are also getting much more serious as the 8-bit Arduino's (328P). 20$ can get you a Teensy 3.2 which has 256K Flash Memory, 64K RAM so, in this case, dynamic memory can be very useful (if you are certain you always have enough memory left).
Also: All STM32F41xxx products embed: Up to 192 Kbytes of system SRAM including 64 Kbytes of CCM (core coupled memory) data RAM
By that, it can also be a very nice way to learn C++ and program in the same language as you do on the PC.
But keep in mind that on an 8-bit micro, you should check if your stl-functions don't give too much overhead.

How use C++ standard template library for AVR?
I've followed the blog from Andy Brown and now have iterators/string/vectors working in AtmelStudio.
Though I did get some errors, the first batch of errors included:
Error        '_M_deallocate' was not declared in this scope, and no declarations were found by argument-dependent lookup at the point of instantiation [-fpermissive]      D:\avr-stl\include\string    173
Message        declarations in dependent base 'std::_String_alloc_base<char, std::allocator<char>, true>' are not found by unqualified lookup        D:\avr-stl\include\string    173
Message        use 'this->_M_deallocate' instead     D:\avr-stl\include\string    173

This error actually explains itself; you should use this->_M_deallocate.
After that I got undefined reference to "operator new(unsigned int, void*). But I fixed it by including "pnew.cpp" right under #include <new>  in stl_construct.h which is weird, but it works.
(Piece of stl_construct.h)
#ifndef __SGI_STL_INTERNAL_CONSTRUCT_H
#define __SGI_STL_INTERNAL_CONSTRUCT_H

#include <new>
#include <pnew.cpp>

__STL_BEGIN_NAMESPACE

After checking some stuff on the internet, it indeed appears that static allocation is most often better than dynamic allocation. Since the problems (possible overflows, less control and heap fragmentation) are unlikely to weigh up against the benefits. BUT, that doesn't mean everyone should stop experimenting with it ;) and nor that it can't be usefull in some niche applications (thus it's not a bad thing to have it "installed").

Tough crowd, I don't think you deserve a negative for your answer!  Heap fragmentation is one of the main things that steer me away from dynamic memory on AVR.  However, on bigger chips I'm a fan - when used carefully.

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


text:
Calibrating ESC and then using it
i have 30Amp ESC which i can move motor by providing values ,
but i am unable to know what is the minimum and maximum throttle speed of the motor....
how to achieve that level of info through arduino,
although when i calibrate through Open pilot software ,it is able to calibrate and the minimum value is 1500ms ..
Also after calibrating it once , do i need to arm everytime before using ESC in the arduino program through serial input ?

What values? How do you provide them? What ESC? What everything basically...?

Used this code -
/*
Coded by Marjan Olesch
Sketch from Insctructables.com
Open source - do what you want with this code!
*/
#include <Servo.h>

int value = 0; // set values you need to zero

Servo firstESC, secondESC; //Create as much as Servoobject you want. You can controll 2 or more Servos at the same time

void setup() {

  firstESC.attach(9);    // attached to pin 9 I just do this with 1 Servo
  Serial.begin(9600);    // start serial at 9600 baud

}

void loop() {

//First connect your ESC WITHOUT Arming. Then Open Serial and follo Instructions

  firstESC.writeMicroseconds(value);

  if(Serial.available())
    value = Serial.parseInt();    // Parse an Integer from Serial

}

the problem was when i was connecting the battery , it was not making any sounds...it was already calibrated by open pilot GCS so it was not calibrating again... i needed to reset the ESC and then run this program from arduino

If this sketch solved you problem, you should accept the answer; If you tried this and are still stuck, it should put in an edit to your question.


text:
Interfacing pc mouse (serial port DB-9)
So I`ve got that mouse with serial connector. It is named serial so it should be easier to connect than even a ps2 mouse, right?
I can`t find any instruction on it. Or should I see instruction on ps2 mouse and plug in the same wires?
Btw mouse has only 4 wires connected inside, as usual PS2 mouse. I want to connect it the same way as ps2 mouse to get easy readings of rotary encoder.

UPD1: I`ve tried to connect it like a PS2 mouse according to this schema with no success. So either a mouse is dead or it uses some kind of different connection?

It might be easier, but you have to figure out how. For PS2 you can use copy-paste existing code, and get it to work in minutes.

A serial mouse is designed to connect to a PC's true serial port - it's an actual RS-232 device using ±5V. As such it won't connect directly to the Arduino's RX/TX pins, you'll have to go through an RS-232 transceiver chip.
It also gets its power from the RTS line, but I never knew what the current draw of one of those things was - be careful trying to power it from the Arduino!
Different mouse manufacturers used different protocols. The original standard used a three-byte protocol at 1,200 bps 7N1. The encoding had the following properties:

The leading bit of the first byte of the packet was set - all future bytes had the leading bit cleared.
The first byte had the buttons' states, and the most significant bits of the X and Y deltas;
The X delta was encoded in the second byte;
The Y delta was encoded in the third byte.

http://paulbourke.net/dataformats/serialmouse/

Other manufacturers added things like extra buttons and scroll wheels that didn't fit in the packet structure. So they modified the protocol, but stuck with some features of the original:

The data rate was (usually) still 1,200 bps, although sometimes they used 7N2 or 8N1 instead.
The leading bit was still used to indicate start of packet;
The X, Y (and Z) wheels still indicated deltas.

http://www.cpcwiki.eu/index.php/Serial_RS232_Mouse

Thanks for the answer! So I should get a grip on a RS-232 transceiver chip and serial mouse protocol. Fair enough.

If you really want to pursue it, but it would be easier all around to use a PS/2 mouse, not only electrically but because most Arduino's don't have a 2nd UART to spare, and implementing the PS/2 mouse synchronous signalling in software is small and more efficient that implementing a serial UART in software.


text:
Executing machine code at runtime Uno
I want to create a small single threaded os for my arduino.The first thing I want to do is to allow my arduino to read a section from flash/eeprom and execute it. I have some question regarding the memory. The microcontroller is executing one command at a time from..where? Does it directly acces the flash containing the code and take every command at a time?(that would be slow) Or does it first load the entire program into sram?(also wouldn't make sense because sram is 2k while flash is 32k). Either way,if I can find in sram /flash my code( or the header to some void) then i could jump there.Am i wrong?Is it possible(to do such os)?
Something like this:
uint16_t addr=0x1234;
void (*function)(void)=addr;
function();

(or maybe with some avr like assembly code?)

The microcontroller is executing one command at a time from..where?

Flash memory directly. The AVR core can only execute instructions from Flash memory. It uses a two-bus system known as Harvard Architecture, where the Instruction Bus is connected to Flash and is used to execute instructions, and the Data Bus is connected to SRAM, EEPROM, all the peripherals, GPIO pins, etc.
It is possible to jump to any location in memory in a similar way as you have depicted, but in order to know where you first need to know the functions you want to call.  You can get the address of any function and assign it to a pointer, and then call that pointer as a function, but what would that achieve? You may as well just call the function directly and save time. Unless you want to store the addresses of those functions in an array or something to maybe associate them with a command to trigger the execution of that function. In which case you don't need anything "fancy", just pointers to the functions you want to use.

I was thinking i could execute from sd card. Just find an empty sector in flash...write there the code from sd and then jump. I believe then this is possible right?

No, you can't. You can only write to the flash memory from code executed from the bootloader portion of flash (which means the bootloader has to do it), so you can't write to flash from your program. Also you'd wear out your flash pretty quick.

Basically you are going from Arduino to AVR :) (Still can use the same HW+IDE+such, but you overgrown Arduino's limits) Next step should be download datasheat for your AVR to study and have it handy and read it (not need to understand it yet (too much info), but to have some idea, what are you going to play with)

@Majenko: "...what would that achieve?..."  Actually, its a game-changer, as can be seen using 3-instruction Forth approach discussed here.  The key is to get the bootloaded code to do it (remote store, fetch, and call instructions), but requires a generic header/hook/container into which machine code can be injected dynamically.


text:
Adding slave device to Arduino Uno-SPI | Configuring pins
I recently started an oled project. I use a small "128X64 OLED LCD LED Display Module" and I control it using SPI protocol(with my Arduino).
It is the only device connected to the microcontroller. But I have some questions regarding the pins. I found this tutorial and it uses pins 9 as DATA(known as MOSI) and 10 as CLK( or SCK). But the datasheet for my microcontroller(328) shows that pin 11 is MOSI and 13 is CLK.
Obviously..it works. So I think the program provided by the adafruit(that I used-Adafruit_SSD1306) took care of MOSI and generated the clock impulses on pin 10.etc. . But then what are those pins on the board and why are called like that? I mean it seems to me that everyone can just use other pins for MOSI/CLK(at least).What is their purpose?
Question #2: What does DC (or D/C) means?
#define OLED_MOSI   9
#define OLED_CLK   10
#define OLED_DC    11
#define OLED_CS    12
#define OLED_RESET 13

VS

(328<=>128)

You can answer these questions by opening the library and looking "under the hood". This is the most beautiful advantage of open source projects.
Here are the links to the relevant files in the library, so I can comment on them.

INO example file
Library header file
Library source file

Ok, first of all let's have a look at the example. you can see that the constructor is called as
Adafruit_SSD1306 display(OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);

When looking at the lines 144 and following of the source file, you can see
hwSPI = false;

Wait, this means that it is not using the hardware SPI? Sure! In the following overload, then, you can see that if you call the constructor as Adafruit_SSD1306(int8_t DC, int8_t RST, int8_t CS), you will use the hwSPI.
Now, I'm not sure whether you know the difference between HW and SW implementations, so here they are. The HW implementation is a peripheral which can run "on its own" and provide the microcontroller the results (automatically send and/or receive the bytes). The SW one, on the other hand, is an emulation done by the microcontroller.
You can also see it in the example:
// If using software SPI (the default case):
#define OLED_MOSI   9
#define OLED_CLK   10
#define OLED_DC    11
#define OLED_CS    12
#define OLED_RESET 13
Adafruit_SSD1306 display(OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);

/* Uncomment this block to use hardware SPI
#define OLED_DC     6
#define OLED_CS     7
#define OLED_RESET  8
Adafruit_SSD1306 display(OLED_DC, OLED_RESET, OLED_CS);
*/

So you can use the second part to initialize a display which will use the hardware SPI (so MISO = 12, MOSI = 11, SCK = 13). If you want to free the microcontroller in order to be able to do other tasks, use the HW peripheral.
As fot the DC pin, it is labeled "DataCommand". I think it is a pin to tell the controller whether the data shared through the SPI port is a command or it is data


text:
Writing to flash Attiny 85
I set a project-goal for me: to make a very small compiler in Attiny.This compiler should read the code from user and translate it into code;then save it in some portion of the flash and jump there. I know this sounds impossible on Attiny85 but I want test self-programming. I read from various websites that the '85 does not have a "bootloader protection" like Atmga or Uno does. If it's true what are the functions used to write to the flash? (The only function I can thing of that access the flash is pgm_read_byte() but that is only for read).

There's an entire section in the datasheet devoted to this. Have you looked at it yet?

Maybe you can learn by reading and understanding an ATTiny85 bootloader, such as Micronucleus.

The datasheet contains a lot of information but I could not find code for writing to Flash (it is a long datasheet and I have no ideea what to look at so maybe I missed it). @Majenko ..yes that was my next step.Thank you.

The datasheet is written from a low-level perspective. If you were working with assembly it would be useful, but when programming in C you would be better with the AVR106 App Note

You could have a look at AmForth and how it writes to flash. http://amforth.sourceforge.net/

I understand assembly(I worked in nasm).Although there are some new instructions in thendatasheet(aleo in the bootloader).I'll have to study those

authors: พัฒนพงษ์ พุทธะ


text:
Using ATiny102 as HID device(emulating mouse)
I am trying to make my own mouse/keyboard from an attiny (it doesn't have to be attiny102 as the title suggests). I have read many articles on this subject: some are using v-usb library.But I understand this is for arduino uno/leonardo.I want to use an attiny with the least amount of electronic parts attached to it(no external oscillator-only the internal one..etc.). All the articles I read said that arduino can't be used as a host usb device but this applies only for it's built-in micro-usb. Can't I just emulate the HID device using digital pins on my attiny? If this is possible where can you provide some well-documented source for the protocol used when communicating with the pc?

Everything is documented on the V-USB website

Atmel Appnote AVR 309 is also a good read on the topic, though v-usb should get you there. And yes, emulating a HID device using GPIO is exactly the thing. And no, this is not about the AVR being a USB host. As posted now the question seems to be a little broad, i.e. there is no specific question here besides "please guide me to some documentation". IMO such questions are not well suited for good StackExchange answers. Maybe it would be better if you research the topic a little more and post more distinct questions along the way.

Don't know anything about the '102 but this is likely achievable in ideal cases with software USB on an ATtiny85.  However, the implementation is unlikely to fully comply with USB specifications so may not work everywhere.  Devices with a dedicated USB host interface and phy should fix that.

I have build a HID midi keyboard with the hiduino lib which is base on LUFA.
http://code.google.com/p/hiduino/w/list
I know LUFA is also capable to build a HID mouse device. But you need to switch to a bigger controller (i think). I used a 8u2 from atmel.
I used AVR Studio 6 to compile hiduino.
Currently i have no link to the LUFA because the git page is gone. Maybe you find a mirror or a other webpage.

the only USB option for AVR microcontrollers without embedded USB, is VUSB which is somehow rare in Arduino; despite some aged libraries around :
https://blog.petrockblock.com/2012/05/19/usb-keyboard-with-arduino-and-v-usb-library-an-example/
https://github.com/gloob/vusb-for-arduino
but if you can rely on atmel studio, the very rich examples of VUSB itself are enough. I made a HID presenter (just two keys to go back and forth on powerpoint slides) using only an attiny24 which is super cheap. the codeandlife blog is a good start for VUSB. it also has a HID mouse example explained :
http://codeandlife.com/2012/02/11/v-usb-tutorial-continued-hid-mouse/


text:
Digispark - Bootloader stuck
I have a digispark that I want to reprogram, soldered into a circuit. I have burned the default t85 micronucleus firmware.
This is the command I used:
"C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude" -C "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf" -v -pattiny85 -cstk500v1 -PCOM4 -b19200 -Uflash:w:D:\Documents\micronucleus-master\firmware\releases\t85_default.hex:i

avrdude: Version 6.3, compiled on Sep 12 2016 at 17:24:16
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM4
         Using Programmer              : stk500v1
         Overriding Baud Rate          : 19200
         AVR Part                      : ATtiny85
         Chip Erase delay              : 400000 us
         PAGEL                         : P00
         BS2                           : P00
         RESET disposition             : possible i/o
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    12     4    0 no        512    4      0  4000  4500 0xff 0xff
           flash         65     6    32    0 yes      8192   64    128 30000 30000 0xff 0xff
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00

         Programmer Type : STK500
         Description     : Atmel STK500 Version 1.x firmware
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.03s

avrdude: Device signature = 0x1e930b (probably t85)
avrdude: safemode: hfuse reads as D7
avrdude: safemode: efuse reads as FF
avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
         To disable this feature, specify the -D option.
avrdude: erasing chip
avrdude: reading input file "D:\Documents\micronucleus-master\firmware\releases\t85_default.hex"
avrdude: writing flash (8116 bytes):

Writing | ################################################## | 100% 0.07s

avrdude: 8116 bytes of flash written
avrdude: verifying flash memory against D:\Documents\micronucleus-master\firmware\releases\t85_default.hex:
avrdude: load data flash data from input file D:\Documents\micronucleus-master\firmware\releases\t85_default.hex:
avrdude: input file D:\Documents\micronucleus-master\firmware\releases\t85_default.hex contains 8116 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 0.07s

avrdude: verifying ...
avrdude: 8116 bytes of flash verified

avrdude: safemode: hfuse reads as D7
avrdude: safemode: efuse reads as FF
avrdude: safemode: Fuses OK (E:FF, H:D7, L:F1)

avrdude done.  Thank you.

I have not set any fuses (I hope the frequency is right.)
The board is recognized by my computer and I can program a sketch into it using Arduino IDE. Despite all this the program I burned into it does not run. It seems it is stuck into the bootloader section.
The sketch:
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(0, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(0, HIGH);
}

Pin PB0 has never a voltage bigger than 1.7V(noise or floating). All pins have similar voltages (except PB3,PB4 which are pulled up or high)
The schematic:

The circuit works. I tested both displays previously with the atiny which I directly programmed with the Uno. The upper right connector is directly plugged into the digispark with the following pins: VIN,GND,5V. The middle connector is also plugged into the digispark.
I have tried:

Powered by USB: I am afraid this will be detected by the bootloader and enter the programming state thus never running the schematic(shouldn't happen but you never know...)
Powered by VIN with a 9V battery. Nothing. All voltages are in check (5V pin has 5v on it. All other pins are floating)
Powered by 5V pin using an Arduino UNO as the source. Nothing.
In all cases the voltage on PB0 stays the same. It varies between 0.6V and 1.6V.

In Arduino IDE:

Tried Digispark 16.5Mhz
Digispark Pro 16Mhz
Digispark(No Usb) 16Mhz

Always a succesfull uploading.
Notes:

After uploading in Arduino this text comes up:

Starting the user app ...
  running: 100% complete

So it is supposed to run the program but the board actually resets because it gets renumerated by windows.
It's not quite possible to de-solder it and program the sketch directly with Arduino as ISP
I use Windows 10
Fuses used when I burned the micronucleus L:F1 H:D7 E:FF. These are the default "safe" values. The actual fuses needed by the firmware are L:E1 H:DD E:FE.
Difference in extended fuse: Self-programming is curently disabled...Is this the culprit?
I managed to desolder PB0,PB1 and PB2 from the back of the pcb. Now I can't program it directly with Arduino as ISP. The setup I have should work because I can easily program an t45. So it has something to do with the digispark. Checked the connection between pins and the actual MCU. The error I get is Yikes... and sometimes it finds an 0x00ff00 or other junk id for the board but probably it's because of misconnection.

Question #2:
In the current configuration(soldered) would it be possible to use again  Arduino as ISP to program it?  PB0,PB1,PB2 are connected to Serial Clock,Serial Data and Serial Storage Clock respectively. I am trying right now to set the right fuses but every time I get this:
avrdude -C "C:\Program Files (x86)\Arduino\hardware\tools\avr\etc\avrdude.conf" -c stk500v1 -p attiny85  -U lfuse:w:0xe1:m -U hfuse:w:0xdd:m -U efuse:w:0xfe:m -B 20 -b19200 -P COM7

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.06s

avrdude: Device signature = 0x000000 (retrying)

Reading | ################################################## | 100% 0.05s

avrdude: Device signature = 0x000000 (retrying)

Reading | ################################################## | 100% 0.05s

avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

avrdude done.  Thank you.

make: *** [fuse] Error 1

Your schematic needs some work. For example the connector(?) in the upper right corner, I can't tell what order the pins are in. I can't tell what the names of the resistors are (because they layer on top of each other). There are dangling wires (stubs) and it seems like a lot of spaghetti. There are no capacitors anywhere so that might be an issue.

The upper connector is for power. It is directly pulled into digispark. So is the middle connector. Digispark already provide the capacitors for the power. And yes..It still needs a lot of work. BUT the schematic works. Tested both screens with numbers by directly programming the attiny.

This is driving me crazy. Since I programmed this bootloader nothing works. I think it is software related because the board works..in its way. It is recognized by the pc, I can program it..but it executes nothing it should have.

have you read this? https://digistump.com/wiki/digispark/tutorials/connecting

I programmed the digisprk a hundred times before. It always worked.

Solved it! I don't know what the real issue was but I constructed a HV programmer and just blasted the digispark with the new and proper fuses. Now it works as it should.

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


text:
Find a time server for NTP to get the current time (EtherCard library)
There are lots of examples around how to connect with an NTP server, but I do not see how to find such an IP-address. From the examples I conclude I need to find it on for example pool.ntp.org, but I do not even see how to get IP-addresses out of there myself, let alone to let my Arduino do it. Of course I looked at the How do I use pool.ntp.org page, but it doesn't seem to say anything about finding IP-addresses.
Questions

Is it possible to let my Arduino find a working NTP server (using the EtherCard library), and if so, how?
All the examples I saw have an NTP server IP address hard coded, isn't that a bad practice and also a bad idea for a longer running project?

The code I currently find the easiest to understand is from the Arduino forum, and has an IP address hard coded.
I have an Arduino Nano ATmega328 with a ENC28j60 ethernet shield, and therefore use the EtherCard libray. I do know of existence of RTC devices but I would prefer NTP.

You need to perform a DNS lookup in order to convert the host name (e.g. "pool.ntp.org") into an IP address. Doesn't the EtherCard library have a facility for that?

@EdgarBonet That sounds logical, indeed EtherCard can do that, googling it it would be something like if (!ether.dnsLookup(website)) { Serial.println("DNS failed"); } ether.printIp("Server: ", ether.hisip); but I'm new to the ethernet connections so I need to find out how to get an ip address out of that to use later in the code...

I found an ip address with the code in the form of a string, but didn't manage to convert it to an array even with http://stackoverflow.com/questions/35227449/convert-ip-or-mac-address-from-string-to-byte-array-arduino-or-c so I'm leaving that for now. This question is solved I guess, although I am not sure of course if the ip is a correct one because I can't test it.

ether.hisip is not a string, it's an array of 4 bytes.

@EdgarBonet Oh indeed you are right! That solves my whole problem, thanks a lot! I was tricked into thinking it was a string by what ether.hisip printed to, but now I see that's why ether.printIP was used.

The EtherCard library offers a method called ether.dnsLookup(host) where you ask it to look up the IP address for you.
etherCard.dnsLookup("pool.ntp.org");

...only that might fail, so it returns a false:
if (!etherCard.dnsLookup("pool.ntp.org")) {
    // Error! Do something!
    return;
} // if

But if it works...
if (!etherCard.dnsLookup("pool.ntp.org")) {
    // Error! Do something!
    return;
} // if
// At this stage, dnsLookup() worked...

// Can now connect to IP adress in etherCard.hispip

Now: please note that ntp.org would prefer you to use a more precise locale than pool.ntp.org. If you're going to distribute your application worldwide, then that's fine. But I always use au.pool.ntp.org because I'm in the Australian region. There are others that you can/should use instead.

Thanks for writing Edgar's suggestion into an answer, the locale is a nice addition!


text:
Large values are changed by Arduino when viewing with `Serial.print()`
Why are (big) values being changed?
I tried out printing some values and noticed bigger values are changed more, they seem to be rounded to quarters and then to halves when the value gets bigger.
MWE
void setup() {
  Serial.begin(9600);
  Serial.print("12457591.51 is changed into ");
  Serial.println(12457591.51);
  Serial.print("2457591.80 is changed into ");
  Serial.println(2457591.80);
  Serial.print("1234567.89 is changed into ");
  Serial.println(1234567.89);
}

void loop() {}

gives me
12457591.51 is changed into 12457592.00
2457591.80 is changed into 2457591.75
1234567.89 is changed into 1234567.87

I'm working with an Arduino Nano ATMega328.
Background
I need the calculation (2457591.33 + 0.5 - 2440588)  * 60 * 60 * 24 to be precise to within preferably a hundred, but currently it's off by about 7000.

Floating point numbers doesn't have infinite precision. But you can always change your equation to use smaller numbers (preferably integers or longs as floating point is extremely slow)
For example on AVR Freaks they mentioned precision about 6 or 7 digits. It makes sense as 24bits signed number range is from -8388608 to 8388607

Of course they don't have infinite precision, but floats should have precision after the dot, right? I thought that's where floats were for. I don't mind speed at all but I understand ints or longs are better, so I'll try to convert the calculation to use longs. Do I understand correctly that the answer is that floats do not have precision when working with more than say 6 digits?

Only small numbers have some precision after the dot. Big ones doesn't have precision even before the dot.

Saw your edit, that makes sense, hadn't thought of that. Thanks!


text:
dns lookup only works with DHCP and not with static setup (EtherCard library)
When I use DHCP with ether.dhcpSetup() the DNS lookup for NTP ether.dnsLookup("0.pool.ntp.org") works fine, but when I use a static setup (because my Android app needs to know the IP address) with ether.staticSetup(myip); then this returns false and I don't get an IP address from the NTP pool. How come?
I have an Arduino Nano ATmega328 with a ENC28j60 ethernet shield, and therefore use the EtherCard libray.
Full MWE:
#include <EtherCard.h>      // https://github.com/jcw/ethercard
#include <Time.h>           // http://www.arduino.cc/playground/Code/Time

static byte mymac[] = { 0x74,0x69,0x69,0x2D,0x30,0x31 };
static byte myip[] = {192, 168, 2, 106};
const char poolNTP[] PROGMEM = "0.pool.ntp.org"; //pool to get time server from
uint8_t ntpMyPort = 123; //port for the time server, no idea why needed

byte Ethernet::buffer[700];

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

 //do not forget to add the extra '10' argument because of this ethernet shield
  if (ether.begin(sizeof Ethernet::buffer, mymac, 10) == 0) {
    Serial.println(F("Failed to access Ethernet controller"));
  }

  //static setup
  ether.staticSetup(myip);
  ether.printIp("Address: http://", ether.myip);

 //this works
//  if (!ether.dhcpSetup())
//    Serial.println(F("DHCP failed"));

  //Find ip address of a time server from the pool
  if (!ether.dnsLookup(poolNTP)) {
    Serial.println("DNS failed"); //with static setup this line is executed, not so with DHCP
  }
  ether.printIp("Lookup IP   : ", ether.hisip);
}

void loop () {}

I'd suspect gateway IP is not set and DHCP provides it.

@KIIV As John Burger suggested in his answer that's probably one mistake, but it's not solved yet even with adding dns ip as well (see comment there)

BTW: why don't you set fixed IP on your DHCP for this device? It could save you these troubles.

@KIIV Sounds good but what do you mean? The documentation says dhcpSetup() doesn't take any parameters, so no way to give it my ip?

You can set it on your router side.

DHCP does more than just give you your IP address: it also gives you the Net Mask, the Gateway IP address, and the DNS Server IP address. If you don't call dhcpSetup(), you'll have to do it yourself.
According to the EtherCard documentation, you can do that as follows:
const static uint8_t ip[] = {192,168,0,100}; // Example
const static uint8_t gw[] = {192,168,0,254}; // Example
const static uint8_t dns[] = {192,168,0,1};  // Example

...

if (!ether.staticSetup(ip, gw, dns)
{
    // handle failure to configure static IP address
    // (current implementation always returns true!)
}

Thanks! I didn't know DNS lookup needed more than my ip address. I found my Gateway ip through an ipconfig command (windows), I'm currently searching what the DNS server ip address should be.

I found the dns ip with doing a DHCP setup and then printing ether.dnsip, and when I print it again after the static setup the ip shows correctly but still the dns lookup fails. Any idea what misses more?

A second look at the documentation solved it! I just had to add the netmask as well, after printing it (after DHCP) with ether.netmask.

the documentation of ethercard.h and examples doesn't fit the actual version of ethercard very well.
for static ip setup use:
ether.staticSetup(myip, gwip, dnsip, netmask);

then the dnslookup works. most examples use the old mymask name, that is replaced by netmask


text:
Atmega328P burn bootloader with FTDI
I need your help.
I am using Arduino ProMini in my project.
In project board there is Atmega328P which doesn't have Arduino bootloader, and Atmega328P RXD, TXD pins are connected to FTDI Basic(sparkfun)'s TXD and RXD pins.
I searched on internet how to burn bootloader for arduino. Most of them use other Arduino's built in SPI or other method. Problem is Atmega328P is already assembled to PCB board and I cannot make any soldering or change. Atmega328 and FTDI basic are connected and assembled to upload sketch (if there is bootloader of Arduino inside of Atmega328P, no problem to upload sketch).
Is there any solution or suggestions to burn bootloader using FTDI?
Thank You.

You cannot upload the bootloader through the ATmega's UART pins, but the necessary pins (SPI & reset) are quite likely broken out on your board, and if not you may be able to tap them with some fine hookup wire long enough for the task.  Otherwise you may just have to desolder the chip.   A typical FTDI serial adapter is not the right tool for loading a bootloader either - it might at a stretch be adapted to very slowly toggling the ISP pins but the usual choices will require far less work on your part.

@ChrisStratton You should turn that into an answer

Every one of the dozens of Arduino Pro Mini I've ever tried to program came with the Arduino bootloader. Are you saying your Arduino Pro Mini somehow doesn't have a bootloader? Or are you saying that you know your FTDI adapter is working because you can upload your sketch to an Arduino Pro Mini, but you get an error message (quote it exactly please) when you upload the exact same sketch with the same FTDI adapter to this other ATmega328P ?

@ David Cary There is new Atmega328P MCU (even fuses are not set) on PCB. AFAIK, I need to burn Arduino bootloader, and it becomes Arduino. To burn bootloader, it seems I need SPI. But Atmega328's SPI pins are not connected to anything on PCB. It seems we need to hardware design again and add SPI feature on PCB. Thank You

You cannot upload the bootloader through the ATmega's UART pins.
Perhaps the the necessary pins (SPI & reset) are broken out on your board, and if not you may be able to tap them with some fine hookup wire long enough for the task as long as there are no conflicting peripherals connected to them which you cannot temporarily disable.
Otherwise you may just have to desolder the chip.
A typical FTDI serial adapter is not the right tool for loading a bootloader either - it might at a stretch be adapted to very slowly toggling the ISP pins but the usual choices, such as an ISP programmer or another arduino with an ISP sketch on it will require far less effort on your part.

After several attempts and searching on Internet, I gave up and decided to design hardware again. It is impossible desolder the Atmega from PCB. PCB is so small and my soldering skill is not enought :((  THANK YOU FOR YOUR ANSWER

Planning for ISP access is of course a good idea.  If you are working with through-hole parts you may want to use a socket on the next prototype, but you could rescue the board by cutting the IC pins and using a new chip (you can, incidentally, buy them with the bootloader already loaded).  If you are working with SMT a hot air desoldering tool will pay for itself the first time you rescue a custom board that might have been damaged by cruder removal attempts.  But it's not clear that you needed to remove the chip anyway, unless you had peripherals driving the needed pins in conflicting ways.


text:
Observing USB Gamepad with Arduino?
I have a gamepad which I want to treat as a sensor for my Arduino board. I want Arduino to trigger a certain action based on button pushes from the gamepad. Different buttons, different actions.
The gamepad comes with a USB connector. I cut the the USB cable open, solder it with pluggable pins which are then connected to a breadboard. I supply the gamepad with 5V power from Arduino and connect the USB's Data+ to Arduino's analog input pin (A0). Please check the images below.
I thought by observing the voltage coming from the gamepad's Data+ pin, I can probably determine if a button is being pushed. However, the observable input voltage in Arduino's A0 do not produce any meaningful difference between button push and release.
My question: Is it possible to detect Gamepad's button pushes with this arrangement? If it's possible, where do you think I'm doing wrong?

simulate this circuit – Schematic created using CircuitLab

You arduino doesn't have USB host controller, so you can't. You have broken the gamepad for nothing..

Ok thanks for mentioning USB host controller, that's the lead that I need!

Adding a USB host controller to an Arduino is technically and economically silly.  You'd be better off with something like a kl25z which is cheaper, more capable, and has that built in.  Or you can gut the gamepad and replace the electronics.

Yes, the real SNES or Megadrive gamepads are much easier to read.

How is a 20,- closed source KL25z dev board cheaper than a open hardware 2,- nano with 3,- usb host shield ???

As mentioned, the problem is the gamepad you have uses communicates over USB, which requires a USB Host chip to communicate with. However, USB Host shields can be found on eBay (under "arduino USB Host shield") from US$10, and they come with a USB socket, so you could use it easily with another gamepad that hadn't had the connector snipped. This also would allow use with HID devices such as mice and keyboards if you wished, so a worthwhile shield to own.

USB devices make a serial communication, a series of packets of bits are sent and received, which is not beyond your power to learn and talk with. Using a USB Host shield or a chip would be easier (and more costly), but doing it yourself will be much more fun and educational.
Surprisingly, for some USB devices (like a keyboard) you need to poll the data. Nothing will be sent to the host automatically. To find out the protocol they speak, you need to connect the game-pad to a PC and monitor the signals.
Also you need to monitor both D+ and D- signals, they are both used.
Here is a wonderful video by Ben Eater about the USB Keyboards where he goes deep into monitoring the signals and the protocol, can be a good start for your project:  https://www.youtube.com/watch?v=wdgULBpRoXk


text:
Grouping multiple pins to one variable
I'm new to all of this, but it's there a way to group a cluster of pins to one variable? I don't necessarily want the grouped pounds to be sequential.

It's called an array.

Does it need to be byte form?

An array can be made from any data type you like. Google "Arduino Arrays".

Can you be more specific as to what you wish to accomplish?

One example of a application I am considering is a grid of LEDs. I may wait to group some LEDs to look like  constellations. I would like to have variables naming the constellations, that I can't turn on and off like a light switch.

Only if you drop to low-level access, and only if the pins are on the same port.
#define pinset 0x55

 ...

PORTC |= pinset;
delay(1000);
PORTC &= ~pinset;

In the example of the constellations, consider using an array for each constellation where each element in the array corresponds to an LED output pin. You could simply put a 1 or a 0 in each array element to indicate if you want the corresponding LED output pin on or off. It would be easy then to create a function that you would pass a constellation array and would turn the LED output pins on or off based on the contents of the array.


text:
Converting char array to int
I'm trying to use nRF24L01 module to send a messages between 2 arduinos
Transmiter code:
  const char text[] = "Hello World";
  radio.write(&text, sizeof(text));

  delay(1000);

Reciver code:
char text[32] = {0};
radio.read(&text, sizeof(text));

Serial.println(text);

How I can put into char array an int value?
I tried doing it in this way
For example:
      int a = 60;
      const char text[] = String(a);
      radio.write(&text, sizeof(text));
  delay(1000);

radio.println(a) maybe?

Are you just looking for a way to get an arbitrary number expressed as a string? If so, you'll likely want to use some existing functions to help you along.
I recommend using sprintf
sprintf(char * str, char * format, args)

Where str is the string you're storing results in, format is the string you're inserting your values into for, you guessed it, formatting, and args are all the args, separated by commas, that you'll be passing into the format string to be inserted into the str string. An example might be:
char[x] result;    //x is the number of elements in your array, atleast one for every letter and one for the end character, ex: "hello" needs 6.
int number = 24;
sprintf(result, "My number is %d", number);
sendSomewhere(result);   //sends "My number is 24"

You forgot to declare the size of result. Also, if your “somewhere” inherits from Print (most things that implement write() do), then you can somewhere.print("My number is "); somewhere.print(24);.

I did forget to declare a size for result! for OP, that line should read "char[x] result" where x is the number of elements in your char array.
As for sendSomewhere(result), it was just supposed to be an open-ended function for the OP to get the concept with.

By char[x] result; you probably mean char result[x];. 2) I understand the virtues of an open-ended answer, but using sprintf() instead of Print::print() will make the compiled program grow by 1 K or so. If the program already uses Print::print() (which is likely, since it is so common in Arduinoland), then the cost of sprintf() is more like 1.5 K.

sprtintf() returns the length of the string created so you can do int length=sprintf(result, "My number is %d", number); radio.write(result, length); This saves using strlen() to calculate how many bytes to send.

The simplest method is to send the integer in binary format (skipping the conversion to text).
int a = 60;
radio.write((char*) &a, sizeof(a));

Cheers!

You can not have 'const' prefixed the 'text' variable as it then become 'read-only'.
    char text[32];
    int a = 60;
    sprintf(text, "Number %d", a);
    radio.write(&text, sizeof(text));


text:
Why FIFO is important in camera?
I want to buy a camera module for Arduino. I came across this OV7670 CMOS Camera Module Lens CMOS 640X480 SCCB W/ I2C Interface Arduino and CMOS With AL422 3M-Bits OV7670 FIFO Camera .
I want to know what difference does FIFO makes in a camera? If I dont use a FIFO will the quality of video be compromised?

It is all about data transfer mode and performance.

Its not FIFO that is the issue, its the FIFO Buffer that you need with an Arduino.  The Arduino can't download the data from the camera at the same speed as the camera can send it.  Adding this extra buffer in lets the camera generate the data and the Arduino download it (in the same order that it was generated) at its own pace.
You might not need the FIFO buffer for faster microprocessors, but you do need it for the Arduinos.  You could get your own buffer and rig that up, but for a few extra bucks let them do it for you.


text:
Does anyone have a data sheet for MC16-0072
I can't seem to relibly find data sheets for MCM electronics parts.. Searched for hours.. Any help?

not really an arduino question, could possibly be better served in the electronics stack exchange... But it could be betetr answered if you described the item and packaging and/or a pic

I'm voting to close this question as off-topic because stack exchange is not a human replacement for google when you are not able to get search results.

A quick search gave me the impression that MC16-0072 is actually some sort of rebranding. It seems MCM is not the manufacturer, simply a distributor.
Does the hardware itself have any number or serial printed on it?
In any case, when I dug a bit deeper and found this datasheet. However, without an image of your hardware or its serial number, I cannot confirm the datasheet is for your hardware.


text:
Quadrature Encoder:Interrupts: Reset Count
I'm working on a quadrature encoder(with a 500ppr codewheel) with a Channel A, B and an Index pulse output.  Using an Arduino Mega I'm counting the number of pulses on Channel A on the rising edge. The code for counting pulses on channel A using an interrupt is straight forward enough with plenty of sources and examples out there to work with.
I've used the the code below to the count the pulses(in an increasing manner). What I'm trying to figure out is how I can reset the overall count using a second interrupt. The second interrupt is invoked when the Index channel pulses high.So in another words when the index channel pulses to indicate a full rotation on the code wheel the main count will reset to zero
#define CHA 2
#define CHB 3
#define CHI 19

volatile int count = 0;
volatile byte INTFLAG1 = 0;

void setup()
{
  pinMode(CHA, INPUT);
  pinMode(CHB, INPUT);
  pinMode(CHI,INPUT);

  Serial.begin(9600);
  Serial.println(count);

  attachInterrupt(0, flag, RISING);

 }

void loop()
   {

       if (INTFLAG1)
             {
               Serial.println(count);
               INTFLAG1 = 0; // clear flag
             }

    }

void flag()
    {
       INTFLAG1 = 1;
       if (digitalRead(CHA) && !digitalRead(CHB))
               {
                count++ ;
               }
     }

Is it possible to implement the reset of the main pulse count with a second interrupt as described?
From what I've read interrupts work at the same level of priority- so I'm thinking there might be a problem here to implement this approach as the interrupts would have to be nested
Any help is appreciated if anyone has done anything like this using interrupts or can point me in  the right direction.

Is it possible to implement the reset of the main pulse count with a
  second interrupt as described?

Yes, and it's quite straightforward. Your index signal goes to pin 19,
which is interrupt 4 on the Mega, so you can simply
attachInterrupt(4, reset, RISING);

in setup(), where reset() is a function that resets the counter:
void reset()
{
    count = 0;
}

I'm thinking there might be a problem here to implement this approach
  as the interrupts would have to be nested

In general you do not want to nest interrupts. If an interrupt is being
serviced when a second interrupt fires, the second one will just wait
for the first one to finish. This approach works fine as long as you do
not have interrupt handlers that take too long to execute.

Very Straightforward and works accordingly.Thanks for the information.


text:
Atmega8 with Arduino bootloader - wrong serial characters
I recently flashed bootloader of Arduino to Atmega8. Unfortunately I stumbled on a problem I can't solved.
I am testing SerialEvent example on Atmega8. I modified it but started debugging it on my code (I think the same problem stops SerialEvent example from working).
I think the Atmega8 reads the characters sent through serial wrongly. That's why SerialEvent 'if' condition doesn't work also. Because it never gets '\n' symbol (it receives it but wrongly interprets it).
boolean prevState = true;
boolean OnOff = false;
boolean stringComplete = false;
String inputString = "";
String OnString = "on\n";
String OffString = "off\n";

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

    while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
    }

    // reserve 200 bytes for the inputString
    inputString.reserve(200);

    DDRD |= 0b00001100;
    PORTD |= _BV(PD2);

    // synchronization info for RPi
    Serial.println("ARD - OK\n");
}

void loop() {
    // turn on
    if (OnOff == true && prevState == false){
        PORTD |= _BV(PD2);
        prevState = OnOff;
    }
    // turn off
    if (OnOff == false && prevState == true){
        PORTD &= ~_BV(PD2);
        prevState = OnOff;
    }

    if (stringComplete) {
        Serial.println(inputString);
        // clear the string:
        inputString = "";
        stringComplete = false;
    }
}

void serialEvent() {
    while (Serial.available()) {
         // get the new byte:
        char inChar = (char)Serial.read();
        // add it to the inputString:
        inputString += inChar;
        // if the incoming character is a newline, set a flag
        // so the main loop can do something about it:
        Serial.println(inputString);
        if (inChar == '\n') {
            stringComplete = true;
            Serial.println("test\n");
        }

        if (stringComplete && inputString.equals(OnString)){
            OnOff = true;
            Serial.println("Turning on.\n");
        }
        else if (stringComplete && inputString.equals(OffString)){
            OnOff = false;
            Serial.println("Turning off.\n");
        }
    }
}

I tested a lot of behaviors. Below I attach one of the tests from Realterm:

First I reset the board - it responded with 'ARD - OK\n' - expected behavior.
Then I sent 'on\n' and it responded with two lines but the characters aren't the same as 'on\n'.
Then I sent 'test123\n' but once again got wrong characters.
It prints multiple lines because it sends the string in which it accumulates the data every time SerialEvent() is fired.
Also sending for example variabl OnString works ok.
I really don't know why is it acting like that... Help would be appreciated :).

Does a simple “echo” program work? E.g. void loop(){if(Serial.available()) Serial.write(Serial.read());}.

Same behavior. It sends string variable normally but returns gibberish. It seems like there is problem with reading then.. ?

I can't understand your answer: there is no string variable in the simple echo program above. Can you try another terminal emulator?

I just added one simple variable to test it. My bad I didn't say it specifically. I tried Realterm and built in Arduino terminal. I don't think another one will bring different results.

Gibberish usually means wrong baud rate, but those seem to match between the arduino code and realterm.

How do you have the ATMega8 connected to your PC?

Through USB to TTL dongle.

Try changing the stop bits to 2; this increases the time between characters.

You have chosen the wrong build configuration which mismatches your hardware.
An ATmega8 with an 8 MHz oscillator works just fine, but all timing aspects of your code must be complied based on knowledge of that clock rate. If they are built for 16 MHz, then everything clock related will take twice as long as intended, for example baud rates will be half of what was intended.
In the Arduino world code is built for a clock rate specified in the chosen boards.txt file entry or in a dropdown menu for recent versions and boards with multiple clock variants. So the answer is that you have chosen the wrong build configuration for your hardware.

Ok I found a solution (rather workaround).
I uploaded the same program to Arduino Uno. It worked perfectly. I transplanted the Atmega328 from Uno to breadboard. Still worked BUT the Atmega328 is using external 16Mhz crystal (which I added to the breadboard).
So what if I uploaded bootloader for 16Mhz external crystal on Atmega8?
It makes it work properly.
So in short:
Atmega8 with 8Mhz internal oscillator doesn't work properly.
Atmega8 with 16Mhz external oscillator works properly.
Don't know why does it make it work. If anyone can think of a reason I would be glad to know it. Thanks for all your help.

Not true.  An ATmega8 with an 8 MHz oscillator works just fine, but all timing aspects of your code must be complied based on knowledge of that clock rate.  If they are built for 16 MHz, then everything clock related will take twice as long as intended, for example baud rates will be half of what was intended.  In the Arduino world code is built for a clock rate specified in the chosen boards.txt file entry or in a dropdown menu for recent versions and boards with multiple clock variants.  So the answer is that you have chosen the wrong build configuration.


text:
Arduino "piston" device
Is there any compact piston-like devices on the market that can apply pressure safely various parts of the head? I can further expound if needed.
The ideal size would be something within the 1-2 inch length range

Could you elaborate a bit on "piston-like devices" that can "apply pressure safely various parts of the head"? Do you have an image or some sort of link to what you are talking about?

Do you need a particular pressure/force to be applied? I ask because it would be possible to use servo or other motor driven mechanisms, but force control would be more complicated with these. I thought of small Lego Technics pistons but some air source and valves would be needed.

Is this really an Arduino question yet? I think this should be migrated to EE (and modified to change title from "Arduino" to something less MCU-specific).

@CharlieHanson, I think the question is off-topic here and in electronics.stackexchange as well.  Possibly on topic in robotics.stackexchange, probably on topic in engineering.stackexchange

It sounds like this is nothing to do with an Arduino, just a general Electrical/Mechanical engineering question that you want to control from and Arduino.
I think you wan a device that when signalled by your Arduino can extend itself by up to 2 inches.
If that is right then I think what you are looking for is a Linear Actuator.  There are plenty out there and some do handle the small stroke you want, but most of them appear to be 9 to 12V.  This means you would require a Darlington transistor or relay to control them from an Arduino.
If you require an extremely precise stoke length then I would recommend a stepper motor with a screw axel.  This would allow you much finer control over how far you pushed, but it would impose limits on what you could do and how it could be mounted.

Can you provide more details on what you want to move?
List item
Is it heavy? Do you need lots of Torque?
Are you pushing straight or do you need to push in an arc (i.e. a door)?
What voltage supplies do you have available?
How fast do you want it to move?
Do you want it to move exactly the same distance every time?

The more info you can provide the better, but in answer to your original question Yes, it sounds like there might be so you plan is still on the rails.


text:
Click counter using SparkFun Qwiic Twist
I wrote the script below in order to count the number of times that I press the SparkFun Qwiic Twist. But when I press the button, I get series of running numbers on the Serial Monitor and not a counter incrementation by 1. Any ideas how can I solve it?
Script:
#include "SparkFun_Qwiic_Twist_Arduino_Library.h"
TWIST twist;
int twistPressCounter;

void setup() {
  twistPressCounter = 0;
  Serial.begin(9600);

  if(twist.begin() == false)
  {
    Serial.println("Twist does not appear to be connected. Please check wiring. Freezing...");
    while(1);
  }
}

void loop() {
  if(twist.isPressed()) {
    twistPressCounter++;
    Serial.print(twistPressCounter);
}

  Serial.println();
}

Likely because isPressed does no debouncing; try isClicked first.

Thanks a lot for the fast respond

print only when there is a change in the value of twist.isPressed ... right now it prints about 1000 times in one second as long as the button is pressed ... so, if you quickly click the button, then it probably prints about 50 times, or more


text:
Can I safely connect my original Arduino Uno to a 19V adapter?
I have an original Arduino Uno R3. According to the specifications the recommended input voltage is 7 to 12 Volt.
However, I have a laptop adapter of 19V that I want to use to power my arduino because it offers more current than the 9V adapter I have as well.
I don't want to damage the Arduino or the DFRobot 2A Motor Shield I'm using. Can I safely plug in the adapter and will it still work correctly?

Input Voltage (limits) 6-20V. What kind of motors do you have, because these have to be able to handle 19v too.

The motors need to handle 19v if powered separately via PWRIN, but not if they use the 5v regulated supply from the Arduino via VIN. See my answer below for more details.

19V is too close to the absolute maximum rating (20V) for comfort. Any voltage surge could kill the regulator. And you'll have thermal problems as well. So I'd say powering the Uno at 19V is very bad advice! Stick to the recommended input voltage range instead!

It's often better to supply separate power to high-current applications (such as motors) rather than taking power off the Arduino. This avoids problems with current and thermal limits of the Arduino on-board power regulator.
Looking at the manual for your board, the motors can be powered by a separate power supply hooked up directly to the motor shield. There's a six-pin header on the board marked VIN and PWRIN. When the jumpers are on the VIN side Arduino-supplied power is used to drive the motors; when the jumpers are on the PWRIN side the motors are supplied with power from the terminal block next to the jumper. (The rest of the board remains powered from the Arduino, but that's usually a negligible amount of current compared to your motors.) A photo in the manual demonstrates the pins set to PWRIN and an external power supply hooked up.
The documentation says you can supply any voltage between 4.8 V and 35 V DC, but be careful! What they don't make clear in the documentation (but is clear from the schematic and the L298N datasheet) is that this power is supplied directly to power side of the L298N and the motors without further regulation. The chip can handle up to 50 V DC, so it would be fine with a 35 V input, but you'll want to check that your motors can handle the voltage you want to give them.
If the motors can handle 19 V input, and your 19 V power supply is reasonably well regulated itself (which a laptop computer power supply generally would be), you can use that to power the motors directly through the motor shield and continue using your current power supply to power the Arduino.
(The ST L298 page has further information, including a slightly less readable copy of the data sheet and application notes.)

According to the page you linked:

The board can operate on an external supply of 6 to 20 volts. If supplied with less than 7V, however, the 5V pin may supply less than five volts and the board may be unstable. If using more than 12V, the voltage regulator may overheat and damage the board. The recommended range is 7 to 12 volts.

So, yes. You can use the 19V external power supply to power the board. However, be aware that the voltage regulator can overheat over time and damage the board.

If someone has a way of calculating how hot the voltage regulator would get, I'd greatly appreciate the knowledge. I'm also not sure if the regulator will get hotter quicker depending on how much current is being pulled through it (for the motor driver shield)

Also, there may be current issues - I found an analysis that says the current limit of the Uno is 1A ( http://electricrcaircraftguy.blogspot.com/2014/02/arduino-power-current-and-voltage.html#.VQcm2UJ6nOQ ). TheDFRobot 2A Motor Shield might try drawing more than the Arduino can handle. I don't know how to calculate that

yes, the more current, the more heat. to calc the temp, you need to know the junction-to-ambient rating of the regulator in watts. To calc watts, subtract 5 from 19 (14) and multiply by the current. If we assume, say, 200ma; 14*.2=2.8w; way too much. divide watts by J2A to get deg C.

I agree with @dandavis. Here's the datasheet for the regulator: https://www.onsemi.com/pub/Collateral/NCP1117-D.PDF. A dissipation of 2.8W would raise the junction temperature by 188°C. If ambient was 25°C, then the junction temperature would be 213°C, far above the 175°C limit at which the regulator internally shuts off. So it won't work at that current (200 mA).

Also, 19V is too close to the absolute maximum rating (20V) for comfort. Any voltage surge could kill the regulator. So I'd say powering the Uno at 19V is very bad advice! Stick to the recommended input voltage range instead!

throwing an LM7812/7809 between the 19v and the MCU would solve the heat issue.


text:
What kind of Arduino should I pick for a calculator?
I am planning to build a calculator using Arduino as the base. I already know C and I love low-level stuff, so I guess the software part won't be a problem.
However, I've been stuck with Arduino. What I need is something capable of doing math (as I'm not even sure if Arduino has a FPU), and it to have enough inputs for more than the basic 0-9 + - / * keys.
I am a real newbie when it comes to hardware. I don't even have the slightest clue where to start. I barely understand Arduino's specifications, which is why I'm asking here.
I want to do something more than the classic calculator, because the software part is not a problem. I just need help on which hardware should I choose; both on the 'which Arduino' and 'which accesories for the Arduino' parts.
P.S. I have some experience with x86 assembly; does that mean that 86duino or Intel Galileo are better for me?

For the most part, none of the AVR based arduinos are any better at number crunching than any others. They all have a single AVR core running at 16Mhz. None have an FPU, but the software floating point code is very efficient and at the time scales you care about for a calculator, it really doesn't make much of a difference.
The biggest differences between models are memory and available IO, so the decision between AVR models should probably come from what kind of peripherals you want to plug in, not what you want to calculate.
That said, if you want to do a lot of high precision, numerical calculations (like numerical integration or something), you will probably want something with more memory, and floating point types larger than 32-bits. I don't have much experience with those models, but I'm pretty sure that a Yun or a Zero would be better suited for those kinds of calculations. They don't use AVR based main CPUs.
For IO there are too many options to enumerate here. Take a look at the usual suspect's pages (sparkfun, adafruit, etc...) for displays and buttons. These sites have good descriptions and example code for everything.
When picking devices, remember that you can have multiple I2C devices plugged in at once, but only one UART serial per port (uno/leonardo 1 port, mega 4). Software serial can give you more UARTs for low speed comms if need be.
If you want a lot of different individual buttons, there are ways to get more than 1 button per pin, but it would be a bit easier electrically to pick an arduino with as many pins as buttons. Some of the keypads available already have a special wiring scheme to get higher than 1-to-1 pin ratios and descriptions of how to use them, so they might be a good pick to get yourself started.

Correction: The Yun does have an AVR MCU.

It has a 32u4 for IO, but the atheros MIPS chip @400 MHz would be used for the calculations.

Start with the biggest (AVR) Arduino you can afford, and worry about miniaturizing it once you have the basics in place. You may find that you don't actually want an Arduino in the end, but something like the ATmega169PA instead so that you have native LCD support (instead of having to use a discrete LCD module).

P.S. I have some experience with x86 assembly; does that mean that 86duino or Intel Galileo are better for me?

Doesn't matter. Most of your x86 assembly experience will easily transfer to AVR (but not all, since the AVR core is simpler than x86).

Any Arduino (I would start with the UNO) will be sufficient to make a calculator similar to the regular HP or TI calculator product line.
For the keypad, you will need to buy an I2C compatible keypad and connect it to the I2C lines. For the screen there is an LCD shield.
You will not need to code anything in assembly. You can write cpp code using the libraries provided with the Arduino.

Much more like a matrix keyboard than an i2c one.


text:
How to build a high-frequency (>20kHz) driver for LEDs?
I'd like to build a LED lighting for my house. I've made preliminary tests and I've realized that my 12V transformer emits a considerable electric hum at the Arduino's PWM frequency range (PWM signal from Arduino gets amplified by external amplifier powered by the transformer).
I know, that I can reduce the audible noise if I will drive the PWM at higher frequency, beyond the human ear's audible range.
AFAIK Arduino itself is not able to give me 8-bit PWM at the >20kHz range. Do you know any feasible hardware high frequency PWMs that will work with the Arduino?

An "amplifier" for a PWM signal need not be more than an nFET, and the PWM signal should not couple into the power the nFET switches.  Ie, there may be some problem with your design other than the PWM frequency.  Perhaps ask on electronics SE about the circuit design

"AFAIK Arduino itself is not able to give me 8-bit PWM at the >20kHz range." Yes it is. 16MHz / 256 = 62.5kHz

I am not into hardware but the way we handle it was by using a external PWM designed for LEDs and control that, using an Arduino. The LED driver we used was a TLC5940, see TLC5940 16-Channel LED Driver With DOT Correction and Grayscale PWM Control. This one is controllable using the SPI bus.
There are several libaries implementing the protocol, i.e PaulStoffregen/Tlc5940.
See Playground from Arduino - TLC5940 for more information.

Actually this is the one, I settled to use. I got one from China for ca. $10.

Just change the timer prescaler to a lower value.
E.g. timer2 (PWM pins 3 and 11) has the prescaler set to clock/64 and runs at around 500Hz. So changing it to clock/8 will result in 4kHz. (Sorry, no clock/16 available).
TCCR2 &= ~_BV(CS22);//clear CS22 bit
TCCR2 |= _BV(CS21);//set CS21 bit


text:
How to make sure Arduino's PWM pulses are phase shifted?
I'd like illuminate my room solely with several RGB LED strips using Arduino's PWM (together with LED amplifier and few transistors).
I want the Arduino to control 2 independent chains of LED strips, and I want to make sure, that the LEDs would not blink simultaneously, creating a very strong stroboscopic effect in my room.
How to delay three Arduino's PWM pins half a phase relative to the other three?

Why do you think you'll observe led blink?

@MertGülsoy I will not see LED blinking, but I will see that the stroboscopic effect the blinking would produce.

How much of a delay do you have in mind? A few microseconds? Half a second? What is the PWM frequency? What is its duty cycle? Which pins are you using?

@NickGammon I need to shift for half of the phase, so if I'd run PWN @ 32Hz, it would mean 1/64th of a second. I plan to use standard PWM pins, but now really consider an external PWM generator which could give me a much higher, not audible frequency (to avoid the annoying buzzing sound from the power source).

I'm not sure I understand here. Your eyes won't detect the difference of 1/64th of a second (or less). There are two figures here: the PWM frequency - which helps make the LEDs appear to be dim, and the rate at which they blink, which must be quite slow or you wouldn't notice it.

@NickGammon Yes, the eyes wouldn't notice the 1/64th directly, but they WILL notice the stroboscopic effect of this frequency. I am talking only about the PWM frequency. I never wrote I want to see my LEDS blinking.

You mentioned "I want to make sure, that the LEDs would not blink simultaneously". So there is a reference in the question to blinking LEDs. I'm a little curious now why you want to PWM at 32 Hz. Why not, say, 7813 Hz? I'd like to answer the question, but I want to make sure I'm answering the right question. :)

@NickGammon Thank you very much. I very appreciate your effort. My English might not be perfect, it's not the first language for me. I want simply to replace the traditional room lighting with RGB LEDS.

Your English is fine, I'm just trying to understand the requirements. Any particular reason the frequency has to be as low as you mentioned above? (32 Hz) And why two strips anyway? Are they going to be at different levels? Eg. one bright and one dull?

@Nick Two strips is the absolute minimum to have an acceptable luminosity. They will be mounted together. The RGB LEDS are not too bright... Sorry, I meant to write 32kHz, not Hz, my bad.

You can, see effects of mains frequency in LED's under some conditions.  I used to have an RC plane charger with a bi-color LED that would be green for one battery pack, red for the other, and amber for both. The amber was almost indistinguishable from the red, but I found if I shook my head I could see it as a distinct red and green.  I also noticed that my LED clock's digits would "swim" when I played low notes on the trumpet (later I had to replace the supply capacitor in that clock - I suspect it had been slowly failing for years, allowing the line frequency to modulate the LED brightness)

Have you actually observed this strobe effect?

This (short) code below will achieve what I think you are asking for, on the Atmega328 (eg. the Uno, Duemilanove, etc.).
byte dutyCycle = 80;

void setup()
 {
  pinMode (3, OUTPUT);    // Timer 2 "B" output: OC2B
  pinMode (11, OUTPUT);   // Timer 2 "A" output: OC2A

  // Set OC2A on Compare Match when up-counting.
  // Clear OC2B on Compare Match when up-counting.
  TCCR2A = bit (WGM20) | bit (COM2B1) | bit (COM2A1) | bit (COM2A0);
  TCCR2B = bit (CS21);         // phase correct PWM, prescaler of 8
  OCR2A = dutyCycle;           // duty cycle out of 255
  OCR2B = 255 - dutyCycle;     // duty cycle out of 255
  }  // end of setup

void loop() { }

How it works
The code uses Timer 2 (an 8-bit timer) to count up to 255 in phase-correct PWM mode. Outputs are to OC2A (the "A" output - pin D11) and OC2B (the "B" output - pin D3). The duty cycle is in variable dutyCycle which must be in the range 0 to 255. The timer counts up to 255 and sets OC2A on compare-equal to the dutyCycle number, and it also clears OC2B on compare-equal, when counting up. The second half of the phase-correct cycle does the reverse. Thus the two cycles are of opposite phase.
Frequency
The frequency of the timer is 3.9 kHz. This is because the timer has a prescaler of 8, then it counts up to 255, then it takes two cycles per period (one up, one down):
16000000 / 8 / 255 / 2 = 3921.56 Hz

As Edgar Bonet pointed out in the comments, phase-correct PWM counts are not zero-relative, unlike other counting modes. Thus you divide by 255 to work out the frequency, not 256.
You could select other frequencies by choosing different prescalers.
Proof of operation
The oscilloscope screen here shows the two outputs, out of phase with each other by 50%.

You can see from the circled cursor measurement that the OC2B pin is off for exactly the requested duty cycle (80 µs).
 1/ 16000000 * 80 * 8 * 2 = 8e-005 (0.00008)  --> 80 µs

Just nitpicking: the counter does not count up to 256: it stops at 255. It's frequency, according to the datasheet, is 16 MHz ÷ (8 × 510) = 3921.57 Hz.

grumble - In non-PWM modes a count of zero gives you one cycle, however observed results (from the screenshot above) appear to agree with your assessment. I must admit that the 80 µs on the screen seemed a little low. FWIW the counter is normally zero-relative, so a count of 255 is 256 cycles.

This is a feature of phase-correct PWM: it takes 255 (prescaled) cycles to count up from 0 to 255, then 255 cycles to get back to zero. In contrast, both normal counting (mode 0) and fast PWM (mode 3) have a period of 256 cycles: 255 cycles to count up, and then one extra cycle to roll back to zero.

@EdgarBonet - thanks for the correction, I have amended the answer.

Why not put a capacitor (and current limiting resistor) in the circuit for each color of each LED? (The output from the Arduino would lead first to a current limiting resistor, value picked to limit the current to the LED to it's max, as usual. Then a small capacitor between the signal line and ground.) That will average out the output and change a square wave output to a DC output (With a fair amount of ripple in it.) The ripple shouldn't matter, but the LEDs won't turn fully off, so the strobe effect should be all but eliminated, and the apparent brightness of each output should be the same.
Then you can use unmodified PWM and don't have to mess with the timers on your Arduino (which affects other things besides PWM.)

This is a very bad idea. Putting a capacitor on PWM signal kills the dimming effect - the light will stay simply ON for most dimming settings and will put a very high load on the driver especially on low light settings. The driver will frantically try to keep the capacitor full by providing increasingly large charging current during the shorter "on" phase (due to dimming).

I just edited my answer to add that you would also need a current limiting resistor. If you limit the max current to the capacitor to the max current for the LED, then lowering the duty cycle of the PWM should lower the average voltage coming out of the capacitor.

Current limiting resistor - is just a resistor that will limit the current by means of consumption. Something tells me, that to get a noticeable effect of dimming you would need such a resistor that would significantly reduce the voltage to the LEDS. Did you actually try what you propose?

No, you misunderstand. Put a current limiting resistor BEFORE a capacitor. The current limiting resistor would limit the max current that would flow out of the output pin to the max on current of the LED. Then any PWM duty cycle below 100% would further limit the average current flowing into the capacitor, which should reduce the brightness of the LED and create a (admittedly noisy) steady-state voltage to the LED, all but eliminating the strobing effect.

And no, current limiting resistors do not "limit current by means of consumption." They drop voltage by means of emitting heat (consumption). They also limit the total current through the circuit, as described by Ohms law.

I have not tried this specific application, but it's a straightforward RC filter.


text:
Can I safely integrate 3,3v sensor with 5v Arduino UNO? How?
I plan to use Adafruit's RGB sensor with Arduino working as a RGB controller running on 5V. In my location, the 5V-compatible version of the sensor is not available.
There is a 3,3V pin on my Arduino board. Can I use it to power the sensor, or will the data pins (which are rated 5V) still burn it?
The TCS34725 chip uses I2C communication, which arguably would still be compatible with the 5V (http://playground.arduino.cc/Main/I2CBi-directionalLevelShifter)
I am still very new to the electronics, and I don't feel confident enough to build my own level converter, and sadly, no converters advertised on arduino.cc are available in my country (Poland).

If you need I2C the best solution is go for a logic level converter based on BSS138 mosfet or similar. I've used a few and they never let me down. Examples: Sparkfun have this https://www.sparkfun.com/products/12009 and Adafruit http://www.adafruit.com/products/757

if you have also a few transistors available, you can make your own homemade solution till you get something more robust, according to arduino page: https://playground.arduino.cc/Main/I2CBi-directionalLevelShifter

(source: arduino.cc)

Thank you very much for this answer. The news is unfortunate for me, because these items seem not to be available in my country (including the ones you referred to). It seems it will be cheaper to ask retailers to get me the 5V-compatible version of the sensor instead.

You can use "logic level converter bidirectional," to connect modules with different voltage requirements. They are pretty cheap.


text:
How is the integration time set for a camera?
I using the TSL1401R-LF Linescan Camera Module, which reads in a 1 X 128 line of pixels, and I'm having trouble understanding how the integration time is set for this device.
I understand from page 9 that the minimum integration time is a constent that results from a function of the clock speed, but I don't fully understand when this integration period takes place.
According to the timing waveform (Figure 1 on Page 5) the integration period appears to be set after the first 18 clock cycles. Does this mean that the integration period is set while the camera is outputting pixels?

How is that even possible? Also does this mean that in order to achive the minimum delay time I would have to take that time and divide it across those remaining 110 clock cycles (i.e. 307 ns for a total of 33.75 us)?
UPDATE:
This is how I am currently programming the camera. I'm using delayMicrosecond() after the HIGH and LOW clock impulses as well as at the end. I have enough delays to achieve the minimum 33.75 microsecond delay, but I'm still having sensitivity problems.
int delayTime = 20;

void readPixels()
{
  digitalWriteFast(SI, HIGH);
  delayMicroseconds(delayTime/2);
  digitalWriteFast(CLK, HIGH);
  delayMicroseconds(delayTime/2);
  digitalWriteFast(SI, LOW);
  delayMicroseconds(delayTime/2);
  digitalWriteFast(CLK, LOW);
  delayMicroseconds(delayTime);

  for(int i = 0; i < 128; i++)
  {
    digitalWriteFast(CLK, HIGH);
    pixelsArray1[i]=analogRead(Cam1Aout);
    pixelsArray2[i]=analogRead(Cam2Aout);
    pixelsArray3[i]=analogRead(Cam3Aout);
    delayMicroseconds(delayTime);
    digitalWriteFast(CLK, LOW);
    delayMicroseconds(delayTime);
  }

  digitalWriteFast(CLK, HIGH);
  delayMicroseconds(delayTime);
  digitalWriteFast(CLK, LOW);
  delayMicroseconds(delayTime);

  delayMicroseconds(20);

}

It is quite a difficult system to get your head around, as you have noticed.  I'll try and break it down more logically for you...
An important thing to note is that there are two capacitors in each pixel - the integrating capacitor and the sampling capacitor. It's these two capacitors that lead to a certain amount of confusion, and it's vital to understand the role of each one.

Under normal sampling operation light falling on the photodiode of a pixel generates charge through the internal amplifier which is stored in the integrating capacitor. Simultaneously that stored voltage level is mirrored in the sampling capacitor.
When you send the pulse on SI a signal called HOLD is generated internally. This signal is sent to all of the pixels and tells them to disconnect their sampling capacitors. They do that through the switch S2.  At the same time the integrating capacitor is emptied by S1 causing a short circuit across it. That is held there for 18 clock cycles to make sure that it's completely empty. All this time the sampled voltage is still there in the sampling capacitor.
Then as you continue clocking the pulse you sent in through the SI pin is walked down a 128 bit shift register. As it pops out of each output in turn it connects the sampling capacitor of that pixel to the output buffer so you can read the voltage. It's then flushed out and re-connected to the integrating circuit again to sample the pixel again.
So there is actually multiple things happening during your 129 clocks. Reading and integrating are both happening at the same time. But you're not reading this set of clock's integration, but the last set of clocks integration.
So you have:

SI pulse - HOLD generated, samples frozen
18 clocks of clearing the integrators and reading nothing much.
110 clocks of reading nothing much (nothing is sampled yet) and integrating.
1 clock to terminate
SI pulse - HOLD generated, samples frozen
10 clocks of clearing the integrators and reading the previously integrated samples 1-18
110 clocks of reading the previously integrated samples 19-128 and integrating new ones
1 clock to terminate
... etc ...

So clocks 130 to 258 are reading the light that was sampled during clocks 19 to 128.
The upshot of all this is that your integrating period is the total time taken for the 110 clocks that occur between the end of the 18 clocks that clear the integrators and the next SI pulse that creates a new HOLD signal.

Thank you so much, you've made this whole process so clear. But I have a follow up question; why am I still having such poor sensitivity if my integration time is so long? When my delay is set to 170 us I get some really good readings, but when I reduce it to 20 us I suddenly lose all of it. But I'm still above the 33.75 us minimum delay.

You still don't understand what happens during integration do you? The longer you integrate for the more sensitive the pixels are. The minimum integration time is the absolute minimum amount of time you have to run for to get a result. That will only be a usable result in a very very bright environment. Sahara at midday bright. The darker your environment the longer you have to integrate for to get any real difference in your values. As I have said before it's like the shutter of a camera. Take a picture with 1/3200s shutter in a dark room and you get nothing. Take a picture with .....

... 5s shutter in full daylight and you get just white. It is up to you to get the optimal shutter speed (integrating time) that allows enough light in to see the image whilst not letting in too much light so you lose detail.

I didn't understand what the minimum delay meant, but I understand what you're saying now. So I have to just deal with the low sensitivity if I want my program to run faster.