text:
Arduino loading variables from an SD card
Hello I have made a small game using and Arduino Uno and a Nokia 5110 screen. I use bitmaps to draw the images onto the screen. The problem is that bitmaps take up a lot of space and I can only use up to three bitmaps before running out of space. Is it possible to use an SD card to store the bitmaps on and have a method in the Arduino code to load a bitmap at a certain time, like when a button is pushed?

How about storing the bitmaps in program memory? And use run-length compression?

How big are the bitmaps you want to use? How much RAM is free, and how big is the program? Are you storing the bitmaps in RAM, Flash or EEPROM? That screen is 84x48, and monochrome, hence 504 Bytes is a complete screen. Several complete screens stored in Flash would likely be smaller than the SD library code.

Typically a bitmap for the Nokia 5110 (PCD8544) requires 504 bytes of memory (48*84/8). A bitmap as a initiated global variable will be stored in program memory, transfered to data memory on startup and then to the device (when drawn). Three bitmaps will use up 1.5 Kbyte. This is the limit for the Arduino Uno as an additional bitmap will require all data memory.
The first trick that can be used is to define the bitmaps in program memory with the attribute PROGMEM and when needed transfer to a buffer (504 byte) in data memory (and then to the device).
void *  memcpy_P (void *, const void *, size_t)

The second trick is to transfer the bitmap directly from the program memory to the device. This may be supported by the library. If not the bitmap draw function will need to be updated to explicitly read program memory.
The upper limit for the bitmaps is now the size of the program memory (30 Kbyte, 60 bitmaps).
Cheers!

Yes, it is possible, but is it practical?
There's basically two ways of doing it:

Load the entire bitmap into RAM for displaying multiple times
Display the bitmap direct from the SD card.

As the Uno only has 2KiB of RAM that rather limits the size of bitmap that can be loaded into it. As you currently can have 3 bitmaps in flash (max 32KiB) I will assume they are considerably bigger than 2KiB each, so loading them into RAM is not really going to be doable on the Uno.
So the second option - drawing it direct from the SD card - is really the only practical way. The problem with that is reading from the SD card is considerably slower than reading from the internal Flash.  That means that your screen updates could be really slow, which would seriously impact the playability of your game.
All that happens when you draw a bitmap normally is that a loop iterates through the data and interprets each bit of each byte as a pixel being on or off and sets the relevant pixel to be on or off on the screen.  Instead of reading data from flash you just read bytes from the SD card and interpret them in exactly the same way.  If you take a look at the bitmap drawing routine in your LCD library you will see how simple it is - replacing the Flash access with SD card reading should be a simple enough matter to implement in your own copy of the routine.
A much better option would be to use a more powerful Arduino - one that has considerably more flash, such as the Mega2560.

authors: Рустам Юнусов


text:
Arduino and reading from multiple USB connections
I'm sending up a high-altitude balloon with an onboard Mighty Ohm Geiger Counter and some other sensors, all of which will be managed by an R Pi B+. I'll collect and store the data with the R Pi; all of that's fine.
In order to track and recover it, I'm using the HABDuino shield on an Arduino. It uses the APRS system and sends back short messages, giving the altitude, internal temp, my callsign, and coordinates. I'd like to add the Geiger counter's data to that, but I'll need to get it from the R Pi.
Currently, I'm using an FTDI Friend to connect the Gieger counter to the R Pi, and getting the data from the serial port. I see here that I can connect the Arduino and Pi vai USB, but... since there's already a USB connection to the Gieger counter, will there be a conflict? Is that something that I can work around?
Thanks for the help!

What is the point of having multiple connections to the same arduino? Just choose one, or the other.

Have you tried using a hub?

There would be two USB connections to the PI, rather than the Arduino. I can't use just the Pi because I need the hardware (it's an Arduino shield) for the tracking, and I can't use just the Arduino because the tracking shield takes up all of the resources.

What sort of hub?

Ummm... USB hub?

I'm voting to close this question as off-topic because this is about the Pi, not the Arduino.

Note you can also connect the Arduino to the pi's hardware serial UART, though if you are running your Arduino at 5v you will need level translation.

The FTDI should be showing up as /dev/ttyUSB0 on the Pi.
If you connect an Arduino as well it will show up as /dev/ttyACM0.
If you don't have enough USB sockets then just add a USB hub.

source: Stack Exchange

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

sort: votes


text:
Why can I power an SD card reader from a digital pin?
I'm trying to understand the power requirements of an SD card. I have a cheap breakout board from eBay that includes built-in level shifters, so I can plug it in directly to my Arduino. I provide power from one of the digital pins, and it works. This doesn't make sense to me, as I thought an SD card reader should draw upwards of 50-100 mA, well over the capacity of an individual digital pin on the Arduino. However, at least one SD card manufacturer does this as well, so I'm not making this up.
I have checked, and the data is written no problem. I have connected an ammeter between the Arduino and the SD reader, and it never jumps above 3 mA? The only problem I have is when I switch from using the USB cable (connected to my computer) for power to a battery pack, the SD card starts acting erratically. Which makes sense, if it's not getting enough current.
What I'm wondering is why it ever works when connected to a digital output pin? Clearly I'm missing something important.
Edit: The reason why I thought they required a lot of current: I've seen comments like this on a number of tutorials:

One is that they are strictly 3.3V devices and the power draw when writing to the card can be fairly high, up to 100mA (or more)!

Edit2: @dlu answer lead me to investigate the voltage I was sending to the SD card reader, which turns out to have been the problem. I was supplying the Vin pin with 5.2V, which was regulated down to 4V, presumably too low for the 5V-3.3V step-down at the SD card. Moving the battery power to the 5V pin corrected this. This also introduces some new risk, as the board is now receiving unregulated power. But that is another problem.
Edit3: And finally, answering my original question: I found a note on the Adafruit product page for a similar breakout that indicates:

Onboard 5v->3v regulator provides 150mA for power-hungry cards

So despite only drawing 3mA of current from the Arduino pin, the actual SD card is supplied with > 100mA from the regulator.

It seems that you've verified that the power requirements are within the range of a digital pin. Is there a reason why you thought they would be higher?
So, it sounds like the real question is "why does the SD card work with USB power, but not with battery power?" The first thing that occurs to me is that the battery is not providing sufficient voltage. What kind of battery are you using and where do you connect it to the Arduino?
Almost any battery that you use will be able to provide sufficient current for a 3 mA load, but the voltage may not be adequate – especially if you are running a marginal battery (voltage wise) through the onboard regulator.

I was plugging the batter into the Vin and GND pins on the Arduino. I added a link to one reference to the high current draw of SD cards in my question.

Forgot, the battery pack is 4 AA rechargeables (1.2V), which are actually producing 5.1V at the moment (from my multi-meter), so presumably they're still well-charged

Checking the voltage drop across the SD card, when plugged in via the USB cable: 4.9; battery connected to Vin: 4.0; battery connected to Arduino 5V pin 4.9. And the SD card works when powered via USB, the 5V pin, but not the Vin pin. I didn't realize Vin and 5V weren't the same thing!

Thanks, that was the nudge I needed to chase down the problem. I've updated my question with additional info and a solution arising from your suggestion.

I just tested a SD card in an adapter (with level shifters). Without any activity the SD card is only drawing around 0.5 mA. So that is in the capability of an output pin.
Doing a directory list appears to use a maximum of 7 mA, so that is OK.
Writing a file used a maximum of 54.3 mA, which is exceeding the absolute maximum ratings for an output pin (40 mA - recommended only 20 mA for continuous current).
Now you may say that "it works" but the question is: for how long? Exceeding absolute maximum ratings is a path to damaging your processor.
If you want to turn the SD card on and off from time to time, to reduce power, I suggest you arrange to switch the 5V line (and not use a digital output). For example from this page about a low-power temperature sensor I have this schematic:

The MOSFET there switches a 5V line on and off under program control.
That particular design includes a SD card, and that particular gadget has been working for a couple of years now.
Photo of hardware:

Thanks Nick. I found your logger while I was researching this issue, it will be a very helpful resource. When I monitor the current of my SD card, it stays below 3 mA even when writing to the card. Is it possible the onboard voltage regulator is this efficient, or is it more likely my current meter is not good enough -- I'm using an INA219 current sensor board.

Measuring burst current isn't the easiest thing in the world. In my case I had my meter on "min/max" mode and hoped it would sample fast enough. My advice is, for the sake on a MOSFET and a couple of resistors: play it safe and switch the power like I showed.

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


text:
Correct solution for "multiple definition of" compile error
I'm in the process of trying to take this demo sketch and extract the necessary bits into a modular library that can be included in other sketches.
Here's where I'm at so far.
Here's the test sketch that I'm including it in.
However, when I try to compile it right now, I'm getting...
libraries/Adafruit_CC3000_Dynamodb/sha256.cpp.o: In function `Sha256Class::init()':
/home/me/sketchbook/libraries/Adafruit_CC3000_Dynamodb/sha256.cpp:33: multiple definition of `Sha256Class::init()'
sketch/sha256.cpp.o:sketch/sha256.cpp:33: first defined here

I've been programming for years in other languages, but I'm not all that experienced in C. I'm sure I'm doing something completely stupid, but I can't figure out what it is.
I'm also aware that this code still needs a lot of cleanup work in general. Right now I'm just trying to work toward a basic MVP that works so that I start gradually cleaning things up and making it more OOP one step at a time.

It looks to me like you have a copy of the sha256.cpp file in your sketch which is causing the problem.

@Majenko , nope, but seeing the sketch would probably be useful... I'll get that into a repo and update the Q.

The error message tells me you have. "sketch/sha256.cpp.o:sketch/sha256.cpp:33: first defined here"

But I'm not sure how to interpret that.  I only have one each of sha256.cpp and sha256.h, and I'm only including sha256.h from one place.  I added a link to the sketch I'm using to test above.

The module sha256.cpp (and I think the sha256.h too) are already present. Remove these 2 files from the sketch directory and it should compile without errors.

@ott  No, they're not.  There's only one of each and they're in the library, not the sketch.

Which of the myriad of DHT libraries are you using?

They may be left over in the build folder. Try restarting the IDE

@Majenko BAM!  Restarting the IDE was it.  I learned something new today!  If you want to make that an actual answer, I'll accept it.  RE: the DHT library... ( https://github.com/adafruit/DHT-sensor-library.git )

You have an old copy of the sha256 files lingering in the build folder. These will have been output at some point in the past and never been cleaned up since they have been deleted from the IDE.
It is probably a bug in the IDE that doesn't remove the old files.
Restarting the IDE will cure the problem and allow you to compile.


text:
Few questions related to programming microcontrollers
I'm learning "Arduino" (I don't have previous knowledge of microcontrollers). I have few questions:

What is the difference between programming a microcontroller in C and programming in "Arduino?"
Is it a good idea for beginners to start programming microcontrollers in Arduino and then start learning to program in C?
I have Arduino Uno with an Atmega328P-PU microcontroller. What are some other microcontrollers which can be used with this board? What are differences between various microcontrollers which can be used with this board?
If a microcontroller is already programmed, can we download the program from it to a PC and edit it in Arduino IDE? Or it is like a .exe on a PC, once compiled we can't get source, all we can do is reverse engineer?

That's it :)

#2 is a "religious" question.  The answer will vary from one end of the spectrum to the opposite, depending on whom you ask.  Even if we manage to raise above the "microcontroller religions", the answer would still depend on your answer to "What are your goals? Why are you learning this?"

#2 IMO only those who understand programming in C can make some custom functions for Arduino, others just copy&paste all the day and seek answers from forums like this. The only advantage is easy moving to different arduino platforms.

The Arduino IDE uses C++ primarily, which it preprocesses in order to make compilable. But you can still for the most part use C in the Arduino IDE and it will just work as normal; there's nothing requiring you to use C++ or the Arduino libraries (or even the Arduino IDE) for most tasks.
Not touching this one. And in the end it doesn't matter terribly since they're very close.
Any of the ATmegaXX8 or ATmega8 chips will fit the socket. Note that they will require separate cores if you're using the IDE. And you can use any chip without the board in the IDE as long as you can find a core for it.
Not if you use a traditional compiled language to program it. If you use a VM then you conceivably could, but you'd have the source on your system regardless.

Nothing really.  The Arduino language is C++, a super-set of C. It contains a library of routines which are automatically included and linked, as well as a small amount of pre-processing to hide some of the pitfalls of C (e.g., automatically adding function prototypes for all functions to the top of your program so function ordering isn't something you now need to think about). Other than that, it is just C++, which is C with bells.
If you learn the Arduino language you are learning C. If you learn C first then it gives you a good grounding in how to program the Arduino. Either way, by the time you have written your first Arduino program, you will be programming in C.
There are a number of chips by Atmel that will work. You need, besides the "core" that Ignacio mentions, a board definition which defines what pins do what and what chip is in use. You also need a bootloader for that specific chip and some way to install that bootloader into the chip. There are tutorials on how to do that for commonly used chips - more uncommon ones may not have a bootloader readily available.
When you program for the Arduino you are compiling the software. That is turning the source code first into object code and then linking the object code into an executable format - almost exactly the same as a .EXE on Windows. There is nothing you can do to "undo" that, only disassemble the raw instructions into assembly language and try to interpret what it is doing, which with assembly is a bit of a black art since it can be somewhat cryptic.

What is difference between programming microcontroller in C and programming in Arduino?

The difference is that the Arduino core includes a set of functions and classes (C++) to make Arduino boards easier to program.

Is it good idea for beginners to start programming microcontrollers in Arduino and then start learning programming in C?

The whole idea with Arduino is to make it much easier to start embedded programming in C and/or C++.

I have Arduino Uno board Atmega328P-PU microcontroller. What are some other microcontrollers which can be used with this board? What are differenes between various microcontrollers which are used with this board?

None. This is the controller for that board (though there are "smaller" versions).

If microcontroller is already programmed, can we download program from it to PC and edit it in Arduino IDE? Or it is like .exe on PC, once compiled we can't get source, only we can do is Reverse Eng.?

This you will have to explain better. Sounds like something bad and you should avoid that (or at least do not ask people to help you do a bad thing).

What is the difference between programming a microcontroller in C and programming in "Arduino?"

The default language is C++, but you can program in C. Thus the difference is "not much".

Is it a good idea for beginners to start programming microcontrollers in Arduino and then start learning to program in C?

Ah, if you program the Arduino you will be learning C. So "goodness" doesn't really enter into it.

I have Arduino Uno with an Atmega328P-PU microcontroller. What are some other microcontrollers which can be used with this board?

You could conceivably remove the chip and replace it with an Atmega168P. I'm not sure why you would want to.

What are differences between various microcontrollers which can be used with this board?

RAM, program memory (flash) size, and EEPROM size.

If a microcontroller is already programmed, can we download the program from it to a PC and edit it in Arduino IDE? Or it is like a .exe on a PC, once compiled we can't get source, all we can do is reverse engineer?

No. Like a PC, you can't get the source back. The compiler is a good, highly optimized one. The generated code won't look like the source.


text:
Update code over Ethernet?
I've got an Arduino faithfully monitoring our sewer lift pump. It talks to the world over Ethernet (with PoE). I'm wondering if there is any way to load new code over the Ethernet as well. Any ideas if this could be done?
I imagine that using the boot loader might be out of the question, but perhaps it would be possible to upload a new system image – perhaps onto an SD card – and then use a modified boot loader to discover the new image and copy it into place.

You can update it in any way you can figure out how to write in the bootloader.

Do you know of any documentation (or descriptions) of how the boot loader works – short of reading the code?

It works exactly as described in Atmel's datasheets and application notes.

See http://forum.arduino.cc/index.php?topic=16812.msg122380#msg122380 or even better https://github.com/LowPowerLab/DualOptiboot.

A bootloader to network-boot might be too large to leave enough code space for your application. Your second suggestion sounds more workable - to collect & verify the entire new image in secondary storage first, then call a storage-to-flash boot loader. You really don't want to start loading an image that then suffers damage in transit, or to have the link go down mid-download. The likely only way out of that is a site-visit. Saving first lets you confirm the integrity of the new image before you start over-writing any of the old one.


text:
How to upload Arduino sketches to Atmel chips
I am new in this Arduino coding world and I was trying to make a project. I normally used Arduino Unos all the time, but I was facing a problem and that is that the Arduino Uno has only 13 digital pins and 6 analog pins, and some of my friends advise me to use an Arduino Mega, but that costs too much, some to my friends also tell me that I could use only a Atmel chip, which will save money.
But the problem is that I can not burn these chips without a burner. I see online that Arduino Uno has Arduino ISP options also that will allow you to bootload or upload Arduino sketches to those kind of chips, but I have been trying for over 3 months and I cannot figure out how to do that
At present I am working with the ATmega8 chip.
This is my problem:

Using stk500v1 but the problem is not resolved

How many pins do you need? It is actually 19 digital pins and 6 analog pins. The analog pins can be used as digital pins. A typical issue when using an Arduino as an ISP is forgetting to use a resistor or capacitor connected to the reset pins to avoid reset and running the bootloader. The ATmega8 might be an issue as well. Which core are you using for that?

@MikaelPatel I need 22 digital pins and 7 analog pins, I am using 10 mf capacitor in arduino capacitor VCC side is Arduino RESET and GND side is Arduino GND

@MikaelPatel: I did not find any core?

Seems like the atmega8 is an older AVR chip and compatible with the pins on atmega328 https://www.arduino.cc/en/Main/Standalone. Smaller memory size and the same number of pins (digital/analog).

@MikaelPatel: Sir at this time I am just testing how it works, When I figure out I will us ATmega 16 ARV Chip

Try option "-cstk500v1" instead of "-c arduino".

@MikaelPatel: OK sir

The problem is not solve
http://www.softbazz.com/jja.jpg

Time to check the wiring from the Uno to the ATmega8.

Arduino pin name: reset: 10: , MOSI: 11:, MISO: 12:, SCK: 13:       Atmega Chip pin: 1 (PC6), 17 (PB3), 18 (PB4), 19 (PB5)

And I also using 10uf capacitor

Add option "-v" to get more info from the upload.

I hate to be that guy, but a USBasp clone costs little and would likely be delivered long before 3 months had passed.

@IgnacioVazquez-Abrams +1 for saying it before I cracked. Fortunately I was out most of the day.

Do not really see how that would help :) This is all about helping with hardware debugging (as I see it). Small steps forward to understand where the problems are. Even better would be to just sent the HEX file off to a company that did all the work for you. But where is the fun in that.

It wouldn't solve the problem, but it would get the job done. Which is why I posted it as a comment instead of an answer.

You say the problem "needs 22 digital pins and 7 analog pins" which is 29 pins. ATmega8/16/328 come in 28 and 32 pin packages. Several pins are used for ground and power, and the reset pin should be left free too. So it is not possible to have 29 pins. So what is your plan to create 29 I/O pins? The options are: a) use multiple ATmega chips, b) use some sort of I/O extender (e.g. shift register, multiplexer, etc), or c) use a different chip?

First thing you need to do in this situation is to crank up the verbosity level on the invocation of avrdude. You do this by adding one or more -v flags to the command line. With -v -v -v -v, you get maximum verbosity.
From your two logs, it appears that the initial handshake with the microcontroller was successful (which would indicate that your connections were good), but then the signature reading turns out quite badly. This is a rather unusual combination which makes me wonder whether you may have misidentified what microcontroller you have.

I was just trying in our way, and this is the result,

http://www.softbazz.com/main.html

That confirms that the initial handshake was good, so your connections must be OK, but that somehow a nonsense signature was read. This is puzzling. Unfortunately, the ATmega8 is quite old, so I'm not sure what could be going wrong here.


text:
Can't send HTTP request using ESP8266 and Arduino Uno
I have an Arduino Uno and for Wifi an ESP8266.
My ESP8266 Firmware is
AT+GMR

AT version:0.40.0.0(Aug  8 2015 14:45:58)
SDK version:1.3.0
Ai-Thinker Technology Co.,Ltd.
Build:1.3.0.2 Sep 11 2015 11:48:04

baund = 115200,
 Both NL & CR

Server -- www.linysoft.com
The URL I want to send is either: http://www.linysoft.com/arduino/?light=off OR http://www.linysoft.com/arduino/?light=on.
Depending on to the link I send the result should be either ==> on or ==> off on the page http://www.linysoft.com/arduino/light.json.
Now I want to send an HTTP request (Weblink - http://www.linysoft.com/arduino/?light=on) so it can write according to that link "on" in the light.json page.
The AT command I am sending (my wifi module is connected to my wifi automatically):
WIFI CONNECTED
WIFI GOT IP

AT+CWMODE=1

OK

AT+CIPMUX=1

OK

AT+CIPSTART=0,"TCP","www.linysoft.com",80

0,CONNECT

OK

AT+CIPSEND=0,200

OK
>

Here I am getting a problem after this > I can't send **GET /arduino/?light=on**. I also tried GET /arduino/?light=on HTTP/1.0\r\n.
After putting this line in the textbox, I press the Enter button or Send Button, but nothing happens.
It is stuck here > for some time. And then it shows me:
OK
> 0,CLOSED

Pin Connection
ARDUINO UNO        ESP8266
RX  -------------->  TX
TX  --------------> RX
VCC--------------> 3.3
CH_PD ----------> 3.3
GND -------------> GND

What technology are you using to connect to the Internet, and hence to "www.linysoft.com"? How have you checked that WiFi access point, and internet connection works?

Is there other solution to these problem ?

linysoft.com is a virtual host. Just try going to http://100.42.56.28/ and see that the connection is reset.
So after the GET /arduino/?light=on, you have to also send Host: www.linysoft.com (on the next line).

The domain is missing. Try this instead:
GET http://www.linysoft.com/arduino/?light=on HTTP/1.0\r\n\r\n

Cheers!
Ref. http://contractorwolf.com/esp8266-wifi-arduino-micro/

I didn't know that was allowed in HTTP, as browsers use the Host header. But apparently using an absoluteURI is allowed.

Just found out a POST wouldn't work. Try this GET request to turn on the light.
    GET /arduino/?light=on HTTP/1.1\r\nHost: www.linysoft.com\r\n\r\n

Then you can get the status of the LED by GETting light.json like this:
    GET /arduino/light.json HTTP/1.1\r\nHost: www.linysoft.com\r\n\r\n

I was having same problem and this one solved the problem that after you get a '>'
sign then write
GET http://linysoft.com/arduino?light=on HTTP/1.0\r\n\r\n(or if you are directly writing this on serial monitor then press enter key twice and then wait for somemoment like 2-3 sec in this case dont put \r\n\r\n)
If this didnt worked then try
GET http://linysoft.com/arduino/?light=on HTTP/1.0\r\n\r\n
But in this I guess you need to specify arduino.php or arduino.html whichever type you have
and too you have to take care the cipsend should be the byte no of get request excluding \r\n\r\n and add 4 to it because we are too sending \r\n\r\n these are 4 character
I hope this will surely work for you

authors: Кристиян Илиев


text:
Sending number as byte through serial
I'm trying to send data from an Arduino to an Android device.
I saw an online guide for that which provided this code:
void setup()
{
  Serial.begin(115200);
}

void loop()
{
  byte msg[64];
  int len = Serial.available();
  if (len > 0)
  {
    len = Serial.readBytes((char*)msg, sizeof(msg)); // readBytes seems to need a char* not a byte*
    Serial.write(msg, len);
  }
}

I tried that example and it is working perfectly!
But when I put Serial.write("3");
in the setup loop after Serial.begin(115200);
it appears as question mark on my Android device,
I guess that I'm not sending it as a byte,
I searched online but without any luck.

What appears in the serial terminal when connected to a PC?

How are u communicating with the android device? Don't u mean that you are sending data from your PC to the android, through the arduino?

It sounds like you have the Arduino hooked up to the Android via a USB cable and are using a terminal emulator on the Android to communicate with the Arduino, with the code in loop() doing a simple echo of what you type in the terminal emulator. Is that right? Everything works using the example above, but when you modify it to send the string "3" to the Android, kind of like a prompt, the "3" is not displayed correctly. Am I missing something?

Start by changing it to Serial.write("3", 1);
Does that help, you're missing the second parameter to the Serial.write call, which is the number of characters (bytes) to write.

The second parameter isn't necessary for c strings, it will read until it sees the null terminator https://www.arduino.cc/en/Serial/Write

I think this is a timing issue. It is fairly normal for a garbage byte or two to be received shortly after doing a Serial.begin() because the transition of "not defined" (or high impedance) output to Serial (which is normally all 1-bits) can cause the receiver to think it got a start bit, and then misinterpret what follows.
Try adding a short delay after Serial.begin. You could also try a pull-up resistor on the serial Tx line to ensure it is high prior to Serial.begin being called.
Your use of Serial.available effectively builds in a delay.


text:
NRF24L01 Connection Not Working
I have an ATTiny85 connected to an NRF24L01+ module using this wiring diagram: diagram. The ATTiny85 periodically goes in and out of sleep to send some value to a receiver, an Arduino Uno. If the ATTiny is running off the Arduino power supply (3.3v), everything works correctly. When I run the ATTiny off of a separate CR2032 coin cell that delivers around 3v, the Arduino never receives any data. I have a status LED hooked up to the ATTiny to ensure that the ATTiny is waking correctly, which it is. Here's the code for both:
EDIT:
Connecting it to an external 3.3v not from the Uno makes everything work - why wouldn't the coin cell's voltage work? I think everything is rated below 2.8v, the CR2032 minimum.
ATTiny Code
#include <avr/sleep.h>
#include <avr/interrupt.h>

// Routines to set and claer bits (used in the sleep code)
#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

#define CE_PIN 3
#define CSN_PIN 3 //Since we are using 3 pin configuration we will use same pin for both CE and CSN

#include "RF24.h"

RF24 radio(CE_PIN, CSN_PIN);

byte address[11] = "SimpleNode";
unsigned long payload = 0;

void setup() {
  radio.begin(); // Start up the radio
  radio.setAutoAck(1); // Ensure autoACK is enabled
  radio.setRetries(15,15); // Max delay between retries & number of retries
  radio.openWritingPipe(address); // Write to device address 'SimpleNode'
  pinMode(4, OUTPUT);
  digitalWrite(4, HIGH);
  delay(500);
  digitalWrite(4, LOW);
  delay(500);
  digitalWrite(4, HIGH);
  delay(500);
  digitalWrite(4, LOW);
  delay(500);
  digitalWrite(4, HIGH);
  delay(500);
  digitalWrite(4, LOW);
  delay(1000);
  setup_watchdog(6);
}

volatile int watchdog_counter = 0;

ISR(WDT_vect) {
  watchdog_counter++;
}

void loop()
{
  sleep_mode(); //Go to sleep!

  if(watchdog_counter >= 5)
  {
    digitalWrite(4, HIGH);
    watchdog_counter = 0;
    payload = 123456;
    radio.write( &payload, sizeof(unsigned long) ); //Send data to 'Receiver' ever second
    delay(1000);
    digitalWrite(4, LOW);
  }
}

//Sleep ATTiny85

void system_sleep() {

  cbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter OFF

  set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here
  sleep_enable();

  sleep_mode();                        // System actually sleeps here

  sleep_disable();                     // System continues execution here when watchdog timed out

  sbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter ON

}

// 0=16ms, 1=32ms,2=64ms,3=128ms,4=250ms,5=500ms
// 6=1 sec,7=2 sec, 8=4 sec, 9= 8sec
void setup_watchdog(int ii) {

  byte bb;
  int ww;
  if (ii > 9 ) ii=9;
  bb=ii & 7;
  if (ii > 7) bb|= (1<<5);
  bb|= (1<<WDCE);
  ww=bb;

  MCUSR &= ~(1<<WDRF);
  // start timed sequence
  WDTCR |= (1<<WDCE) | (1<<WDE);
  // set new watchdog timeout value
  WDTCR = bb;
  WDTCR |= _BV(WDIE);
}

Receiver Code
#define CE_PIN 7
#define CSN_PIN 8

#include <SPI.h>
#include "RF24.h"

RF24 radio(CE_PIN, CSN_PIN);

byte address[11] = "SimpleNode";
unsigned long payload = 0;

void setup() {
  while (!Serial);
  Serial.begin(115200);
  radio.begin(); // Start up the radio
  radio.setAutoAck(1); // Ensure autoACK is enabled
  radio.setRetries(15,15); // Max delay between retries & number of retries
  radio.openReadingPipe(1, address); // Write to device address 'SimpleNode'
  radio.startListening();
  Serial.println("Did Setup");

}

void loop(void){
  if (radio.available()) {

    radio.read( &payload, sizeof(unsigned long) );
    if(payload != 0){
        Serial.print("Got Payload ");
        Serial.println(payload);
    }
  }
}

Is the problem here that the ATTiny and Uno need to be turned on at the same time to establish a connection, or is it something to do with the battery, or something else entirely? Any help would be appreciated.

Yes, receiver needs to be listening while another one is transmitting to receive packets.

Also, try setting the PA level lower.

Coin cells can't deliver a lot of current. To account for the short bursts of higher current (during transmission) you can put a capacitor in parallel to the battery.

Good call, I'll try it with a capacitor. Would 10uF be not enough, or too much?

Experiment. Also set the PA level lower so that the radio would consume less power. https://tmrh20.github.io/RF24/classRF24.html#adedac579590a668ae97baccab284de8a (You are using https://github.com/TMRh20/RF24, right?)

Didn't know that I could do that with the RF24 library, thanks. I'll try some different capacitor configurations.

I was just researching the exact question and I have some bad news.
The ORIGINAL nrf24l01+ alone use around 10-12 ma in transmitting, but unoriginal might even draw more. (https://www.sparkfun.com/datasheets/Components/SMD/nRF24L01Pluss_Preliminary_Product_Specification_v1_0.pdf)
Nevertheless a standard CR2032 battery is simply not made to supply more than a few milliamps at the best, leaving your nrf24L01+ lacking enough current.
There is something called shockburst which can lower your consumption considerably at the cost of range - but if it will succeed in transmitting with one CR2032 I'm not sure about.
Edit:
If you add a capacitor you need to cover at least a 10ma drain for around 15ms (turn on - send - turn of immediately), that will require a minimum of a 200µF capacitor at 3V to be able to deliver the current while keeping above 2.0v.

Hmmm... this is very good to know. I had some 100µF capacitors lying around and, after testing, it appears that it is transmitting, albeit after setting the PA level to its lowest setting. Not sure if it works on a higher PA level. Looks like that capacitor seemed to do the trick.

Glad to hear it, I used values think you should have enough power

I tried to say you likely have enough capacitance for high PA level if it is burst only. Otherwise you could add more capacitors - or switch to a power source with higher current capabilities


text:
Pinout for Leonardo USB
According to the docs, the Arduino Leonardo uses digital pins 0 and 1 for the USB D- and D+ lines. However, which is which? e.g. is D0=D+ or is D1=D+?
To save space in a very tight project, I want to wire USB directly to these pins instead of using the USB plug, however, I can't find any resource that explains which pin goes to which USB line.

Where does it say that pins 0 and 1 are D+ and D-?

"The ATmega32U4 provides UART TTL (5V) serial communication, which is available on digital pins 0 (RX) and 1 (TX). The 32U4 also allows for serial (CDC) communication over USB and appears as a virtual com port to software on the computer."

I think you are completely misunderstanding what it is saying there. The UART TTL and the USB are two completely different things. The UART is on pins 0 and 1, and a USB CDC/ACM connection is also provided (dedicated pins on the chip).

The USB does not go to pins 0 and 1.  The UART goes to pins 0 and 1 - that is a totally different interface.
The USB is connected to dedicated USB pins on the chip.  If you look at the Leonardo schematic you can see it is pins 3 and 4 on the chip. Note that that is not pins D3 and D4 on the board, but the third and fourth pins anti-clockwise from the "pin 1" dot on the main chip.

As shown in the ATmega32U4 datasheet, D- and D+ connect to pins 3 and 4 respectively of the MCU. But you don't want to wire directly to the chip unless you know what you are doing since the chip does not include the USB termination resistors. Follow the schematics given in the datasheet when connecting to the USB pins of the MCU.


text:
Do I need a lot of Arduinos?
I would like to make a smart home using Arduino. My system must be wireless. I want to control power outlets and lamps and I want to be able to turn off and on power outlets and lamps wirelessly, using my android app, using nRF24L01.
Do I need an Arduino for each power outlet and lamp? Do I need to put an Arduino, nRF24L01 and relay inside each power outlet and lamp?

Might I suggest using off the shelf remote controller power outlets. You can control these outlets using a single 433mHz transmitter. Probably about the same price as an Arduino+NRF24+AC-DC adapter+Relay, and already in a convenient package. They are also available in lamp socket. It also means you don't have to touch AC-mains.

You might also consider using ESP8266 + relay combinations, instead of Pro Mini + nRF24L01 + relay sets.  An Arduino IDE setup is available to support C code on ESP8266 systems (1,2,3).
Note:  As a consequence of its higher clock speed and larger RAM size (80 MHz or 160 MHz clock, and 80 KB DRAM, vs Mini's 16 MHz clock and 2 KB SRAM) a typical ESP8266 board uses more power than a Pro Mini + nRF24L01 does.  According to nrqm.ca/nrf24l01, the nRF24L01 draws around 11 or 12 mA when sending or receiving, and  22 μA in low-power standby mode.  According to wiki.iteadstudio.com/ESP8266_Serial_WIFI_Module, an ESP8266 draws ~ 60 mA receiving and 135–215 mA sending.  (That current range covers a power output range of 5.5 dBm.  It probably supports a much bigger communication area than nRF24L01 does.)  Of course, if all your installations have mains power available, the power requirements might not matter much to you.  Note, ESP8266 boards typically run on 3.3 V power instead of 5 V power.
As far as cost goes, at the moment Pro Mini clones cost about $2.15 each.  nRF24L01's run about $0.90.  ESP8266 modules are $2–$3 depending on model and level of module (1,2).  You might save a few dollars on your whole system using ESP8266's, but the smaller-sized electronics they provide probably is more important.

One arduino can control multiple relays. Beyond that, how many you need will depend on the details of your project.
Once you have a working example, you can build it using less expensive alternatives than regular Arduino boards.

I need 22 arduino pro mini + 22 relay + 22 nRF24L01 and main arduino


text:
ESP8266 (connected to Arduino) only works when plugged into USB power
The Wi-Fi connects when the Arduino is powered by my computer and a serial console is connected, but not if I plug into an outlet.
UPDATE
It seems this is a power issue. I am powering the esp8266 from the Redboard 3.3v line that is only rated for 150mA. I will be switching to the 5v line with a 1A regulator.
I also switched to 9600 baud for communicating with the esp8266, added retries around all of esp8266 commands, and added reconnect logic in case the esp8266 reboots. With the changes, it works okay even with the underpowered 150mA line.
It's still a mystery to me why it works so well when connected to my Macbook.

Another thing to note is that you are likely to run into issues using SoftwareSerial at 115200.  If you need to use SoftwareSerial, best to drop the baud rate.  Depending on your firmware, the AT+IPR=9600 command should work.  If you're getting garbage responses coming through from the ESP8266, this is the likely culprit.

It sounds like your power supply is inadequate to the task.
The ESP8266 is notoriously finicky about having a noise free power supply capable of delivering a lot of instantaneous power. If you are using a wallwart style supply it should promise at least 1A and more is better. Even though the actual use is more like 250 mA.


text:
I want to pour 500ml of Water in jar with Arduino water flow controller?
I want to pour 500ML of water with Arduino water flow controller with maximum accuracy.
How will I get the maximum accuracy with this sensor?
Could someone can give suggestion for accuracy or any other sensor that i can use?

What flow controller? What accuracy?

I want to fill jar with 500 ml of water. I thought this can done with two ways either water flow controller sensor or Ultrasonic sensor. Is water flow controller sensor will pour accurate 500 ml  into jar. If it pours more or less  then my marking on jar will fails. so that' why i want accurate performance.

option three is using a scale (i.e. weigh the water). Forth option is a Liquid Level Sensor. There are probably even more solutions. PS you still haven't told what flow-controller-sensor you are using!

What flow sensor? Why is water flowing both directions through the pipe? How much money have you for 'maximum accuracy'? i.e., What accuracy do you really require? How will you turn off your water? How will you allow for the amount of water between the valve and the jar if the flow rate changes?

Flow Sensor / Fluid FLowmeter Control Switch YF-S201

Above sensor offers +/- 3% Accuracy Please refer below video https://www.youtube.com/watch?v=CtgP6Ewtinc

And you still have not updated your question with the information requested by multiple users.

The flow meter you specified, YF-S201 Hall Effect Water Flow Meter (datasheet) measures the water flow rate, producing signal output frequency in range 16Hz (at 120L/H) to 90.2Hz (at 720L/H). Datasheet claims "error range +/- 10)". Note that this only measures the rate of flow, it is not a valve and so does not control the flow.
Problem with using a flow rate sensor to measure total quantity of water, is that you must constantly integrate the flow rate over time to get the total volume. Any errors in rate measurement or integration time, will accumulate; so this is generally not an accurate approach. Cumulative errors are highly undesirable, because they are difficult to detect and compensate. You have to not only measure the output frequency, but also carefully control the time between measurements, because you are integrating over time. This will be even more of a problem if you are printing out messages to the serial port.
If the water supply is well regulated and always provides a steady flow, then you will open the valve for a specific time interval. But if the supply pressure is not well regulated, then you may accumulate integration errors and dispensing will not always be accurate.
If you care about dispensing precisely 500mL of water, a more practical solution is to use a weigh scale (load cell). First, measure the tare weight of the empty container, then dispense (using a control loop) until net increase in weight is 500g. With this setup, the dispenser accuracy is determined by the load cell repeatability error (0.1% for a good quality load cell, a couple % for a fair quality load cell) and the measurement accuracy of the ADC (depends on resolution and reference voltage stability). You could try using the Arduino's on-chip ADC which is only 10 bits, or for best accuracy use a real 24-bit weigh scale ADC. The load sensor's offset error is set to zero by measuring the tare weight of the empty jug, so you only need to be concerned about gain error at 500mL and repeatability of the load sensor. This approach does not have cumulative errors.
You have not specified what kind of valve you will use to control the flow. If you use a solenoid value, the valve is only on-or-off, there may be some overshoot due to valve reaction time (10ms), so you will need to experiment and determine an "off threshold" before reaching 500g.
Since you have no way to compensate if the system overfills the jar, you will need to dampen the system response so that it slows down as it approaches the target level, without overfill. I'd therefore suggest using a proportional valve instead of a solenoid valve. Start with a fast flow rate when net weight <400g and then switch to a slower rate as the jar reaches its target weight.

I suppose that you already found a solution. If you haven't, one inexpensive way for the Arduino to sense when the water reaches the desired level is to drill two thin parallel holes into the container (using a wire gauge drill bit, provided you're not using glass or something difficult to drill) slightly below the "trigger point." Then, you can insert two thin strands of conductor so that they protrude a millimeter or less inside the container(consider something like graphite 0.5 mm pencil leads to prevent corrosion). You'll need to seal the holes using epoxy. If you make a voltage divider and put these two pencil leads in the place of the second resistor, you can measure the resistance change (using an Arduino analog input pin) when the pencil leads are "connected" by the water. Once you find the ADC value for the "water full" state of your connection, you can make the Arduino turn off the flow when this value is detected. You should place the pencil leads below the "trigger point" so that you can experiment with different delay periods between sensing the water and turning the flow off (to compensate for the water that remains in the pipe "downstream" the flow controller. I've used this approach successfully to measure flow rate, but I can't guarantee it would work in your application.

You haven't specified what level of accuracy you are aiming for so I have assumed 0.01ml.
What ever solution you go for you will also need an accurate temperature and pressure sensor, because these will affect the density of the water.
Each individual sensor you use has a degree of error associated with them.  You would nee to calibrate each sensor to establish what level of error each individual instance of a sensor has.
Weight would seem to be the best solution.  Surface tension could affect a flow metre or a contact sensor.  I have to be honest I don't see how an ultrasonic sensor could give you any degree of accuracy.  With a weight sensor you would need to establish the dry weight of the container then pour the liquid in until the desired volume was achieved.  A quick response to close the very end of the inlet pipe would be required to prevent un-necessary drips.
As to marking the container, are you using some computer controlled marking tool, because if you are just drawing on the side with a Sharpie you may as well use a measuring jug. :)
You should be able to get a weighing PCB, a pressure and temperature sensor off any of the usual electronic sites to suit you budget and the libraries will be on Git hub.

Another option is to use a stepper motor and a Peristaltic Pump (or IV pump). You can use this to control the flow rate AND volume. For speed you need to make the motor run faster and for volume just run the stepper motor x times to get x volume. I do not know how precise it is. Good luck with what ever option you pick.


text:
Negative voltage: How do I scale a 0 to 5 V signal to -10 V to +10 V?
To control my robot, I need to generate negative and positive voltage in a single line, because the motor I try to control is an industrial one.
Do you have any suggestion for it? How can I produce a negative voltage using an Arduino board and simple electrical elements?

wire a positive voltage in reverse?

It would help if you could be specific about the motor that you want to control.

The servo-pack takes the voltage in single line from -10v to +10v. Usually motors have two pins to control the direction and velocity. But, in our servo-pack, one pin is ground and the other one takes a voltage in the interval of [-10,+10].
I want to control this motor using an Arduino Uno.

@BrettAM I need to change the direction of motor with my control circuit and I just have the positive output of Arduino. Where should I put this single output line to inverse the direction?

Can you provide a link to a datasheet for the motor? How does the +/-10V relate to how the motor works?

Can't you use an H-bridge for this?

[link] https://www.yaskawa.com/pycprd/lookup/getdocument/jvgyvE5ZTUY_5CC1znzBoe-iyvC0118s_1GfGe382go7iz9ltcbQkMVMhVN8L5K3hXb6Zpv5R6zVrH-_NQ6U3hPPUoT2-nMfM5mD23cQKH7xVWeJTen95A
this is a link to the catalogue. You can find the information in p160 for torque control for instance.
It's impossible to use H-bridge for this servo-pack. Because one of the pins is ground. In H-bridge, we have access to two pins in motor to control the direction. Here we have just one pin.

@Gerben, no he can't. He's driving a servo amplifier, not a motor. He needs to generate a control voltage ranging from -10 V to +10 V. See my answer.

Your question should read:

How do I scale a 0 to 5 V signal to -10 V to +10 V?

First write the conversion formula:
Vout = 4 * Vin - 10

Testing the formula gives the following:

Vin = 0.0 V ==> Vout = -10 V
Vin = 2.5 V ==> Vout = 0 V
Vin = 5.0 V ==> Vout = +10 V

You will need an op-amp circuit to create this function. In addition you will need a +12 and -12 V supply.

simulate this circuit – Schematic created using CircuitLab
How it works:

OA1 is an op-amp wired in an inverting summing amplifier configuration. We'll address the inversion later but for now all the answers will be "upside-down". The gain is set by -R2/R1 = -40k/10k = -4. If we feed 1 V in from the ADC we will get -4 V out.
R3 provides a negative input. The gain will be set by -R2/R3 = -40k/48k = -5/6. Since it's connected to -12 it will contribute +10 V to the output.
The actual output will be the sum of the two: in our example, +10 - 4 = 6 V.
C1 and C2 provide noise filtering for the op-amp. Place them close to the chip.

Now, what to do about the inversion? We have three choices:

Fix it in the micro controller code. Set +5 V as maximum reverse speed / torque. Set 0 V as maximum forward speed / torque.
Fix it in the servo amplifier and tell it to reverse its command signal.
Fix it in the electronics. By adding another inverting op-amp we can turn the signal the right way up.

The TL082 opamp suggested has two op-amps in the one 8-pin package.
Ref: Inverting Summing Amplifier.

Servo Enable

simulate this circuit
Delay the servo enable until the micro controller has initialised and all other functions are ready. See manual Section 3.2.3, page 73.
Note that this is a simplified relay drive schematic. You need a transistor drive and a snubbing / flyback diode around the relay so one of the small 5V relay boards would be a good solution as they are already built in. An opto-isolator would be simpler.
Ensure that safety circuits (guarding and e-stops) are correctly wired using safety-rated components (and not only, for example, the micro).

Thank you so much for your complete answer. I am going to make the circuit and may ask more questions when I finish making it. One more time, thank you for the detailed answer.

This circuit seems to have an issue. When the Arduino is not fired yet, if the motor is turned on, it will rotate with the maximum torque in negative direction. Which may damage our system.
One solution comes to my mind to solve this. We can use a 74HC4052 to scale the voltage to [-5,+5] and then use an op amp to gain this value. Am I right?

You should already be using Servo Enable to inhibit the drive until the controller is ready. See update.

I'm back after so long :).
Actually the circuit works but not well. There is an offset in output. After lots of searches, I found that there are other solution for this problem. For instance, it is possible to use an IC which is called Digital to Analog converter. Do you know how can I handle the problem using that IC? Because the output of abovementioned circuit is not precise and reliable.

P.S.: my system has high band width and accepts pure analog voltage as input. That's why I came into the idea of using DAC.

The Arduion PWM output is a form a DAC. It is precise and reliable. You need to figure out why it's not working. Post a schematic of your system. There's a schematic button on the editor toolbar.

PWM output of Arduino has the strict frequency of 490 hz while my motor's bandwidth is 1.6 khz. Consequently, when I run the motor using the Arduino PWM it rattles.
My circuit's problem is the voltage offset of the op-amps. Even when I simulate the circuit, it works well, but in practice, there is an offset voltage on the output pin of the op-amp.

(1) What offset voltage do you get? (Measurement, please.) (2) What is the -12 V actual voltage? (3) What are the measured values of R1, R2 and R3?

The PWM signal alternates between +5 V and 0 V. Did you forget that you'd need to low-pass filter it? Start with an RC filter with a cut-off of half the PWM frequency. What is your last comment about? If it's a link it's broken.

Sorry about my late reply. When I wanted to measure the required information, I realized that, mysteriously, my circuit, which had .3v offset, now works fine (with .03v offset). Actually the circuit I have implemented is different than yours. I used a 74HC4052 to make a bipolar differential line (similar to controlling a dc motor with an H-bridge). Then I used differential amplifier configuration for my op-amp. The output of the IC is two line and using differential amplifier, I combined them together. But, even if this problem has been solved, the frequency problem is still remained unsolved.

The current frequency of PWM (490hz) is unacceptable for my system. If I add a low pass filter to it, it will add a delay to it too. I should find a way to increase the frequency of PWMs.

What kind of motor and load are you actually driving that needs a 250 Hz response?

I want to control the tension in a cable (actually in a cable-driven robot) and the band-width of the motor is more than 1Khz. But, at least I must reach to 1Khz.

"transistor" has walked you through what is necessary. Just an additional point of note: if you don't have a +/- power supply, you can easily generate the negative voltage using eg ICL7660 or even using a 555: https://www.ikalogic.com/555-based-voltage-inverter-schematic/
Just because I'm curious, could you add a link to the servo datasheet?

you can find the link in the 7th comment of the first post.


text:
Why does Ethernet.begin() require a MAC address when WiFi.begin() doesn't?
I am working on an Arduino application which is dependant on a certain library. This library uses the Ethernet class for network communications, but ideally, I would like it to be wireless (I have both an Ethernet and WiFi shield available for testing).
When working on replacing the Ethernet functionality of the library with the corresponding WiFi functionality, I noticed that the Ethernet.begin() function requires a MAC address while the WiFi.begin() doesn't (it instead accepts SSID and password, among a couple of other things).
As both come shipped with a MAC address sticker on them, I couldn't really figure out why this is the case (and if I need to supply the MAC address found on the WiFi shield in some other fashion).
Why is this the case?

The flip answer would be "because it doesn't need it…"
I think what is going on is that older Ethernet shields did not have a MAC address and it was necessary for the code to set one (and I would guess that on at least some of them you can still set the MAC address, overriding the one that is on the sticker).
WiFi cards, I would guess, are newer and the MAC address is always there, so there is no need to require you to assign it.

I think this is because [most] WiFi cards already have a firmware, which holds the MAC address and that's why changing it on a WiFi card is only possible if the firmware allows it. With Ethernet there is no firmware needed, or simply put the Arduino is the firmware.


text:
How to clear of contents of string in Arduino?
Currently I convert the characters in char received[20] to string using String randomString(received) and I am able to display it using Serial.println(randomString). After displaying the string, I would like to know the easiest way to clear out its contents.

Have a look at the related question at stackoverflow: http://stackoverflow.com/questions/632846/clearing-a-char-array-c ...

Why are you converting a char array to a String just to print it? Do you realise just how bad that is for the poor little Arduino? http://hacking.majenko.co.uk/the-evils-of-arduino-strings

In C and C++ a null terminated array of characters is a string (although not a String). Many routines for reading input terminate the result with a null as does an assignment like"
char foo[] = "This is a string.";

All you would need to do to "clear" this string is to assign a null to the first character. For example:
foo[0] = '\0';

This clears only the first byte. With = { 0 }; everything is cleared.

For C (null terminated) strings, if the first character is a null, then the string is empty or clear. Functionally that solves the problem, but if there are security concerns then you are right that the whole string should be cleared.

First version with conversion from char[] to Arduino String class:
char received[20];
...
// Some code that assigns received
...
String randomString(received);
Serial.println(randomString);

// Clear string
randomString = "";

Second version without the Arduino String class:
char received[20];
...
// Some code that assigns received
...
Serial.println(received);

// Empty received buffer
received[0] = 0;

And third version where the buffer is cleared:
char received[20];
...
// Some code that assigns received
...
Serial.println(received);

// Clear received buffer
memset(received, 0, sizeof(received));

Cheers!

Although an old question, I thought I would chime in. If I took the time to understand the question properly, I believe you wanted to clear the contents of the String and not the char array. This may help those who wanted to empty a string for other reasons.
String randomString(received);
Serial.println(randomString);
randomString.clear(); // This will clear the string

It should be noted that for outputing, there was no need to convert to string first if that was all that was required, because println will prefer a char array anyway.
Again String has a .clear() method for those who reached this page via web search.
Update:
It has been pointed out thanks to @VE7JRO in the comments, that the clear methods availablity is not universal. The ESP devices with Arduino compatibile core libraries do have it, as may others. But AVR devices such as the UNO do not. Which I have confirmed.
A revised version to suit all cases where the .clear method is unavailable.
String randomString(received);
Serial.println(randomString);
randomString = ""; // This will clear the string

Arduino IDE 1.8.9 says this about the clear() function "'class String' has no member named 'clear'". What version of the IDE / other software are you using?

@VE7RJO Using platformio, it shows the method. Which I have alreay used in code. It may depend on whether using AVR or the ESP's but it is certainly present on the ESP8266.

The OP's question "title" mentions "Arduino", which as far as I know is not an ESP8266. Perhaps another Arduino user with a newer version of the IDE could confirm / deny whether this woks or not.

@VE7JRO Have revised after testing. Thanks.

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


text:
Can I set an Arduino pin as input and output?
When I used to program PICs, there was a way to set the pins to input and output, at the same time. Can this be done on the Arduino?
I see the pinmode documentation, but nothing about being an IO port.

Ok, please explain this better. I think you just forgot the "set the pins to Input AND OUTPUT, at the same time". If so, please explain what you mean by "input and output". You want to set the value and then read the same value?

Or do you want to set a group of pins at the same time using a mask? If so, check here: https://www.arduino.cc/en/Reference/PortManipulation

Are you asking if you can do something like creating a memory interface or the control register of a hardware device where you would both read and write data?

No there is no function that lets you set all the pins to either input or output at the same time, but it wouldn't take much to write one.
No, you can't set an Arduino's pin as bidirectional.  If you are running out of pins look at IO expanders or multiple Arduinos.
Hope that helps, if not please feel free to clarify what it is you would like to know and we'll try and help.

I’m not running out of pins, I’m using a piezo electric wafer as a sensor, but after it senses an impact, I'd like it to then mimic the impact (in sound). Sure, I can use 2 peizo electric wafers to do that, but if there were a way to only use, one, I would be very interested. maybe I can toggle the pin mode. I'll look into that.

Surely you want the pin to be an input, and once you get an impact turn it into an output.

@j0h like Nick says you can alter the mode of a pin at runtime (i.e. in the loop function). Would that be enough to achieve what you want?  Of course it will meant there is a period where you won't be able to receive new signals.
Could you use two pins and run the input through a transistor that is normally closed unless the output pin is sending out a signal (to prevent a feed back loop)?

yeah, I looked at how a 3 pin ultra sonic sensor works, using the ping function from USsensor.ino, and realized that the pinmode is being changed. Its a fix. Thanks guys!


text:
Controlling an LED using a transistor (TL188)
I wanted to control an LED using a transistor (my first attempt at using a transistor). I connected a transistor (TL188) to pin 13 of an Arduino Uno accidentally and noticed something.

(The resistor I used was 150 ohms, and I forgot to change the resistor value in the diagram.)
The program on the Arduino Uno was the basic Blink sketch. As per the program, the LED on the Arduino Uno was supposed to turn on for 1000 ms and turn off for 1000 ms. But when I connected the LED like the diagram below
For the first 1000 ms delay:

LED on pin 13 stayed on
LED connected using the transistor stayed off

For the next 1000 ms delay:

LED on pin 13 stayed partially on (it was dim)
LED with the transistor was on

I know that the connection that I made is completely wrong. Can someone explain me how and also why the LED on the Arduino Uno was dim?

Your transistor is a PNP transistor. They are slightly harder to work with than NPN transistors. I would suggest starting with an NPN transistor as a low side switch first before stepping up to PNP transistors.

Okay,. But the reason i used a PNP was, I have a bunch of 7segment LED(common anode type). so before connecting a segment i wanted to just try connecting an LED.

@Rob It's not too bad if all your voltages are the same - it's when you start trying to switch higher voltages with a lower voltage signal that you get difficulty - you can't get the base voltage up to the level of the emitter to get it to turn off. You then need extra drive circuitry or other trickery.

Did you connect ground correctly? Looks like an external power source (battery) but not ground is not common.

If you provide complete details of your setup So, giving specifics as I think it would help understand the maths, if you have say a 10 3.4v\25ma LEDs in 5 sets of 2 LEDs with a 100ohm resistor on each pair connected to a 9v supply along with an Arduino Nano (5v\40ma PWM output pins) with say a 2N3904 transistor (NPN, 200ma max, ~0.7v drop, 100-300hfe I think) how do you calculate "a resistor in the range 1K to 2K should do"?

You should have a resistor of a few hundred ohms on the base connection of the transistor - that is, between base and pin 13.
A PNP transistor is somewhat harder to get to grips with than an NPN transistor.  Much of it does things backwards.
The operation you see seems to be completely correct when you understand how a PNP works.
With and NPN transistor a high voltage on the base turns it on and a low voltage turns it off. The opposite is true with a PNP transistor.
When you have a voltage close to or above the voltage at the emitter the transistor will be off.  That means, providing a HIGH to the base will turn it off.  A voltage on the base that is below the emitter voltage minus the threshold voltage of around 0.7V will turn the transistor on.  That means providing a LOW to the base will turn it on.
So that means that when the on-board LED is on the transistor is off, and so the LED on the transistor will be off.  When the LED on the board is off the transistor will be on, so the LED on the transistor will be on.
"But", you say, "the on-board LED doesn't turn off".  That is correct. It just gets dimmer.  That is, again, because of how the PNP transistor works.  Current (seen from the conventional sense - i.e., flowing from + to -) enters the emitter and is then split between the collector and base. The amount of current allowed to flow out of the base defines how much is allowed to flow out of the collector (in an NPN it's current into the base and collector that combine to flow out of the emitter, and the amount that is allowed to flow into the base defines how much is allowed to flow into the collector). So there will be some current flowing out of the base - which makes its way to ground both through the microcontroller's IO pin and also through the LED on board, making it glow slightly*.

*That is a little crudely put, but kind of illustrates what is going on.

In what way are PNP transistors "harder to work with"? They do things "backwards" compared to a NPN but NPN works "backwards" compared to PNP.

@Rob Everything is the opposite of its opposite. Of course an NPN does the opposite to a PNP if a PNP does the opposite of an NPN.

Thanks for the explanation. So if some amount of current is flowing back through the pin and into the microcontroller, then the controller will get damaged right.? By adding a resistor as you suggested will also allow some amount of current to pass through. Am i correct ? so can a PNP be never connected to a controller's pin(even using a resistor on the base) directly ?

My point is, PNP works differently than an NPN but it is not more difficult. Just different.

Some current is safe. Up to the limit of what the IO pin can handle (40mA absolute maximum, 25mA sustained recommended maximum). The resistor is there to limit that current to a safe level so it doesn't exceed those limits.

@Rob It's not too bad if all your voltages are the same - it's when you start trying to switch higher voltages with a lower voltage signal that you get difficulty - you can't get the base voltage up to the level of the emitter to get it to turn off. You then need extra drive circuitry or other trickery

In no way is that statement true. You can make a PNP switch exactly the same way with no more difficulty, ignoring that the voltages won't be the same. Again, my point is, PNP transistors are different than NPN but no more difficult to work with.

@Rob They are when you don't understand them, is MY point. When you DO understand them, and understand their differences, they are no harder. But since the concepts are backwards compared with the easier to understand NPN it IS HARDER to work with them - UNTIL you DO understand them.  REMEMBER - THIS IS A BEGINNER STRUGGLING TO UNDERSTAND IT.

Which is exactly why you shouldn't confuse him by saying PNP transistors are more difficult to work with. That statement is false.

@Rob Ok, let's argue semantics then. Would you feel more comfortable if I used the phrase "More difficult for the novice to get to grips with" which means exactly the same in the context above.

No cause that's not always true. You should have just said "differently" and that would have worked.

@Rob Well, maybe if you don't like my answer, instead of getting all sarky and pedantic about the most minuscule of things, why not WRITE A BETTER ONE (which incidentally you could have done in the time you wasted here). I like my answer, the OP likes my answer. It's only you around here that seems not to.

I said nothing about your answer. I said your statement about PNP transistors is false and I mention it so others won't be confused by that. Such statements may dissuade new users from using PNP transistors. And that's a bad thing.

@Rob I see you are pretty new to this site. You have to realise that this site isn't like many of the other SE sites. This site is frequented by people who have pretty much no knowledge at all on the subject of electronics. You have to spoon feed them a little bit at a time. In the context of those people the phrase "PNP transistors are harder to work with" is completely correct. If I were on Electronics.SE then it would be incorrect. You have to understand this concept of context and learn a little about the site before you decide what is right and what is wrong.

The fundamentals of electronics do not change based on which forum you are on.

@rob I never said they did. It's the UNDERSTANDING of electronics that changes depending on which forum you are on. There is a concept called Wittgenstein's Ladder - I suggest you read up on it.

guys,.. thanks a lot. for the explanation..  and also for making the fell nothing is difficult

It really doesn't matter if you use a PNP or NPN transistor, they are just mirrors of one another. If you have some common anode displays then just start directly with the PNP's.
The flaw I see in your circuit is that you should always use 2 resistors to drive a LED (See schematic). R2 (as you already have) will limit the current to the LED; 220 Ohm you as illustrated is fine.
R1 is needed between the I/O pin and your transistor. This will limit the current through the I/O pin. For what you are attempting a resistor in the range 1K to 2K should do, even if you're switching a few LED's in parallel.
If you provide complete details of your setup we can always refine the calculations. One can then take into account the total currents from your displays, the amplification factor of the transistor (hfe) etc.


text:
Strange problem. Arduino stops working after few hours. Opinions please
I am trying to setup an automated relay for my aquarium. The Arduino should switch off the pump every 3 hours for 20 minutes, and feed at particular times during the day. The code works fine for the first two on/off cycles. However after that the system stops responding.
I have tried many ways to solve the issue, I am led to believe that the issue could be a memory leak, which I have tried to fix that with watchdog timer reset, I have also tried resetting the Arduino but it doesn't work after the first reset.
I am still not sure what the problem could be, so any information would be appreciated.
I have included the code that I have stitched together using references from the web and a schematic of my circuit along with a picture of a tiny RTC module.
Schematic:

Tiny RTC:

My code is below, any advice would be appreciated.
#include "Wire.h"
 #define DS1307_ADDRESS 0x68
 #define RELAY_PIN 2
 #define Feed_PIN 4
 #define led13 13

 void setup() {
   Wire.begin();
   Serial.begin(9600);
   pinMode(RELAY_PIN, OUTPUT);
   pinMode(Feed_PIN, OUTPUT);
   pinMode(led13, OUTPUT);
 }

 void loop() {
   printDate();
   // digitalWrite(led13, HIGH);
   //delay(500);
   //delay(500);
   //digitalWrite(led13, LOW);
   // byte zero = 0x00;
   ///Wire.write(zero);
 }

 byte bcdToDec(byte val)  {
   // Convert binary coded decimal to normal decimal numbers
   return ( (val / 16 * 10) + (val % 16) );
 }

 void printDate() {
   // Reset the register pointer
   Wire.beginTransmission(DS1307_ADDRESS);
   byte zero = 0x00;
   Wire.write(zero);
   Wire.endTransmission();
   Wire.requestFrom(DS1307_ADDRESS, 7);
   int second = bcdToDec(Wire.read());
   int minute = bcdToDec(Wire.read());
   int hour = bcdToDec(Wire.read() & 0b111111); //24 hour time
   int weekDay = bcdToDec(Wire.read()); //0-6 -> sun-sat
   int monthDay = bcdToDec(Wire.read());
   int month = bcdToDec(Wire.read());
   int year = bcdToDec(Wire.read());
   //print the date EG   3/1/11 23:59:59
   Serial.print(month);
   Serial.print("/");
   Serial.print(monthDay);
   Serial.print("/");
   Serial.print(year);
   Serial.print(" ");
   Serial.print(hour);
   Serial.print(":");
   Serial.print(minute);
   Serial.print(":");
   Serial.println(second);
   if ( (hour ==  9 && (minute >= 00 && minute <= 20)) ||
        (hour == 12 && (minute >= 20 && minute <= 40)) ||
        (hour == 15 && (minute >= 40 && minute <= 59)) ||
        (hour == 18 && (minute >= 00 && minute <= 20)) ||
        (hour == 20 && (minute >= 20 && minute <= 40)) ||
        (hour == 22 && (minute >= 40 && minute <= 59)) ||
        (hour ==  1 && (minute >= 00 && minute <= 20)) ||
        (hour ==  3 && (minute >= 20 && minute <= 40)) ||
        (hour ==  5 && (minute >= 40 && minute <= 59)))
   {
     Serial.print(month);
     Serial.print("/");
     Serial.print(monthDay);
     Serial.print("/");
     Serial.print(year);
     Serial.print(" ");
     Serial.print(hour);
     Serial.print(":");
     Serial.print(minute);
     Serial.print(":");
     Serial.println(second);
     Serial.print(':');
     Serial.print(':');
     Serial.println(", pump off!");

     digitalWrite(RELAY_PIN, HIGH);
   } else {
     digitalWrite(RELAY_PIN, LOW);
   }

   if ((hour ==  2 && minute == 43 && second >= 52) ||
       (hour == 10 && minute == 00 && second >= 52) ||
       (hour == 13 && minute == 00 && second >= 52) ||
       (hour == 16 && minute == 00 && second >= 52))
   {
     digitalWrite(Feed_PIN, HIGH);
     Serial.println("feeding fish.....");
   } else {
     digitalWrite(Feed_PIN, LOW);
   }
 }

Important information: what time does it stop at and what is the last serial print? Add the info to your question rather than the comments.

When do you intend to "digitalWrite(Feed_PIN, LOW);"?

the last serial print is nothing. as the serial monitor stops scrolling too.

im not writing digital LOW because after the minute is over the if condition is not met

the time its stops is approximately after an hour

@user16314: Mikael has given you a very big hint. Think, man. Think.

@user16314: Telling us it stopped after an hour doesn't answer my question in the first comment. "What time does it stop at." Anyway listen to the hint!

ok here's the new code,

Ive not been able to figure the exact time it all fails , cause it fails randomly at different times, however ive implemented the Feed_PIN LOW. il try and note the exact time again. thank you

Cross post of Strange Unknown problem. Arduino stops working after few hours. Opinions please - trying to get help from two places, huh?

How do you know the system has stopped responding? Serial monitor? If you put back your LED pin13 blink does it freeze? I'm asking about exact times because that may point us to your if clauses.

@transistor I would suggest every one looks at the forum post Nick Gammon linked to as it has info the OP has posted related to some serial info.

http://forum.arduino.cc/index.php?topic=369822.0 here's a link to the arduino forum post

MIght avoid reading the RTC while the motor is running.

nice project How did you go? did you manage to fix it?

power input problem, try to solve the problem with power bank. another solution 555 Watchdog Timer

Perhaps you could expand your answer to explain what a 555 Watchdog Timer is, and why you think it would solve the problem in this case?

Your code seems fine, I cannot give a comment yet due to me not being a high enough ranked member, so i will try to phrase this as annswer instead.
Your arduino might be the problem, but I don't think it is likely as the clock is known to be troublesome, but as "transistor" suggested you should let it run on the serial for some time so that you can see if time is reported correctly.
I time is not working then I would like to direct your attention to this thread on the arduino forum, as this is apperently a very poor module. Several people have clocks that doesn't function properbly and there is many post adressing troubleshooting, but since this is supposed to be answer I have taken the top issues and put in below.
https://forum.arduino.cc/index.php?topic=177297.0
primarely they problems come from:
an unrechargeable Cr2032 battery is shipped, instead of a rechargeable li2032, this cause the charging Circuit on the board to act up.
Fix : replace to li2032 or remove charging circuitry - se link
ungrounded crystal - may or may not be a real issue
Fix: ground the crystal
Bad crystal:
Fix: replace crystal
Error in design - Resistor nr. 7 in place
Fix: remove resistor

Here's what the exact timings are :start time
::, pump off!
1/13/16 5:50:49
1/13/16 5:50:49
::, pump off!
1/13/16 5:50:49
1/13/16 5:50:49
::, pump off!
1/13/16 5:50:49
1/13/16 5:50:49
::, pump off!
1/13/16 5:50:50
end time
1/13/16 15:42:55
1/13/16 15:42:55
::, pump off!
1/13/16 15:42:55
1/13/16 15:42:55
::, pump off!
1/1/0 0:0:80
1/1/0 0:0:80
1/1/0 0:0:80
1/1/0 0:0:80
1/1/0 0:0:80
1/1/0 0:0:80                               after it starts spaziing 0:0:80 is the outpu

Perhaps you can try while (Wire.available() != 7); before calling Wire.read() 7 times in succession. Also remove leading zeros in the integer literals of 0 in your IF conditions. And make bcdToDec return an int instead of a byte, in the unlikely case of any overflow issues.

I know a very rough brute force idea, but I'm afraid you won't like it.
Here, how it goes: Use additional relay for powering arduino: While arduino is turned on, let the power be connected to NC contact and after each cycle, just turn this output to HIGH. How it works, you ask? Well, after a cycle, you will with logic 1 (HIGH) state cause to "unplug" the arduino power, which will lead to loosing power supply. However, the relay has a spring, that in case of loosing power, it goes back to NC, in which case, your arduino will be reset and working for another cycle.
That should 100% work, but as I said before: It's a horrible brute force idea :)

I had something same with my  Arduino UNO weather station until I switch to the PSU with lead battery. The most common thing is the power supply.
Try to use more powerful and use the ferrites on the PSU wires.


text:
No Battery Microcontroller Operation - (Motion, heat, induction etc)
I am using an ATtiny85 to sleep for a long period of time, collect some data, send it over radio, and go back to sleep, after disabling everything possible. The ATtiny is currently powered by a coin cell. I can get quite some time off that coin cell, but it's simply not enough, and the coin cell cannot be changed once the board is deployed. Peak current draw is around 10-15 mA.
My aim here is to find an alternative power source for my board. Some good news is that the boards are never more than one or two feet from a receiver, so rf-like power transmission may be possible. Some other options may be motion or heat (it's a wearable device). The amount of power could be pretty small, as I only need it at peak periods, so I could just charge up a supercapacitor for a while and drain it when power is needed after the Attiny wakes up for less than a second.
The ideal situation would be to have a means of power transmission or generation that provides enough current to continuously power the microcontroller without the need for sleep, but I recognize that this is probably not feasible. However, due to the limited range it might be. Another concern is radiation to the wearer.
If anyone has any experience in this kind of power transmission or generation or just any ideas I would love to hear it. Thanks!

I can get quite some time off that coin cell, but it's simply not enough - please specify numbers. You get x days off the coin cell, but you want y days? What are x and y? I have a post about a solar powered Arduino which may be relevant to you. I can elaborate in an answer (rather than just giving a link) if you think it would be useful.

I can get a few weeks depending upon usage, and I need a few months. Unfortunately, solar is out of the question for this project

a few weeks on a single coin cell is quite short. I think you should be able to get a lot more time out of it in software. e.g. disabling all unused modules; combining data, and sending it all at once; not sending data if data hasn't changed; etc. But without any specifics it's hard to say. Have you measured the standby current? How often do you collect/send data per hour? What radio are you using? Do you put the radio to sleep? What code are you using?

As soon as you use a radio, you are looking at wasting power in RF circuits. Most power is wasted in PA in RF circuits. A Li cell like CR2032 can't survive in RF transmission tanks. Some power would always be reflected (and wasted) due to impedance mismatch irrespective of your perfect RF circuit.

10mA is quite a lot for a coin cell. And of course the duration is really low.
As for wireless power transmission, I highly discourage you. Since you are using coin cell batteries I think that size is a must for you, and for wireless power you will need a really big antenna. If it is a wearable I think that the receiver is on the body too, and so much power is not a good thing.
In my opinion and according to my experience you have two possibilities:

use alkaline batteries (e.g. AAA). Use a step up driver to get 3.3V from 1.5V (since the current you need is low you can use simple charge pump regulators, so with a 10pin TSSOP integrate and three small capacitors you are done) and you will get a really long lasting circuit. Drawback: AAA batteries are a bit large, so probably you'll have to make a bigger receiver
use lithium batteries (usually I use LiPo). You will then be able to recharge the battery with any power supply (I usually use an IC which can charge LiPos with a 5V source - USB - and a couple of other components (two capacitors and a LED with its resistor).

Personally I struggled with coin cells for a long time before giving up and sticking with lipos forever.

Unfortunately I can’t charge or access the devices once deployed. I was thinking of using a cr123a as a last resort, because it’s small but still delivers 3v. I might be inclined to agree with you about coin cells - they’re more trouble than they’re worth.

Instead of that I'd still prefer a lipo one.. In the end they have similar capacities and sizes, but once a CR123A expires you have to change it, while when the LiPo does you simply recharge it.. (note: I'm not a LiPo batteries seller XD)

@frarugi87 Do you have any charge pump regulators you recommend (i.e. recommended part nr)?

Well, for my projects I used the MAX1759, which is an adjustable regulated charge pump, and the MAX1595, with fixed voltage (either 3.3V or 5V). The second one is smaller, delivers more current and requires less components, so if you want either 3.3V or 5V the second is better. I usually use these because they are regulated (and very stable), use small components (just three ceramic capacitors the 1595) and, most important, they deliver a reasonable amount of current (100mA the adjustable version, 125mA the fixed voltage one). And.. no, I'm not from Maxim ;)

This question seems to be aligned to your other question about nrf24l01+ transceiver. The charge pump is a good idea, but if this is still for the nrf24l01+ project i would not recommend it because it would cause ripples in the supplied power and RF noise which is really not something you want together with the nrf24l01+.
if the unit is to be strapped on the wrist or ankles a concept like the one in a shake/faraday flashligt might be implemented, but that would be a diy custom job. and probably require size, even though they can fit a similiar contraption into a wristwatch.
But anyway I'm not sure if you are aware, but the nrf24l01+ has a function called enhanced shockburst which is designed for very low current consumption according to the datasheet it only requires 1% or 0.12ma at normal transmitting mode! this comes at the cost of transmitting power ofcourse but your receiver is only a few feet away so that is most likely not an issue.
https://www.sparkfun.com/datasheets/Components/SMD/nRF24L01Pluss_Preliminary_Product_Specification_v1_0.pdf page 14
I'm pretty sure you already have optimised your current consumption, but one setting you might have missed is  the atTiny clockspeed which can be lowered to 1mHz instead of 8mHz this will lower the current to run the processor to 20 of the normal.
if these are not implemented already, then they might give you the needed battery life.

Thanks for the info on shockburst, I’ll look into that. The Attiny is already running at 1MHz. I didn’t know that it could transmit with such low power...

I have not had an opportunity it test it, so I don't if they are overselling it so to speak - but I'm waiting for my nrf24l01+ and will most definitely test it when I get my hands on them

I just helped a friend install a Fitbit "Zip" model. In the process of doing that I noticed it is powered by a CR2025 (3V lithium button) battery.
Their ads claim it runs "up to 6 months" on this battery. It communicates wirelessly (ie. Bluetooth) as well as having an LCD screen. It also takes measurements.
Thus, what you are trying to achieve sounds technically possible, as someone has done it.

I can get a few weeks depending upon usage, and I need a few months.

So to solve your problem it would help to know what your existing current consumption is.
I have a project about an ATtiny85 torch locator. That does not do radio transmission but does flash an LED. I calculate the battery should last 3 years, and at this stage (almost a year after I made it) it is still working on the same battery.
You may get some ideas from that link.
I calculated (and confirmed by measurement) that in idle mode it uses 4.4 µA. You should be getting a similar figure during your sleep periods.

I gotta say, that's pretty amazing that it can run for so long on such a small battery with all those radios and displays working. I've got the power up and power down much more efficient - now the peak current draw is less than 5mA or so (my DMM's fuse is blown so I can't read it accurately). The main purpose of this question was to see if there was a better option than battery power, but the general consensus seems to be that most things will require quite a bit of experimentation and to work. Thanks for your help.


text:
One time execution of a variable incrementation
As part of a larger script intended for a very simple arduino "synthesizer" I am trying to increment the amount of cycles a melody will be played once a key is pressed (the key in turn passes a value to the variable selectMel). The problem I encounter is that the moment I call my function in the main void loop() function, I cannot control the incrementation of the variable ncycles, which is intended to be only increased once per key press. I tried to solve this by creating a global switchVar variable as an "on/off" switch but that did not do much to solve the issue at hand.
Any tips or help will be greatly appreciated!
PS: I have of course googled and tried the solutions posted on similar stackExchange posts but to no avail, sadly.
      void playMan (int ncycles, int mSpeed) {

        switch (selectMel) {
        case 1:
          if (ncycles > 0) {
            tone(12, NOTE_B7, mSpeed);
            delay(100);
            tone(12, NOTE_B5, mSpeed);
            delay(100);
            tone(12, NOTE_B3, mSpeed);
            delay(100);
            tone(12, NOTE_B1, mSpeed);
            delay(100);
            ncycles--;
            break;
          case 2:
            if (millis() % 100 == 0) {
              if (switchVar == 1) {
                ncycles += 5;
                switchVar = 0;
              }
              Serial << ncycles << endl;
            }
            break;
          default:
            break;
          }
        }
      }

See http://www.gammon.com.au/switches.
Basically you need to detect the transition between the switch not being pressed before, and now being pressed. This transition will occur once per press (possibly after you add debouncing). If you just test for the switch pressed naturally you will get multiple increments.

Assuming I add debouncing, how would it help in incrementing the value of ncycles only once ?

To clarify, you increment once on a transition, note when you did this (eg, by calling millis() ) and then ignore any further transitions for, say 10 ms.

Assuming I add debouncing, how would it help in incrementing the value of ncycles only once ? From what I understand debouncing is only helpful as a means of toggling from one state to another without the "noise" of outside factors, or is there something I am missing entirely?

I have just found a solution to my own question, albeit not without your kind help Mr. Gammon, thank you!


text:
Using an Arduino as the processor for a computer-mouse-like speed detector
I'm looking at making a pretty cheap and easy odometer, eventually for an electric car or similar vehicle.
My idea is to implement a big computer mouse, and track the speed with that: a computer mouse takes photos of the surface it is on, and finds the difference between sequential images in both the X and Y directions.
What I am wanting to do is to attach a downwards-facing camera; something like this, to the bottom of the vehicle, and use an Arduino Nano to do the image processing to achieve a result similar to a computer mouse.
I was wondering whether anyone knows of an libraries/documentation on anything similar, or if anyone has any pointers on reasons why this would not work, or ways it would work.
Thanks all.

Neat idea! One potential problem that occurs to me is the lens getting dirty. You might also need a light for it to work at night.

Mouse chips are ASICs specifically designed for image processing. Use an encoder instead.

Like @jogco pointed out, you will have very little computational power. With that camera you will have to use a clock at 24MHz to read the data; this means at least a 100MHz uC. So forget the arduinos... Maybe you will manage to do that with higher power uC (for instance ST nucleo boards), but then you'll have to face another problem: resolution. An electric car moving at 7.2 km/h (human speed) travels 2m in 1s. The frame rate is at most 30fps, which means that the car moves 7cm every frame. This means that the camera should be at least at 10cm from the ground to be able to see some common

points between two frames. Since, however, it'll be very difficult to compare them, I think that at most you should allow for half an image of difference. This means that the camera should be at least at 20-25cm from the ground. And if the car is faster than humans, well, just give up. The easiest solution is to use an encoder on a shaft (for instance on the wheels one). I suggest an optical encoder because they are easier to assemble, but dirt can lower their performances, If dirt can be an issue use a magnetic one (or just magnet + reed relay)

@frarugi87 Thanks for that analysis, it definitely puts it in perspective! I can't rationally explain why, but I am trying to avoid shaft encoding. I am wondering about a small array of photoresistors, and simply multiplex them, so I can have a significantly faster read time, and just look for patterns.

@dlu thanks for your input, I hadn't really thought about either of those!

Whooa, wait a minute. This sounds way too complicated, and my guess is that a Nano would be seriously underpowered.
If you really want to do all that work, you probably would need to step up your processing power. I suggest that you do some calculations on that, the number of pixels per second that should be compared.
Also factor in the time it takes to capture the image, the device you suggested is probably not fast enough. My guess is that by the time you can take next picture of the surface, you don't have any part of the image to compare with. According to wikipedia, a modern mouse has a 18 by 18 pixel sensor, and we're not talking a lot of (surface) speed here.
But there's a simpler solution; mount a magnet to one of the wheels (or axle) and a reed switch so that it is actuated as the magnet sweeps by. Then use the Nano (or a Trinket, no need for power here) to count the pulses from the reed switch. Do your math; (circumference of wheel) * (pulses per time unit). Convert to suitable format.
Voila; speed! :-)
This method was used to get accurate speed for deadreckoning, before GPS was really usable on land.. OMG, I'm old.
Possible problems areas - dirt, debouncing the switch, timing of arduino. But these sound simple in comparison.

I totally agreed with this until you wrote that "need RTC" sentence.. An RTC? Why? RTCs are good at keeping time when the device is off, not to measure small time gaps (usually they have a 1s granularity). Crystals' precision is really enough for this project. What really lacks is the computational power to analyse the image in few milliseconds

Sure, then we can straighten out that question mark, and move it: !(need RTC). I was just throwing up possible areas to investigate.

Thanks Jogco, I wasn't totally sure about feasibility. I guess for speed accuracy there is some relationship with the field of view and the speed at which each image is processed. I have been looking for a significantly lower resolution camera, but am unable to find it. I wonder if I would be able to use a small (~10x10?) array of photoresistors and multiplex through them. This would need some form of light source to go with it, too.


text:
Connect Bluetooth remote control with Arduino
For a project I need to connect a Bluetooth Remote control with an Arduino Nano.
On the Arduino-side I have an HC-05-Bluetooth module. With the Android Application "Bluetooth Terminal" I can verify that the connection is ok, because I can send and receive Strings with an Android smartphone.
In the minimal example I send values from a sensor which is connected to my Arduino via bluetooth to the smartphone, which is working nice. So I guess the wiring is correct:
void loop() {
  sensorValue = analogRead( sensorPin );
  cm = 10650.08 * pow( sensorValue, -0.935 ) - 10;
  Serial.println( cm );
  softSerial.println(cm);
  delay( 500 );
}

Instead of sending sensor values, I need to connect said remote with the Arduino.

(Picture shows the basic model of said remote control.)
The remote control has the Bluetooth class 20258C which means:

Major Device Class: Peripheral
Limited Discoverable Mode
Audio
Pointing device
Remote control

Remote Control Bluetooth  Specifications:

BT Device Name: YL-BTM3-xxxxxx
Supplier ID and Product ID: 0x0A5C / 0x4503
Class of Device: 0x20258C

My Question is: How can I pair those two devices? I can get the remote control into "Pairing mode", by pressing 2 Buttons. But how do I pair the Arduino-Bluetooth-module with this remote-control? Is it possible at all?
Best regards

This should be a comment, but..
For starters, you'll need to do the pairing from the Arduino with the HC-05 in master mode.
Check this out.

Thank you for the response. I already put it into Master mode and I also found some tutorials like the one you linked. But unfortunately my case is a little different: I do not know the mac-address of the remote control. (In the link the address is known and used to establish a connection). I just have no clue how to connect a Bluetooth device with "Limited Discoverable Mode" like this remote.

You'll have to scan for the "mac" address, that's described on the page I linked to. It is also possible that it is printed in the battery compartment of the remote, or as a last chance, on the pcb/bluetooth module. "Limited" just means that it is discoverable for 30 seconds.

Ah Ok. Thank you! I will try this and report

And if you pair using a PC, you should be able to see the "mac", or device address in the Control panel if you are using Windows or About this Mac on OS X, or "hcitool scan" on Linux

Thank you. I now understand the process and this answers my question. Unfortunately I have a follow-up question, which I have posted here: http://arduino.stackexchange.com/questions/19517/hc-05-bluetooth-module-inq-command-doesnt-work