text:
Change Servo Speed With RedBearLabs BLE Shield
I recently got the RedBearLabs BLE shield to use it to control two high spped continuous rotation servos. I have the BLE example sketch loaded and the ios controller app works. The problem is that the servos are too fast to control and I want to slow them down. I cannot use the app to slow them down. I was wondering how I could modify the example sketch or servo library to change the ax speed or something. Thanks in advance.
BLE Shield Homepage: http://redbearlab.com/bleshield/
BLE Libraries and Example Sketch: https://github.com/RedBearLab/nRF8001

Can you be more explicit in what you want to achieve.  What do you mean by "the servos are too fast to control" - do you mean the servos are repositioning too quickly?  Something else?  Also can you please post (or link to) the exact code you need help with - not a whole library of stuff.

The servos spin too fast to be able to control it very well. I want to slow those down.
https://codebender.cc/sketch:245943
This is the code

SnapDraggen, please edit the question to answer the items in Kingsley's comment.  Note, there are seven different examples at the github link, four of them having BLE in their names, so you should say which one you mean.  Also add a direct link to whatever iOS app you used.

This is the app: https://itunes.apple.com/us/app/ble-controller/id855062200?mt=8
The sketch is the one called BLEControllerSketch
I am using it to build a robot

I am building a robot with two servos as motors. I want to use the BLE Controller app(linked above) to drive it. I have already done this but it is very fast and hard to control. I want to somehow slow down how fast the servos spin. They are parallax high speed continuous rotation servos.

@SnapDraggen - please edit your question and copy the information in your comments into it. The question will then be more complete. Please read How do I ask a good question?

The bi-directional Parallax High Speed Continuous Rotation Servo responds to “simple pulse-width modulation”, according to its web page.  That is, pulse widths in the range from about 500 μs to 2500 μs will set the speed and direction, with some value near 1500 μs corresponding to zero RPM.
The code in the BLEControllerSketch uses the following bits of code, among others, to initialize servo-control data structures and to control them:
#include <Servo.h>
...
byte pin_servo[TOTAL_PINS];
Servo servos[MAX_SERVOS];
...
      case 'O': // set Servo
        {
          byte pin = ble_read();
          byte value = ble_read();

          if (IS_PIN_SERVO(pin))
            servos[PIN_TO_SERVO(pin)].write(value);
          pin_servo[pin] = value;
          reportPinServoData(pin);
        }
        break;

Thus, you will need to send an O message from your iOS app, together with servo pin number and control value, to set a servo's speed.
As noted on the ServoWrite page at arduino.cc, the parameter to Servo's .write() method is a number:

On a standard servo, this will set the angle of the shaft (in degrees), moving the shaft to that orientation. On a continuous rotation servo, this will set the speed of the servo (with 0 being full-speed in one direction, 180 being full speed in the other, and a value near 90 being no movement).

You can find out a little more by looking at Servo's .write() method in Servo.cpp:
void Servo::write(int value)
{
  if(value < MIN_PULSE_WIDTH)
  {  // treat values less than 544 as angles in degrees (valid values in microseconds are handled as microseconds)
    if(value < 0) value = 0;
    if(value > 180) value = 180;
    value = map(value, 0, 180, SERVO_MIN(),  SERVO_MAX());
  }
  this->writeMicroseconds(value);
}

SERVO_MIN() and SERVO_MAX() are macros that access min and max fields in a Servo object and convert them to microsecond values.  Because the code in BLEControllerSketch.ino lets those fields default, the range evidently will be from 544 to 2400 μs (see the values given in Servo.h).
Note that you can get better resolution – hence, better speed control – by sending values in that range of microseconds to your servos, instead of trying to control it using values in degrees.  The .write() method will interpret such numbers as microseconds instead of as degrees.  Servo.cpp appears to use half-microsecond timer ticks; and each degree corresponds to about 10 μs of pulse width; so resolution using microsecond values should be about 10 times better than using degrees.
In short, it appears that you should do some experimenting with O messages that send values around 1500, to find the values that correspond to slowest forward and backward speeds.


text:
Taking off the chip from Arduino
I just uploaded a sketch of a song to my Arduino and it works well.  Could I just take the chip out and hook up speakers to it and a power source to play the song? and just get another chip and put it in the Arduino.

There are lots of resources on this subject on the internet.
It is possible, but requires some engineering.
Try searching: "Breadboard arduino" or "barebones arduino".
https://www.arduino.cc/en/Main/Standalone
You'll need:
5V power supply, or circuitry to provide so.
20Mhz clock or use the internal 8Mhz clock.
Something to program it with, an USB<->uart converter or ICSP programmer. (Or just put a programmed chip in)
And optionally a reset button,

@FuaZe arduinos use 16MHz, not 20mHz.

@Gerben ah, ofcourse, no idea why I thought of 20Mhz. Thanks for pointing that out!

Yes and no.
To elaborate, the sketch you downloaded to the chip has been flashed to internal non-volatile memory. So if you were to move it to another Arduino board or other device with the appropriate support hardware, then it should work just fine.
However, if you're intending to directly hook-up speakers to it and a power source, then I highly doubt it's going to work. You really need some support hardware for the chip (such as an external clock - though I think the Atmega328 has an internal clock, decoupling capacitors, amplifiers for the spearkers, etc.).

More specifically, the ATmega328p in a typical full-size Arduino is typically fused to rely on an external clock.  While being provided with such a clock it can be re-programmed for internal clock operation, as those used on some of the various smaller boards typically are.

Easy part first: You CAN put another chip on arduino PROVIDED that chip already has a bootloader on it. If it's a raw chip, burn the bootloader on it first. This guide will help.
You CAN connect the programmed chip to speaker PROVIDED you add the minimal circuit components required for an arduino to run. These include - a 16 MHz crystal, two 22 pf capacitors and a 10K resistor. Use the schematic in the bootloader guide. That will work.
Besides this, you will require a 5V power source. You can alternatively use 3xAA cells (4.5V will work perfectly). Alternatively use a wall adapter of 7V or higher and use a linear regulator (7805) to generate a perfect 5V supply for your arduino. You will need this pin mapping diagram to connect the speaker to arduino once you take it out from the board:

source: Stack Exchange

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

sort: votes


text:
Arduino Uno and Raspberry Pi USB Serial Communication
I am trying to get Arduino Uno with Raspberry Pi to communicate with each other. I want the python script to write a message and for my Arduino to read it. This was working before, but I came back a week later and it stopped. Essentially, I want the Raspberry Pi to write '3' and for my Arduino to recognize this 3 and light up some LEDs. Where do you think I am going wrong? The Arduino works when testing it through the IDE and Serial Monitor. There are no errors when running the python script, the LEDS just don't light up, so I assume there is some miscommunication.
Python Code
import serial
ser = serial.Serial('/dev/ttyACM0', 9600)
ser.write('3')

Arduino Code
String serialRead;
int val;
void setup() {
  Serial.begin(9600);
  strip.begin();
  strip.setBrightness(25);
  strip.show(); // Initialize all pixels to 'off'
}

void loop() {
  serialRead = Serial.read();
  if (Serial.available() > 0) {
    val = Serial.read();

    if (val > '0' && val <= '9') {
      Serial.println(val);
      val = val - '0';
      Serial.println(val);

      if (val == 3)
      {
        //strip.setBrightness(100);
        colorWipe(strip.Color(127, 127, 127), 50);
        colorWipe(strip.Color(0, 0, 0), 50);
      }
    }
  }
}

What you can do is remove the rPi from the equation. Run the sketch and send your own serial commands direct via your computer and see if the LEDs change as expected. That will narrow down which end is having the problem: works, it's the rPi send/arduino rcv. doesn't work, it simply your code or the LED setup. Report back and tell us how you go

Just at a glance:
Your loop consumes the byte and stores it in serialRead, so there is probably no available data at the outer if, so it is never entered.
Try deleting this line:
serialRead = Serial.read();

Unfortunately, that did not work. I am able to get it to work through the Arduino IDE using Serial Monitor both ways, but still not with the RPi

I suspect a timing issue; perhaps the rPi sends the '3' before the Arduino is listening?  Have you tried to put a loop w/delay in the Python code?

The first Serial.read(); is a problem for sure – unless the Raspberry Pi sends more than one '3' this line could consume it, and then nothing will happen. I'm suspicious that there are garbage characters that are consumed by that first Serial.read(); when you're testing with Serial Monitor. Why don't you print what your get from it. Also is the pi sending a newline? Could the problem be that there is Serial.read() expects one?

I took out the first Serial.read(); and the problem persisted. I think NVRAM may be right with the timing issue. I was able to get it to work with constantly writing a 3. Unfortunately, I had to give the setup back to my friend so I won't be able to test this issue further. Thanks for the help.

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


text:
Blink question with breadboard & LED
I tried a basic Blink example and I found a strange case where :
Works

Does not work

Can someone explain me what is happening ?

It is because the rail in the middle breaks the vertical connections.
So the positive leg in the first example is not connected to the negative leg of the LED.
In your second example both the negative leg and the positive leg are connected on the same rail, because of the that the power is not flowing through the LED but directly back to the GND pin of your arduino.
Same for the resistor. Since both legs are connected to the same rail, the resistor has no effect.

Also note that in both cases the resistor will not work. This will damage the led, and possibly the arduino.


text:
Rotating a motor with L293D
I'm following this tutorial to control a DC motor with an Arduino.
I have the same problem as this stackexchange post arduino.stackexchange.com/questions/10049/problems-with-l293d where the motor is not rotating.

The chip is heading to the right. (5v pins are on the right)
Connecting directly the motor to the battery works.
Current (5V on the bottom & 2*1.5V) is flowing everywhere expected EXCEPT on the yellow & green wires of the motor (the red wire of the battery pack is connected to the second line of the breadboard).
Connecting directly the motor to the battery works.
I copied the code of the above tutorial which is basically : "digitalWrite(4,HIGH);", there is current on the cable.

Am I wrong into thinking that a L293D chip can output sufficient current ? Is the chip malfunctioning ?

Your picture shows a holder for two AA cells, yielding something in the neighbourhood of 3v.  That is far too little for an L293D.  (This isn't really your fault, as it appears you got this erroneous idea from following a bad tutorial, but it does demonstrate that not everything you read on the Internet is sensible.  Using a 9v "transistor" battery is also a bad idea).    3 cells would be about the minimum, but even there it would not work well, as that chip has two bipolar transistors in the path yielding a voltage drop of over a volt.
To use a an L293D you really want at least a 5 or 6 volt system, and a motor wound for low to moderate current at that voltage.
If you want to use a lower voltage, look at a more modern MOS-based H bridge chip - the TB6612FNG is an often used example.  You will however still want to choose motors wound for moderate current at a 3- or 4- cell voltage - those intended for 2-cell usage typically draw more current than is ideal for an IC driver chip.
It is entirely possible that there are additional issues with your attempt as well.  Normally, a question such as this would require a complete and accurate schematic diagram, which you have not provided.

I think you're right even though i've seen demonstration videos using 2 AA batteries and 2 DC motors working fine.
The goal of my project is to use a smaller DC motor than this and a small 3.7v rechargeable battery. So switching to a smarter motor contoler might be a better idea. I'll try the reference you gave me, thanks !

So I used a 4x1.5v battery pack. The L293D chip was faulty, I changed it. Still, the motor is running way slower than directly connected to the batteries. The TB6612FNG chip is not to be used for a small DC motor like this, it is meant for bigger scale projects.

Whoever told you the TB6612FNG is only for larger projects has no idea what they are talking about.  The L293D has a large voltage drop - effectively one of the cells in your battery is only to offset that loss, and part of a second too -  which is why you should not be using it.  In contrast the TB6612FNG and similar MOSFET bridges are much more efficient - a far greater fraction of your battery voltage actually shows up across the motor, and less is wasted as heat.

I ordered the TB6612FNG chip and will soon experiment on it. Thank you for your clear explanations and the reference of the chip.

Make sure you get or have plans to make a carrier PCB - the pins are about twice the density of your breadboard, so it won't be fun to hand-wire to.  It wouldn't make a bad introduction to toner-transfer PCB fabrication though, and it shouldn't be too hard to hand solder to a PCB as long as you approach it carefully: solder one corner, check alignment, solder the opposite, check alignment, and only then solder everything else.  Ultimately it is surface tension and flux which get the solder in the right place.  Have some of the finest size solder braid on hand to fix any accidental bridges.


text:
Set an arduino software clock
Me and my friend are having some trouble setting up an software clock to our arduino uno.
It's for a school project and we´ve never done any programming before. thanks!

We try to. Just having some trouble setting the time for our project. We´re stuck and could really use some help.

Thanks! But we're having trouble with the compilation. It says that there´s no such file or directory #include <Time.h>. Do you know what to do?

Please post any code that you have done so far. Is the project just a software clock or is there more? What is the project goal?


text:
Simple compiler design help: Variable length arrays?
I'm trying to write a simple compiler in C++ for a language that I am making up for my lab.  The compiler will have to be able to turn a string like this:
"do command_one 3 times"

into a data structure that represents this:
<command_one>, <command_one>, <command_one>

it should also be able to turn something more complicated like this:
"do do c_one do c_two 2 times 2 times c_thr 2 times"

into a data structure that represents this:
<c_one> <c_two> <c_two> <c_one> <c_two> <c_two> <c_thr> <c_one>
                <c_two> <c_two> <c_one> <c_two> <c_two> <c_thr>

Another function will then read the commands out one by one.
These examples show all of the functionality that I would want from the compiler.
I'm having design issues for the compiler that I want to create.  Initially, I just wanted to do some string manipulation and turn the input string into an array of integers representing commands.  However, since the compiler will be outputting an arbitrarily large number of commands, and since arrays in C++ need to be initialized with a length, this could be a problem.
I am not fluent in C++ so I am hoping that a C++ whiz can show me a quick solution.  I have already come up with the suggested solution on my own in Python, however, my solution in Python has to do with the ability to change the length of lists on the fly.
EDIT: I am also intending to use this code for an Arduino, which supports C++ code but not the standard libraries.  I found the vector solution to work in my C++ code, but it will not work in the Arduino interface.  Is there a way to do the compiling WITHOUT using vectors?

It is, both were asking different questions originally (answers for C++ and answers in Arduino) but as I got an answer in C++ the mods moved the C++ question to the Arduino forums

To clarify, I did need answers for both C++ and Arduino since I needed the compiler on both systems.

In C++ there is a std library container called vector you can use to create variable length arrays. You can use it like this:
#include <vector>
// ...
std::vector<int> commands;
// ...
// parse string and generate commands, add your commands with push_back
commands.push_back(new_command);
// and you can access elements in the array like normal
commands[0];
// and also see how many elements are in the array
commands.size();

I also want to mention the std stack, which I think would be a helpful class for managing the states of your nested loops. Each time your interpreter enters a new loop for example, push to the top of the stack how many times to run, and each iteration count down till 0 and pop (just as an example).
Edit:
Because you can't use vectors C++ also supplies the new and delete keywords to dynamically allocate and delete memory. However as arduino has really low memory I don't recommend trying to implement an expansible array on this.
This post here mentions that program memory and global memory is shared on 2K: new operator on arduino
You may just want to go with a reasonably sized static array on arduino considering the memory limitations. I would suggest using a pool or the new + delete stuff but any implementation you add to deal with memory management will take away space you need for your interpreter and its instructions.
Also I don't know what data type you've chosen to represent your instructions but char is probably best  on the embedded implementation if your instruction set is small as it only occupies one byte each.

My instructions can simply be represented by numbers.  Ex: 1 can mean cmd_one and 2 can mean cmd_two, etc...


text:
How to convert macros for Arduino code?
I have a piece of code I'd like to make Arduino editor friendly. The code is written in C and contains macros the Arduino IDE can't deal with. Is it a good idea to turn those macros into functions?
#define AN221_EXECUTE_Low   cbi(PORTA, PIN0)        //drive EXECUTE low
#define AN221_PORb_High     sbi(PORTA, PIN1)        //drive PORb high
#define AN221_ACTIVATE      bit_is_set(PINA, PIN2)      //sense ACTIVATE high
#define AN221_NO_ERROR      bit_is_set(PINA, PIN3)      //sense ERRb high i.e. no rror
#define AN221_ERRb_Input    outp(0xEB, DDRA)        //make uP drive ERRb
#define AN221_ERRb_Output   outp(0xE3, DDRA)        //make uP sense ERRb

Compiled ok for me - what were you expecting and what actually happened?

Is it a good idea to turn those macros into functions?

it depends.
macros are fast, but lack type checking.
functions offer type checking but incur overhead.
whether one is better than the other depends on your priorities.


text:
How to connect HC-05 to an arduino Galileo?
I connected a logic analyzer on digital pins 0 and 1 (Rx and Tx). Using Serial. functions on Galileo and the integrated terminal on Arduino IDE, I noticed this UART port was not used when chars were received and transmitted, what is sustained by the blocks diagram of Galileo here.
So, if UART1 is used on PC communications, I would like to use UART0 to other things, like a bluetooth adapter. Any tips?

This might answer your questions about the Serial mapping on Galileo. Seems like you should use Serial1 for UART0 and Serial2 for UART1.
Cheers!


text:
Why my Galileo isn't getting a IP address?
I have an Ethernet cable connected to my router. I connected the other end to my laptop and got a successful connection. When I plug it into my Arduino Galileo gen2, even with Ethernet port green light on, I got nothing when I run this:
delay(1000);
system("ifconfig eth0 > /dev/ttyGS0");

This is my output:
eth0      Link encap:Ethernet  HWaddr 00:00:00:00:00:00
      BROADCAST MULTICAST  MTU:1500  Metric:1
      RX packets:0 errors:0 dropped:0 overruns:0 frame:0
      TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
      collisions:0 txqueuelen:1000
      RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)
      Interrupt:41 Base address:0x8000

What I'm doing wrong?

You have no MAC address (HWaddr).  This usually means you have a driver problem.  That might be why you aren't getting an address.

This might point you in the right direction; https://communities.intel.com/thread/45455

I really don't know why, but after I initialized the Ethernet interfaceifconfig eth0 up it started working properly. I don't know why this time this command was needed and the others didn't.


text:
Why SD.exists() only looks for inside media/realroot on Intel's Galileo?
I'm following a tutorial which says SD.exists() only look for files inside media/realroot on Intel's Galileo board. I just confirmed this using SSH to create e remove files during a loop which was looking for some specific named file. Where's information about this? I searched for cpp files inside SD library and found nothing.

The Intel Galileo runs Linux.  Most Linux distributions (auto) mounts media under specific directories like "/media".  So this is likely not so much a feature of the Arduino paradigm but of the Linux paradigm.  If you really want to change this you will probably have to research how Linux (specifically how the Intel Galileo version of Linux) auto mounts media.
This is a stack exchange question about auto-mounting using a Linux distribution called Ubuntu.  I am not sure how close the Intel Galileo Linux is to Ubuntu.  But it's a starting point.


text:
What happens when there's no space left on SD card?
I'm coding a data logger and I would like to know what happens if there are no bytes remaining to be written using SD library, ie, if the SD card is full of data. The logging would just stop or I would get some nasty error?

Unless you list your code no one can say.

Open-source is just great. Lets have a look at the source code for SD. Here is what happens on write of a block.
/**
 * Write data to an open file.
 *
 * \note Data is moved to the cache but may not be written to the
 * storage device until sync() is called.
 *
 * \param[in] buf Pointer to the location of the data to be written.
 *
 * \param[in] nbyte Number of bytes to write.
 *
 * \return For success write() returns the number of bytes written, always
 * \a nbyte.  If an error occurs, write() returns -1.  Possible errors
 * include write() is called before a file has been opened, write is called
 * for a read-only file, device is full, a corrupt file system or an I/O error.
 *
 */

The source code shows that blocks are allocated from the free list and if there are no more blocks the function will return an error.

There doesn't seem to be any definite answer in the library documentation, but I am fairly certain that writes will simply fail, and not cause any sort of corruption. The last log entry may be incomplete, but the file should still be readable.

Any of us can speculate in that manner about what might happen, and come up with an answer like that that's hardly worthwhile.  I suggest that if you don't know the answer and don't have evidence one way or another, then don't put what you have to say in an "Answer" but instead in a comment, if at all.   ¶ To answer a question like this, either examine the library code itself (rather than its documentation) or run an experiment (eg, declare a big file, seek to near its end, write some bytes, repeat until fail, ie until write() < bytecount)


text:
Can I receive data on the Arduino by sending data to /dev/ttyACM0?
I'm working on a Raspberry Pi connected to an Arduino.
When I execute
echo 'Hello' > /dev/ttyACM0

, the Arduino receives the data, as indicated by its LED. How can I read the data on the Arduino and process it?

start with a simple google search "arduino serial data read" or any similar combination, you will find a myriad of written tutorials and videos. If you've followed such tutorials, edit your question and show us which one (with a link), post your code and tell us a little more about what you've done and what's exactly not working. Then you might get a real answer to this question, although if you do that (above) you will arrive at the answer all on your own, I'm sure of it

Use Serial.read() there are plenty of examples that come with the Arduino IDE, just make sure the baud rates on the Raspberry Pi and Arduino match.


text:
Atmel studio 7 with Arduino Uno: Just upgraded to Atmel studio 7 and my target platform is the Arduino Uno
Atmel studio 7 with Arduino Uno:
Just upgraded to Atmel studio 7 and my target platform is the Arduino Uno.
I can't get past the start procedure: Firstly on starting up I get Sequence contains no elements (first image below). Then after pressing enter and entering the the Sketch File and Arduino IDE Path fields, the Board and Device fields remain empty (second image below).
I'm unable to select or update any of these two fields (Board and Device) - any assistance is appreciated.

I also had random problems trying to import Arduino sketches using the new Atmel Studio feature. I eventually gave up. It might just not be ready for prime time yet.

Do you run the Configuration Manager, upon the first launch? It should run automatically, in fact. I installed AS7 yesterday, using the web installer, and it automatically selected Arduino IDE 1.6.5, and the boards were also selected automatically. Do you actually have the Arduino IDE installed? I assume so, from looking at your screen shot. Try upgrading the IDE and running the Configuration Manager again.

Do you have Visual Micro installed?


text:
Arduino nano standalone - pcb to be manufactured
Using EasyEDA I've designed a standalone Arduino nano and plan to have a small PCB manufactured by jlcpcb. I've used the Nano's user manual as a reference for the PCB; within this scope I've used the same microcontroller (ATMEGA168-20AU) and kept close to the original design.
The circuit is modestly basic and will use a blank target ATMEGA168 placed by jlcpcb - my question is - From a programmer Arduino, do I flash the bootloader and program the target micro through the ICSP (left hand side) or is something else required for bootloader plus program? Is the circuit schematic sufficient to work? (could be opening a can of worms here in asking that)
Thanks

I do not see any high frequency bypass capacitors.

Add the capacitors suggested in the answer (you can look to the manual for reference), and as good practice, add a pin header with several extra pins on it. This has saved my butt countless times. They won't take up much space at all and you never know when they might come in handy, even just for testing.

You program the chip through ICSP, yes.  Whether or not you include a bootloader is optional - you don't need a bootloader to program through ICSP, that is only for if you want to program through the UART pins and a USB to UART adapter.
Your circuit doesn't appear to include any "bypass" capacitors. These are small capacitors (usually 100nF) placed close to each power (VCC) pin on all chips. These are not optional and are required for the proper running of the chip.

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


text:
Can I use my phone's charger to connect arduino M0 pro R3 with computer?
I found out that the arduino M0 pro R3 needs either micro HDMI or micro USB.
Since I don't have any micro USB or HDMI adapters, can I use the Samsung galaxy USB/micro adapter to connect?

If the Samsung cable has a micro-usb on one end, and a usb-a on the other side, then I don't see why not.

@Gerben I actually tried it, and I did get a successful upload. But the power is 5 volts, and 1.5 amps. Will that be enough? And just to add, can I use a 3 amp, 12 volt Ac/DC adaptor? Or will it fry my arduino?

You just want to power it, not connect it to a PC? A regular USB port only supplies upto 500mA, so 1.5A is plenty.

@Gerben And will my arduino be fried if I use a 12 volt, 3 amp AC/DC adaptor as an external power supply?

What board are you using? The R3 doesn't make sense for the M0, and in the tag you refer to a pro-mini.

@Gerben My arduino has text saying the board is an M0 R3. It is the arduino.org brand. Should I tag this question as arduino-zero?

The allowed input voltage range for this pin is 6-20 V. source. So your 12v adapter is also fine.

@Gerben You can put all the details discussed in an answer for me to accept. And finally to add: Do the amps matter? What is the maximum amount that can be handled as an external source?

Echoing what Gerben said, in order to wrap up this question:

If the Samsung cable has a micro-usb on one end, and a usb-a on the other side, then I don't see why not.
You just want to power it, not connect it to a PC? A regular USB port only supplies upto 500mA, so 1.5A is plenty.
The allowed input voltage range for this pin is 6-20 V. source. So your 12v adapter is also fine.

I actually tried a month ago. Worked. Thanks ;)

Excellent. This question now has an acknowledged good answer. That's what we like!

It should be noted that "this pin" (6-20V) is the VIN pin. And not the USB port. To avoid mixing those up. Also, you won't fry a board because your supply can supply more current, the Arduino will simply use the current it needs. If your Arduino pulls more current (by attaching a motor directly) than it can handle, you might indeed harm it, or the power supply.
And, yes, acknowledging the answers pumps up the stats a little ;)


text:
Use Unix terminal instead of the Monitor on Arduino IDE
I want to make a shell or C script that interprets the Arduino serial input to run commands. For that, I will need to make that script be the Serial monitor for my arduino. Another reason I want to use scripts or the command line as a Serial I/O is because the Arduino monitor function freezes the IDE.
My arduino's serial port is /dev/tty.usbmodem1d112
This is what I have tried so far:

cat /dev/tty.usbmodem1d112 < This returns absolutely nothing
screen /dev/tty.usbmodem1d112 < This Prints output, but has problems with input.
cat < /dev/tty.usbmodem1d112 < Same result as cat without the < symbol.

Sometimes, I also get annoying Resource Busy messages. This makes me re-plug the Arduino board.

OS X (10.9.5) Arduino IDE latest version. Arduino M0 pro board.

On linux, I usually have to configure the device with stty to raw mode or whatever I want first, but I'm not sure how portable that is.

screen /dev/SomeUSBSerial SerialSpeed works fine here on Debian with CP2102, FTDI232, Atmega32u4 (Leonardo), Atmega8U2 (serial chip of UNO-R2)... input and output are ok.

For what it is worth, the 1st and 3rd versions of your command are identical in function. In the 1st, cat uses the argument as the file to display. In the 2nd, the shell sets the standard input for cat to the file. The net result of both is that cat reads from the file and writes to standard output. The < and > operators are used to redirect the input and output of a program.

Have you tried miniterm.py? It works really well in Ubuntu as serial monitor with Arduino boards.

Yes, miniterm really works very well on Ubuntu and faster than screen, minicom, cu, etc. https://helpmanual.io/help/miniterm.py/

https://playground.arduino.cc/Interfacing/LinuxTTY/ might help

You'll need to condition the serial line with the stty command to get this to work. One of the easier ways to do it is to start by using the Serial Monitor and running the command:
stty -g < /dev/tty.usbmodem1d112
That will show you all of the settings that the Serial Monitor used to conditions the line. The -g flag to stty tells it to give you the results in a form that can be used as the arguments to another stty command. You could do this like this:
echo -n 'stty ' > stty.arduino ; sudo stty -g -f /dev/tty.usbmodem1d112 >> stty.arduino
chmod +x stty.arduino
The first line creates a shell script to condition the serial line. The second line makes it executable so that you can run it as a shell command – ./stty.arduino. The sudo runs the command as root (with elevated privilege) which allows you to open the port even though the Serial Monitor will already have it open.
If you want you could move the command into a directory on your $PATH (for example ~/bin) so that it can be found regardless of where your current directory is.
After getting set up you can see the output from Serial.println() on the Arduino by doing:
./stty.arduino
cat < /dev/tty.usbmodem1d112
Depending on what you are trying to do, you might find the expect or script commands helpful. Expect (man page) lets you automate interactions with a text based application or process. Script (man page) creates a transcript of your interactions on the command line with another program or process.

Strangely, running the stty -g < /dev/... acts like the command is running, but nothing happened for long. When I use the second command to make a shell script, upon execution, it freezes my Terminal command line.

Can you show the output you get from stty -g…? Are you running the command with -f and/or sudo? I'm very puzzled that the second command, chmod, would hang your shell – it should succeed (or fail) immediately.

chmod was fine. The long command creating shell script works, but the execution of the sh hangs shell. I did try sudo, and -f, but it shows new line as if processing, but nothing seems to happen

When you say "nothing seems to happen" do you mean the command produces no output and you get your prompt back? Or, the prompt doesn't come back until you interrupt the command? Or, it appears to execute as you'd expect by the settings on the serial line are unchanged? Or,… Too many possible nothings :-)

Sorry for that inspecificness. Upon entering a command and pressing return, you get a blank line, and once the command executes, the usual Name@Device:~$ Shows up. And upon hitting return on that command, I do not get that Name@Device:~$ on the new line

Would you try ./stty.arduino < /dev/tty.usbmodem1d112 and see if that works? Looking this over, I see that the command to condition the line doesn't specify the line – so it's going to act on your terminal, and that's almost certainly not what you want.

I just get Resource busy when I try stty -g < /dev/tty.SLAB_USBtoUART on my machine. This is the correct path for my nodeMCU.

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


text:
How are HIDs (keyboard,joypad) created and mapped?
I am creating an electronic device that has a 4 position rotator switch and a SPST Momentary ON push button. For the knob, I plan for position 0 to be low (OFF). Position 1-3 are high (ON). But I want these positions to equate to a different signal so they each have different values. When push button is pressed, it sends a high (ON) signal.
Can someone point me into slightly setting up the circuit to accomplish this?
And how can I create a remapper program (preferably in C++) that detects the HID device and allows the end-user to remap the pushbutton signal to any QWERTY key? I want replicate this process for each input of my device.

Why not have the device send the appropriate key in the first place?

I want people to be able to remap the input, instead of just having a static key input.

And? Store the button-to-key mapping in EEPROM, and write a utility to change it.

I'll go with this example. I have a device that has one push button. I will program it to when the button is pressed, it sends a "generic" value to the computer. Now let's say I give this device to a friend, and he cannot re-program the device itself. How can I make it to where I have a computer software that can detect the "generic" button input and map it to whatever the friend wants to assign it to?

You'll need to write a driver that intercepts the generic HID message and translates it into an API call that the OS will understand. For every OS. It is much easier to write a program that uses a generic USB library to communicate with the device and tell it what each button should map to, and you only need to write it for one OS and publish the protocol for people who use the other OSes to use if they like.

Okay thanks. How would I go about coding that generic message in Arduino?

You wouldn't, because Arduino doesn't let you do that. Look at Atmel Studio and its USB examples, and do all the USB reading you can.

When the Arduino sends data to the computer using the HID protocol it sends what is called a HID Report. That is basically an array of numbers in a pre-defined format that correspond to what the computer is expecting.
In the case of keyboard events it sends a HID Keyboard Report

It can send events for up to 6 keys at once along with up to 8 meta keys.  How those key events are interpreted are down to the Keyboard Mapping used on the computer.  This is the setting (usually in the Language or Regional settings of the computer) that defines the layout of your keyboard - UK, US, French "AZERTY", etc.
While it is possible to create custom key mappings in many operating systems it is usually a very difficult and involved task. Also the mapping takes effect for every keyboard attached to the system, including the one you type on. So changing the mapping at will is probably not a good idea since it could break your normal keyboard usage.
So how would you go about doing what you want to do?  Well, my recommendation is not to do it on the computer, but to do it on the Arduino.  The Arduino has multiple interfaces available at once. As well as the HID interface for keyboard and mouse it also has the CDC/ACM interface for emulating serial. You can use both of these at once quite happily.  So you can use that USB serial interface to configure the way the Arduino works - including what key code to send for any particular event.  You could even write an easy-to-use GUI in Visual Basic or something that communicates with the Arduino over serial to adjust the settings.  How you do that communication (what protocol you come up with) is entirely up to you.

As for the hardware side of things - all you really need is just the switches / buttons and wire.  Just follow the on-line tutorials (there's millions of them) for connecting switches and buttons to the Arduino. Enable the internal pullups, and connect the switch between the I/O pin and ground.  For the rotary switch you will have 4 inputs and 1 output, so connect the 4 inputs to I/O pins and the 1 output to ground.

Is this sort of similar to how joypads work? What I'm trying to understand is how joypads can be remapped using software. For instance, Button 1 can be assigned to key F or key 4. I want to be able to replicate this with Arduino, as I will write a program to allow this remapping. So after reading this comment, can you kindly confirm that your post will accomplish this task.

All USB HID devices send HID reports. The format of each report for each device is different as befits the device. What is this "joypad" that you are on about?

The joypad is for video games. I'm trying to understand how games can detect a gamepad/joypad is connected and then allows you to assign a key per button.

@O.J.: Gamepads have their own HID report format.

@O.J. The game pad sends a report in its own format with its own numbers in the various fields. It's then up to the game what it does with those numbers. Windows doesn't really do anything much with the game pad - it just presents the numbers sent by it to the game. With a keyboard it is different because windows handles the incoming reports and maps them to key events.

Understood. So my overall result is to be able to create an API in C++ that can read the switch positions, etc.. Functions like Device.isConnected() and Device. GetSwitchPos() and Device.isButtonPressed().

@O.J.: If you're generating standard HID reports then the standard HID drivers will handle them. That is why I made the comment about having the device generate the correct report and having the software tell it which reports to generate. Otherwise you will have to go fully custom with your HID implementation.


text:
Arduino Yun & nRF24L01+ -> Linino crashing
I'm trying to hook up a nRF24L01+ wireless transmitter to an Arduino Yun Mini on SPI, but I'm having a hard time. After a few minutes Linino crashes and becomes completetly inaccessible - until I upload a new sketch to the Arduino.
I connected the SPI pins (MOSI, MISO and SCK) to the corrensponding pins of the Yun. I connected CE to pin 3 and CSN to pin 2. I'm using the RF24 library found here: https://github.com/TMRh20/RF24
The following little code is enough to make Linino crash:
#include <SPI.h>
#include "RF24.h"

RF24 radio(3,2);

void setup() {
  radio.begin();
}

void loop() {

}

What am I doing wrong here? Any ideas? Any help is greatly appreciated!

Sounds like lack of power to me. What are you powering the board with?

~14mA, I doubt it. Does Linino work with the default, empty sketch?

I power the board with an external power supply, two voltages common ground. 5V/1.5A attached to Vin. There is one component on the pcb (h-bridge) hocked up to 12V supply, common ground. There's a 3V3 voltage regulator (no logic level converter) between the 5V rail and the Vcc of the nRF24L01. And yes, Linino is doing fine with an empty sketch.

Random thought I had: Since I use an Arduino Yun mini I only have wifi to access linino. Could it be possible that the nRF24L01 is jamming wifi that much that it is unable to connect to the router? I guess that sounds strange but would explain the strange behaviour.

I tested the hypothesis of radio interference and I could be on to something. I did this before by changing the distance to the router, which didn't seem to do the trick. Now I got an external wifi antenna and it seems to work more stable now. I'll do a long-term test and post the results here.

I finally managed to get it running. It really seems to be a problem with radio interference. I failed to hook up an external WLAN antenna to the Arduino Yun mini but I found a very useful workaround with a usb adapter here:
http://www.lucadentella.it/en/2014/11/08/yun-adattatore-wifi-usb/
This workaround is possible with an Arduino Yun mini as well but you'll need the Arduino Yun Linux OS from here:
https://www.arduino.cc/en/Main/Software
because the necessary packages are not available for the Linino system that comes with the Yun mini. Then, you can connect the WiFi adapter to USB+, USB-, 5V and GND of the Yun mini and you're good to go.


text:
ESP-01 OTA Error uploading
Im trying to do OTA upload from Arduino IDE.
Uploaded BasicOTA to ESP-01 with flash size set to (FS:2mb, OTA 1019kb).
ESP-01 connects and shows up in Port selection, but when trying to upload I get
Uploading.................................................

14:40:35 [ERROR]: Error Uploading

Thats the only output I get.
Anyone had similar issue?
Thx

Does your ESP-01 have that much flash?

nop, read wrong the chip info value. It said 4Mbit and I read 4mb. Dumb me

The ESP-01 comes in two variants: blue, with 512KiB flash, and black, with 1MiB flash.
You have chosen an arrangement that needs 4MiB flash.  It won't fit.
Choose a suitable flash size for your board.

Im using Blue variant. Read the chip info using espressifs flash tool and it read 4MBit. In my haste I read 4MB not Mbit :) I have a black variant, will try with it


text:
Burning the Bootloader on Adafruit Feather 32u4
So, the default bootloader in Arduino is oddly set to erase EEPROM with every reboot, rendering the EEPROM, well, useless.
I found where the fuses are set in the boards.txt file, but getting this configuration change into the chip requires burning an updated booloader.
In the Arduino IDE, there is an option to "Burn Bootloader", but that would be way too easy, and of course, doesn't seem to work.
I can't find any clue on the Internet about how to actually get the bootloader updated in these devices.
So, is it possible to reprogram the bootloader on the Adafruit Feather 32u4 devices?
If so, what's the trick to do it?

Are you sure it erases on every boot and not on every re-flash?

Yes, it seems to be every boot, however I am looking to survive re-flash, so I needed to set the EESAVE bit correctly to make this work.

Update:  it looks like i had a bug in my code that was making me think EEPROM data wasn't being saved, so I ended up not needing to burn the bootloader after all.  Woot.

"Burn Bootloader" only works if you have a programmer connected to the device. The onboard bootloader in your Feather cannot change the fuses, even though the process may indicate it has done so.
You would have to connect an ICSP (In-Circuit Serial Programmer) to the correct pins (MOSI, MISO, SCK, RESET, VCC, GND). You can use another Arduino as a programmer by uploading a specific sketch to the Arduino to make it an Arduino as ISP.
The normal bootloader on an Arduino emulates this kind of device to allow programming by serial/USB port, but it has limitations. The ICSP process is the native way to get a program onto the AVR chip, and is the only way to set fuses.
EDIT:
This AVR USB Bootloader Datasheet states on page 3:

• Boot Reset Fuse The Boot Reset Fuse (BOOTRST) can be programmed so
  that the Reset Vector points to the Boot Flash section start address
  after reset. Once the user code is loaded, a bootloader command
  (“start application”) can start executing the application code. Note
  that the fuses cannot be changed by the MCU itself. This means that
  once the Boot Reset Fuse is programmed, the Reset Vector will always
  point to the Bootloader Reset and the fuse can only be changed through
  the serial or parallel programming interface. The BOOTRST fuse is not
  active in the default factory configuration.

That document also references AVR282: “USB Firmware Upgrade for AT90USB” (Note, I could not find this on the Atmel website.) This document details the FLIP program, at Atmel tool for uploading firmware over the USB DFU interface and setting configuration settings, etc.
This doc has a FAQ section which states:

Can I modify the fuse bits using Flip? • No, Flip cannot modify the fuse bits. To modify the fuse bit you can use either the JTAG ICE
  MKII, the AVRISP MKII, or parallel programming

So, while this may not be a definitive answer, it appears at this time that "burning fuses" cannot be done over USB on the 32u4. If that's not the case, I'm sure the site would welcome the new info.

Note that the question is about a 32u4, not a traditional Arduino, so I believe there are some hardware-assisted DFU options in addition to ISP.

Not long after I asked this question, I had a "duh" moment and and realized I had a JTAGICE3 in my drawer.  Once I got the pinout right, and overcame a problem with macOS grabbing the device, I was able to cobble a way to get the bootloader to work.  I'll post a complete answer here later today so everyone gets the benefit.

In my case the 32u4 (Lora32u4II) failed after uploading big firmware. Not responsive.
Fortunately I have the buspirate 4 with firmware 7.0. And during this time I discovered that the BusPirate is not able to power the board to reflash the firmware. But if I connect the board over USB and then the cabling as described:
BUS PIRATE - LORA32U4II
MISO              MISO
MOSI               MOSI
CLK                SCK
GND                GND
CS                 RST

And I use arduino ide to upload a new bootloader it starts to work again. So. I wonder why the firmware update locked the board while there's enough space. And why powering over 5v doesn't get it to work on buspirate + arduino ide.
I leave info for others that have same problem.
I discovered that using this method, even if slower, I can skip bootloader, leaving more room for my firmware...


text:
how to detect the incoming message from sim800 GSM module
I am designing an motorcycle security system and I need to receive the message  from the user.Hence i need to detect the incoming message and read the number and data from the message

How does your question differ from http://arduino.stackexchange.com/q/2899/6628 ?

i am not using gsm shield i am using sim800

So you are looking for the specific codes or a library for receving SMSs on the SIM800?  Wiring? Code for parsing the messages?

yea, i need to first identify the incoming  message if it is received i need to the parse the phone number and content of the message


text:
Using 6 axis accelerometers
I've been messing around with accelerometers for Arduino for a school project. I bought the SODIAL GY-521 accelerometer + gyroscope module for Arduino. It uses de Invensense MPU 6050. I managed to connect it onto my board and successfully detect it, but it returns values of -1 on all output ports. I was expecting there to be a port for every axis of acceleration and rotation but it seems that this isn't the case. How should I connect the module into my Arduino, and how should I program the Arduino to read my data?
I tried to follow the Arduino Playground example but the result was as explained above.
Thank you for all answers.

From the Arduino playground:
This sensor board has a voltage regulator. When using 3.3V to the VCC the resulting voltage (after the onboard voltage regulator) might be too low for a good working I2C bus. It is preferred to apply 5V to the VCC pin of the sensor board. The board has pull-up resistors on the I2C-bus. The value of those pull-up resistors are sometimes 10k and sometimes 2k2. The 2k2 is rather low. If it is combined with other sensor board which have also pull-up resistors, the total pull-up impedance might be too low.

I am kind of new to this whole electronic thing, so I may need a little more explaining. I believe I connected the module into the 5V pin but I have no idea about the other stuff you mentioned.

First of all you should measure the pull-up resistor values. Secondly do you have other I2C devices connected?

My circuit consists of an Arduino Uno + accelerometer, nothing else. My question is where do I connect what and why, and how do I code it. So basically everything.

I usually use the following connections for my MPU 6050:
Vcc: 3.3V
GND: Any arduino GND
SDA: A4
SCL: A5
AD0: GND(for address 68)/ 3.3V(for address 69)
I do not usually connect any of the other pins. For the code I usually use a wonderful library written by Jeff Rowberg which can be found here(http://www.i2cdevlib.com/devices/mpu6050#source). This library enables you to also use the Digital Motion Processor on board the MPU 6050 to give you prefiltered rotation data. It also has example code which should make things easy.
You can connect at most 2 MPU 6050s to the I2C port of the arduino by using different addresses for it. If you need to hook up more, you will require a multiplexer.
Hope this helps.


text:
Arduino Pro Mini
I have the following problem
I have a pro mini clone, with 328/5V. It was successfully working in my board. I pulled it out of the board, and wanted to update my software. I connected it to my FTDI, arduino was normal by this time. Power on LED was on. I stared uploading, my sketch compiled and started writing. While it was writing, my 3.5 year old daughter who approached me from behind and whom I did not see pulled the Arduino out of FTDI - "what is that nice red light?" Of course writing failed.
Now, when I connect the arduino to FTDI, it is dead. No LEDs light up, no sync... what to do? Any chance to revive it?

Check the FTDI as well. Voltmeter could be helpful.

Just flashed another Arduino board to test - worked without problems...

Ok, then if looks like FTDI is alive and the Pro Mini is dead.

Just decided to examine the Arduino for physical damage, and that was it! Looks like she ripped Arduino off the cable so hard, that the solder holding the programming pin row was not holding! I resoldered all connector pins, and it worked now!

Tough thing. You are lucky. Cheers! Please mark the question as answered (i.e. provide your solution as an answer and accept it).

Check for physical damage! Solder connection of the programming pins to the board was damaged in my case. Resoldering helped!


text:
Should I use OOP?
I am a long time participant in a competition called Robocup Rescue Line. For next year's competition, I am building a robot (and the code for the robot) from the ground up. The tasks that the robot has to do are complex enough for the code to be a fairly complex thing. I have some experience with classes and OOP so I thought I could try to organize the code in a OOP fashion. I thought I could have a class for each type of Sensor (e.g: LineSensor(), RGBSensor UltraSound()...) and another for the Motors (e.g: Motor()) that would have two instances on the code. Basically, all the code has to do is take sensor readings and produce a motor response. With this class structure, where would I do this correspondence? Is this not appropriate for this kind of project? Is there a better way to do this, that is still OOP?

I have a lot of experience with OOP, but mostly in embedded/pure software designs. However, I'm sure you can use it in a robot project too.
Avoid creating lots of objects dynamically, this results in gap in the very small memory available for the Uno. Try to create the object instances beforehand (this will also benefit performance hits during execution, by placing it into the initialization).
About the Sensors: you can make a baseclass if needed (Sensor) and let other classes derive from it (there is a small performance hit when calling methods though).
For the controlling:

Put sensor readings in the sensor classes
Put motor responses in the motor classes
Put the control in a special class (Control?) that couples the sensor response to the motor response.


text:
Programing uploading to Arduino due
I am new to Arduino and bit blur on how it works. lack of info on the net about it. please help me with these questions!

Does Arduino due allow you to upload a program on programming port and then run it through Native port?
Can I work with SerialUSB instance in Programming port?

lack of info on the net about it Then you can't be looking very hard.

Does Arduino due allow you to upload a program on programming port and then run it through Native port?

You don't run a program through anything. You run it on the Due. Where you send text to is entirely up to you.

Can I work with SerialUSB instance in Programming port?

I have no idea what you are asking there. Both the Programming port and Native port are capable of being used as virtual USB COM ports. They use CDC/ACM. One is directly connected to the SAM3X chip's USB peripheral, and the other is connected to the SAM3X's UART interface via another microcontroller as a USB to UART converter.


text:
How to send data from Arduino Uno with SIM900 GPRS to Firebase
I'm creating a real-time vehicle tracking Android application using the Arduino Uno and SIM900 GPS. I want to use Firebase as the database for the coordinates which will hold just the longitude and latitude. My question is about sending the data through the GPRS to Firebase. Right now I've only been able to use a terminal program to send AT commands to create a connection but I've been getting errors when connecting to firebase using AT+CIPSEND. I know that it only excepts https traffic so I've been trying commands from here. Here is some code that I've tried:
AT
OK
AT+CREG?
+CREG: 0,1

OK
AT+CGATT?
+CGATT: 1

OK
AT+CIPSTATUS
OK

STATE: IP INITIAL
AT+CIPMUX=0
OK
AT+CSTT="att.mvno","",""
OK
AT+CIICR
OK
AT+CIPSTART="TCP","https://mygpstracker.firebaseio.com","80"
OK
CONNECT OK

and
AT+CIPSHUT
OK
AT+CIPSTART="TCP","https://mygpstracker.firebaseio.com","443"
OK
CONNECT OK

If I use CIPSEND, how should my message be formatted to send lat or long in a way Firebase can interpret?
Or am I going about this in a convoluted manner? Is there an easier way? I appreciate any help/comment. Thank you.

Like you said, Firebase only accepts HTTPS traffic, which the Arduino Uno cant generate. Your HTTP requests first need to be sent through a proxy server that supports SSL, before being sent on to your Firebase database using a PUT or POST request. This site explains how to do everything from setting up your own proxy server to writing the GPS data (in your case) to Firebase. You may want to look at alternatives if this is too tedious for your purposes.

just remove "https://" its working


text:
Controll LED Strip with Arduino BLE
I'm working on this project where I have interfaced a LED strip (a two wire LED strip) with this Arduino (its not an Uno). I have setup every thing correctly according to this instructable. I'm able to make a simple blinky pattern and I turn it on/off with an Android app I made to communicate with the Arduino using Bluetooth on my phone. Cool.
What I cannot understand is, since the strip is two wired, how should I address individual LEDs on the strip to make more complex patterns? Can I use bit shifts? Reading an article from Makezine (insufficient reps to post more than 2 links), it says that I should connect the strup directly to the output pin. IMO, this will fry the Arduino or in a less virulent sway, not light up the strip in any way.

Is this the article you mention ? It does say to connect directly only for 1 or 2 LEDs and you are right : typical limit is 40mA per Arduino output pin. And it won't work directly if you have common anodes like in the schematic.

Addressing individual LEDS on a simple strip with LEDs in series and/or parallel connection is just not possible.
Connecting the strip directly to an output pin is completely nonsense. Forget it.
You need a strip with digital LED controllers populated, as described (for instance) in another link mentioned in your second link: http://www.adafruit.com/products/306
Have a look at this, then I'm sure you will come back with more detailed questions ;-)

Nice ! Have you tried this type of LED strip, I'm very curious about it ?

@FredP: I didn't try. But I found a really awesome project with a similar type. Have a look at this: https://www.pjrc.com/teensy/td_libs_OctoWS2811.html


text:
Arduino Yun - Sensor Data logging to MYSQL on External Server
I want to log data from Sensors (Say Temperature, moisture or humidity) to a MYSQL database (provided by a online hosting company). Is it possible to establish communication between Arduino Yun and that database and log the data to it

Yes, you can do that using python as well as other languages, or you can use Temboo: there's an example bundled with the Arduino IDE, it's called "SendDataToMySQL"


text:
Convert long to char array and back
I'm trying to store a state in my data logger. I can read/write fine to SD, but I can't wrap my head around reading/writing a long value correctly - I've build it down to converting it to char array and back.
My best try so far has been
long temp = 1418172669L;
unsigned char buf[4];
buf[0] = temp         & 0xFF;
buf[1] = (temp >>  8) & 0xFF;
buf[2] = (temp >> 16) & 0xFF;
buf[3] = (temp >> 24) & 0xFF;

long  l = buf[0] | (buf[1] << 8) | (buf[2] << 16) | (buf[3] << 24);

But l is very different from temp - currently the output is -26371. Am I making an obvious mistake?

I suggest using a union:
union {
    char myByte[4];
    long mylong;
} foo;

Char to Long:
Then you can just add the bytes:
foo myUnion;
myUnion.myByte[0] = buf[0];
myUnion.myByte[1] = buf[1];
myUnion.myByte[2] = buf[2];
myUnion.myByte[3] = buf[3];

Then you can access the long as:
myUnion.myLong;

Long to Char:
The same if you want to go the other way from long to char array:
foo myUnion
myUnion.myLong = 1234L;

To access bytes:
myUnion.myByte[0];
myUnion.myByte[1];
myUnion.myByte[2];
myUnion.myByte[3];

Thanks, this worked great (for longs, not for floats). Can you give me a documentation link for union?

@LordT: I don't know why I used float as an example, I must have misread. I have no link to a "documentation" page, but this is a tutorial/example I think is good: http://www.tutorialspoint.com/cprogramming/c_unions.htm

I think the last expression is performed exclusively as an int expression and converted to long only at the end, i.e. before assignment to l.
long  l = buf[0] | (buf[1] << 8) | (buf[2] << 16) | (buf[3] << 24);

Here the compiler calculates buf[0] | (buf[1] << 8) | (buf[2] << 16) | (buf[3] << 24) as an int only.
If you give a hint to the compiler by telling it you want long expressions used, then it should work. The easiest way to do so is to replace the number of bits to be shifted as long literals:
long  l = buf[0] | (buf[1] << 8L) | (buf[2] << 16L) | (buf[3] << 24L);

That should be enough for the compiler to perform the whole operation as long and not loose precision.

Sorry, even with the implicit long, the result is -26371.

Just for completeness, after posting this, I've found another way around it, but @Phataas solution is much more elegant.
Using the ltoa and atol functions, long to char array and vice-verse can be done like this:
char temp[10];
ltoa(669L,temp,10);
long result = atol(temp);

It is also a lot more inefficient.

Yes, it is - but if you're goal is to write a text file to SD card, it beats the binary approach. I've ended up using a combination of the byte conversion with union and the ltoa version for printing to log files


text:
How to have precise measurements
I need to display measurements of a sensor which need to be presented on a precise time-scale.
Since the loop function is not quite precise, how can i make sure that i can measure at say for example exactly 1ms?
( I am using an ADXL345 sensor )
Thanks a lot!

The ADXL345 has both a FIFO and data rate setting. This allows sampling to be done with a precise frequency without having to use timers, etc, on the MCU. The MCU/Arduino has to fetch data before the FIFO overflows. The max sampling frequency depends on the communication protocol (I2C or SPI), i.e. how fast the MCU can empty the FIFO.
It is possible to use the ADXL345 in stream mode, collect samples at a fixed rate, and get an interrupt when the FIFO has been filled to a specified level (watermark). The samples can then be read in burst mode.
The samples will be on a "precise time-scale".
There are even more advanced usages of the device with tap, double-tap and free fall detect.
Please see Data Rate setting and FIFO control in datasheet.
Cheers!
PS: Using I2C at 100 KHz will take 1 ms just to address the device. Addressing a register will take another ms and a ms per data byte. Reading the data register (six bytes) will take at least 8 ms. Realistic max sample rate with I2C at 100 KHz is 10-100 Hz. There is also limited amount of memory for buffers.

Microcontrollers have built in peripherals called Timers. They are used for many purposes, including working out when something should be done.
There are plenty of good Timer libraries around for the Arduino, including the popular TimerOne/TimerThree libraries.


text:
How to produce 6 PWM signals with 60 degrees phase shift?
How to produce 6 PWM signals with 60 degrees phase shift using Arduino Uno 6 PWM pins like in the image below?

What duty cycle? 50%?

You could also use a timer interrupt, that will bitbang PWM. Kind of similarly to how the servo library send "PWM" signals to multiple servos.

Using hardware it's not possible. Simply because you effectively only have three PWM timer units, each with two compare outputs.
That means you have three timebases, which are each compared with two values for two PWM signals each.
You would need a single master timebase with six independent offsettable counters with comparison for your needs.
It would be possible to (roughly) do it in software, though, depending on your needs. You get jitter from software generated PWM, due to interrupts getting in the way of your smooth execution. However you have complete control over how the waveform is generated. Instead of a 0-X duty cycle you could program it to have an X-Y duty cycle. And with all of them taken from the same counter value it's then all synchronised 100%.

Can I make the 3 timers begin counting at the same time?

Not precisely, no. There is no way of starting them in the same instance. You could do it close together though. It wouldn't give you different phases then though.

You can invert one of the two PWM outputs.

You'd have to setup the timers with appropriate TCNTx values before starting them at the same time.

You can start the three timers at the same time by using the “Timer/Counter Synchronization Mode”. See the description of the GTCCR (General Timer/Counter Control Register) in the datasheet.

I found the correct method for 6-phase PWM as the OP requested. And it can have any duty-cycle you want. My erroneous findings for 50% only duty we're because I used Fast-PWM mode. When I switched to Phase-PWM (mode-10-PWM in a 2560 ARduino), I got the correct waveforms, the same as the OP wanted.
Below is a link to a logic-analyzer snapshot showing the 6-phases from a 2560. The frequency is 500 Hz but that's easy to change. 4 Timers in all used to realize this outcome. 3 Timers used mode-10-PWM, 1 mode-14-PWM at the same frequency.
The full project is documented at Runtime Micro.

EDIT:
I can now do this using an Uno. But there are limitations to duty-cycle and some other concerns. Provides usable N-channel (2, 3, 4, 5, and 6) phase-shift PWM from a single Uno board.
EDIT:
A full 6-channel PSPWM solution using only an Uno is now published at Runtime Micro under Projects Menu. You'll find details, images, code and diagram. There are limitations such as no channel-to-channel overlap in pulse-width.
FWIW

Are you able to share your code so others can follow your method?

Use a timer to trigger an interrupt. Set the timer to 1/6 of the overall pwm cycle to get to 60degree phase. Each time the interrupt is triggered it turns on the next channel.
You could have a second timer and interrupt to turn them off working in the same manner.


text:
AVR - How to know that there is collision between stack and heap or the memory has filled?
I am using the dynamic memory in AVR microcontroller, so How to know that there is collision between stack and heap or if the memory has been filled?

I am using the dynamic memory in AVR microcontroller, so How to know that there is collision between stack and heap or if the memory has been filled?

The first thing that happens is that malloc() will return NULL saying that memory could not be allocated. The AVR heap implementation has a few safety measures. One is to check that there is a minimum margin (__malloc_margin) between end of the heap and the top of the stack. This can be adjusted by the application.

Typically the minimum margin should be able to hold the largest stack usage (typically deepest function call tree with the largest local variables usage) plus largest ISR stack usage.
If the stack runs into the heap the memory block/s at the end of the heap is/are corrupted. What happens depends on the type of data structure.
Not checking NULL return from malloc() gives some interesting errors on the AVR as the processors registers are memory mapped. NULL points to R0.

A good rule of thumb when using malloc() in small scale embedded systems is 1) avoid it, 2) allocate memory with malloc() during the setup(). All other dynamic memory need be allocated temporary on stack and only for the processing.

“allocate memory with malloc() during the setup()”. If you know from the very beginning how much memory you need, there is no point in using malloc() instead of static buffers. As to what usages of malloc() are safe, see my answer to a related question.

@EdgarBonet I seem to have missed one of the requirements; software with dynamic configuration, e.g. EEPROM variables that say number of elements, etc. The actual size of the dynamic data structure is not known at compile time or is allowed to change. In other cases, I fully agree with your objection. If the size is known avoid malloc().

In simple terms: if the stack and heap have collided then the program will most likely crash, and any countermeasures you may have in place are now null and void.
However, you can find out the current amount of free memory quite easily by looking at where the top of the heap is and creating a local variable on the stack and getting its address - subtract one from the other and you get the free memory size.
That's exactly what the MemoryFree Library does for you.

What happens if the program crashes? Will the AVR reset the program?

Anything at all can happen. No one can predict what might happen.  The watchdog exists as a method to try and recover from such scenarios.


text:
Print string and integer LCD
How do I print a string and integer on an LCD? Here is what I have tried:
int number = 2;
int result = (number + number);
lcd.print(number, DEC + " plus " + number, DEC + " equals " + result, DEC);

And the result is an error.  When I try:
lcd.print(number + "look");

or
lcd.print("1234 " + number);

Then the result on the LCD is "34 ", as it deleted the first two numbers!
I want it to print:
1234 2
Please help!  Thanks!

The lcd.print() method takes a string or a number as an argument, but not both at once. Using the + operator for concatenation is not native to C strings. C strings are basically stored as pointers to the first character of the string. So when you tried lcd.print("1234 " + number) and got "34 ", what most likely happened is that you advanced the pointer, pointing to the first character of "1234 "(i.e. '1') by number (i.e. 2), thus making the pointer point to the 3rd character in the string and thus making lcd.print() display "34 ".
In order to print something that contains both strings and integers, the most straightforward way is to convert each piece to an Arduino string and then concatenate them, using the + operator like you did earlier.
    lcd.print(String("1234 ") + String(number));
    lcd.print(String(number) + String(" plus ") + String(number) + String(" equals ") + String(result));

These are some examples. You could also use create a sufficiently large char buffer and use sprintf() from stdio.h to build a string made up of integers and strings. Look up a textbook on C/C++ for more details.

I got the same problem and I printed the string and the integer on the same line by moving the cursor like this :
   lcd.setCursor(0, 0);    <----------Column 0 , Line 1
   lcd.print("This code failed");
   lcd.setCursor(0, 1);    <----------Column 0 , Line 2
   lcd.print("Error Code = ");
   lcd.setCursor(13, 1); <-change the cursor for the INT. Column 13 , Line 2
   lcd.print(int);

What happens if a first error code is, say, 1234, then another one is 57... the display would show "5734" right?

int a=0;
float b=10.01;

char str[16];

sprintf(str,"a=%d, b=%.2f, c=%d", a, b, 2); // use sprintf() to compose the string str

lcd.print(str);

The output will be 'a=0, b=10.01, c=2'

What is wrong with this:
lcd.print(number, DEC + " plus " + number, DEC + " equals " + result, DEC);

It is the number of parameters and the assumption that plus will concatenate string literals.
lcd.print("1234 " + number);

This gives "34 " when number is 2. Why? This is because that is the result of adding 2 to the string literal pointer, i.e. the string starting at the character "3". Please use separate print statements instead:
lcd.print("1234 ");
lcd.print(number);

Do not use String to concatenate strings. That is a waste of SRAM, processing and has a risk of heap fragmentation. Simply a bad idea in small scale embedded systems such as AVR.
To understand these errors you should go back and read about strings and string literals in C/C++ (compared to Java :).
Cheers!


text:
Join Serial Data Seperated by Newlines?
I have two Arduinos connected through Bluetooth. One sends a string of data similar to 506:507:1\r\n. The data can vary similar to 0:1000:0\r\n. I already have functions to break that string down into three variables. I send it from one Arduino over Bluetooth and the second Arduino receives it through Serial. The only problem is that the second Arduino receives this:
5
0
6
:
5
0
7
:
1
"\n"

At the end it adds a space at the end ("\n") How can I parse this data back into a string similar to 506:507:1\r\n that can still vary in length?

Read this: https://hackingmajenkoblog.wordpress.com/2016/02/01/reading-serial-on-the-arduino/

I don't see what the problem is?
Though, you do seem to miss the \r?
And I don't see the space at the end? You can easily make it a string by adding the characters to the string, until you receive your end character \n?
Maybe https://www.arduino.cc/en/Serial/ReadStringUntil is an easy to use, "all in one" solution for you.

Simply reverse the steps you took on the sending side.

Create a char array of sufficient size as well as an index variable to keep track of your position within the array. An Arduino String may be more convenient, though they can cause a lot of problems.
In a loop, use available() to wait for incoming chars and add them to the array you've created, using your index variable.
Keep going in the loop, while checking for that unique character (\n, perhaps) that signals the end of a packet. Add this last byte to the array and then terminate the string with null or \0.

If you want to re-use the array for another packet, simply set the index variable to 0 and continue.


text:
Led on when not supposed to be
So I made a program that controls two LED's when two buttons are pressed, but one of the LED's comes on when the button isn't pressed. And what's weird is that if I literally move around the breadboard the LED might turn off for a little, and if hold the button down while doing it the LED remains solid. I have done a lot of taking out and switching wires without any unexpected effects. However, if I switch the LED wires the other LED turns and stays on while the first one turns off, so I am pretty sure that it is a programming error. Here is my code:
const int ledPin1 = 8;
const int buttonPin1 = 1;
const int ledPin2 = 9;
const int buttonPin2 = 2;

int buttonState1 = 0;
int buttonState2 = 0;

void setup()
{
  pinMode(ledPin1, OUTPUT);
  pinMode(buttonPin1, INPUT);
  pinMode(ledPin2, OUTPUT);
  pinMode(buttonPin2, INPUT);
}

void loop()
{
buttonState1 = digitalRead(buttonPin1);
buttonState2 = digitalRead(buttonPin2);

  if (buttonState1 == LOW)
  {
    digitalWrite(ledPin1, HIGH);
  }
  else
  {
    digitalWrite(ledPin1, LOW);
  }

  if (buttonState2 == LOW)
  {
    digitalWrite(ledPin2, HIGH);
  }
  else
  {
    digitalWrite(ledPin2, LOW);
  }
}

You use pull up or pull down resistor for button?

The behavior you describe is symptomatic of a floating input.
I guess you have directly wired your buttons between input pins and +5V (or GND, that won't change the observed behavior).
The problem is when you don't push the button, the input pin is left floating and can be read as HIGH or LOW based on strange factors.
The solution to this is to use pullup (if you connect the other side of the button to GND) or pulldown (if your button is connected to +5V) resistors.
The following image, off the arduino website, shows such a circuit with a pulldown resistor, i.e. connect the switch to +5V and the resistor to GND:

An even simpler way is to connect the buttons to GND and use pinMode(pin, INPUT_PULLUP); in setup().

Just note that when you are using Pull-Up resistors the signal is inverted. So you'll read a LOW when pressed, and HIGH when not. No big deal; just change buttonState2 == LOW to buttonState2 != LOW

I don't think it is necessary to do the declaration of int buttonstate1 = 0; and int buttonstate2 = 0; seeing that in your loop the buttonstates gets read by you using digitalRead. Also I don't think the buttons is inverted, because you aren't using a pull up resistor if I'm correct.
Hopefully this helped.
Also something that I found helped a lot is that if you use a lastbuttonstate variable too. Than your if statement might look something like this:
if(buttonstate1 == HIGH && previousbuttonstate1 == LOW)
{
digitalWrite(ledPin1, HIGH);
previousbuttonstate1 = buttonstate1;
}

else if(buttonstate1 == HIGH && previousbuttonstate1 == HIGH)
{
digitalWrite(ledPin1, HIGH);
}

else if(buttonstate1 == LOW && previousbuttonstate1 == HIGH)
{
digitalWrite(ledPin1, LOW);
previousbuttonstate1 = buttonstate1;
}

else
{
digitalWrite(ledPin1, LOW);
}

Basically adding the previousbuttonstate1 just gives it a more accurate way of checking the button state(I'm typing under correction).
Sorry for the sloppy answer, but hopefully it helps.


text:
Wireless Shield Not being detected w/ Arduino Uno R3
Wireless Shield is not being detected by arduino, not MAC address is displaying.
 Not sure what to try next, there is nothing noticeably wrong with the shield at first glance.
Green LED under status is on.
Shield Type: CC3000 WiFi Shield
Board Model: UNO R3

No Mac Address is being detected (my output in Serial Monitor)
Initializing Wifi...
MAC: 0:0:0:0:0:0
Scanning available networks...
** Scan Networks **
number of available networks:0

My Script:
#include <SPI.h>
#include <WiFi.h>

void setup() {
  // initialize serial and wait for the port to open:
  Serial.begin(9600);
  while(!Serial) ;

  // attempt to connect using WEP encryption:
  Serial.println("Initializing Wifi...");
  printMacAddress();

  // scan for existing networks:
  Serial.println("Scanning available networks...");
  listNetworks();
}

void loop() {
  delay(10000);
  // scan for existing networks:
  Serial.println("Scanning available networks...");
  listNetworks();
}

void printMacAddress() {
  // the MAC address of your Wifi shield
  byte mac[6];

  // print your MAC address:
  WiFi.macAddress(mac);
  Serial.print("MAC: ");
  Serial.print(mac[5],HEX);
  Serial.print(":");
  Serial.print(mac[4],HEX);
  Serial.print(":");
  Serial.print(mac[3],HEX);
  Serial.print(":");
  Serial.print(mac[2],HEX);
  Serial.print(":");
  Serial.print(mac[1],HEX);
  Serial.print(":");
  Serial.println(mac[0],HEX);
}

void listNetworks() {
  // scan for nearby networks:
  Serial.println("** Scan Networks **");
  byte numSsid = WiFi.scanNetworks();

  // print the list of networks seen:
  Serial.print("number of available networks:");
  Serial.println(numSsid);

  // print the network number and name for each network found:
  for (int thisNet = 0; thisNet<numSsid; thisNet++) {
    Serial.print(thisNet);
    Serial.print(") ");
    Serial.print(WiFi.SSID(thisNet));
    Serial.print("\tSignal: ");
    Serial.print(WiFi.RSSI(thisNet));
    Serial.print(" dBm");
    Serial.print("\tEncryption: ");
    Serial.println(WiFi.encryptionType(thisNet));
  }
}

Try using a library for the CC3000 instead of the one for the Arduino Wifi (W5100) board. You may have a little bit more luck.

Which wifi shield are you using?

Your problem:

You have a CC3000 WiFi shield
You are using the WiFi library for the Arduino WiFi Shield
The Arduino WiFi Shield is a HDG204 based shield, not CC3000

Get the right library for your shield, install it, and try the examples and tutorials that come with it.

Using CC3000 Libraries seem to work.  Thanks


text:
No Socket Available message floods serial monitor
Serial Monitor get's flooded with "No Socket Available" message.  This seems to occur even before I Try to communicate with my Hue bridge through my hub port.  Does anyone see why this is occurring after my wireless connection is established?
Serial Output:
Firmware needs upgrade
Attempting to connect to WPA SSID: ifiw_ym
connected to the networkSSID: ifiw_ym
BSSID: 0:B2:8F:6A:C4:28
signal strength (RSSI):-47
Encryption Type:4

IP Address: 192.168.1.7
192.168.1.7
MAC address: 78:C4:E:1:9F:B1
in loopin loopin loopNo Socket available
No Socket available
in loopNo Socket available
No Socket available
in loopNo Socket available
No Socket available
in loopNo Socket available
No Socket available
...

code:
#include <SPI.h>
#include <WiFi.h>

//  Hue constants
const char hueHubIP[] = "192.168.1.6";
const char hueUsername[] = "my_hue_app";
const int hueHubPort = 80;

boolean activated = false;

//  Hue variables
boolean hueOn;
int hueBri;  // brightness value
long hueHue;  // hue value
String hueCmd;  // Hue command

unsigned long buffer=0;  //buffer for received data storage
unsigned long addr;

// Wireless network
char ssid[] = "**********";
char pass[] = "**********";
int status = WL_IDLE_STATUS;
WiFiClient client;

//0:B2:8F:6A:C4:28

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

  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    while (true);
  }

  String fv = WiFi.firmwareVersion();
  if (fv != "1.1.0") {
    Serial.println("Firmware needs upgrade");
  }

  while (status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    status = WiFi.begin(ssid, pass);

    // wait 10 seconds for connection:
    delay(10000);
  }

  Serial.print("connected to the network");
  printCurrentNet();
  printWifiData();
}

void loop() {
  Serial.print("in loop");
  // printCurrentNet();
  alterHueColors();
}

void alterHueColors() {
  if(activated){
    client.println("Hue is activated");

     // A series of four sample commands, which colour fades two lights between red and pink. Read up on the Hue API
    // documentation for more details on the exact commands to be used, but note that quote marks must be escaped.
    String command = "{\"on\": true,\"hue\": 50100,\"sat\":255,\"bri\":255,\"transitiontime\":"+String(random(15,25))+"}";
    setHue(3,command);
    command = "{\"on\": true,\"hue\": 65280,\"sat\":255,\"bri\":255,\"transitiontime\":"+String(random(15,25))+"}";
    setHue(4,command);
    command = "{\"hue\": 65280,\"sat\":255,\"bri\":255,\"transitiontime\":"+String(random(15,25))+"}";
    setHue(3,command);
    command = "{\"hue\": 50100,\"sat\":255,\"bri\":255,\"transitiontime\":"+String(random(15,25))+"}";
    setHue(4,command);

    activated = true;
  }
  else{
      activated = false;
      client.println("deactivated");

      //was activated, so send a single off command
      String command = "{\"on\": false}";
      setHue(3,command);
      setHue(4,command);
  }
}

It's also interesting to not that my print calls in alterHueColors()  aren't triggering.
Full .ino file

For one thing, your logic is backwards. activated = false to begin with. So in alterHueColors() the if condition will never be true and only the else block gets executed because it keeps activated = false;.

Second, can you open 192.168.1.6:80 from any other pc on the network?

@johnnyMopp Thanks for finding that, i've noticed that as well.  Fixed it locally, I will update.  After update it does go through the else.  The 192.168.1.6:80 is accessible on my browser.  However, the No Socket Available message still occurs in serial monitor.


text:
Which is faster, Serial or DigitalWrite?
I am working on an Arduino Uno battle bot that uses a Sabertooth moter controller. Right now it is connected to the Arduino through Serial communication. Which is would be faster (So I can increase response time on my robot) Serial, or pwm using DigitalWrite?

I don't understand how you could substitute one for the other. Are you designing both ends? What sort of commands are you sending? Speed? Direction?

Using digitalWrite() is the slowest by far.
Using PWM could be the fastest.
Using Serial could be the fastest.
PWM:
You have to filter the PWM output to be a smooth analogue signal for it to be of any use. The filtering adds an inherent sluggishness, or response time, to the system - the harder the filtering the slower the reaction to changes in the PWM duty cycle. Adjusting the filter component's values will give an optimum point between smoothness and response time. Bear in mind that the motors may respond erratically if there is insufficient damping of the signal. This will probably give the Sabertooth a hard time, too. The datasheet recommends are filter response time of greater than 1ms.
Serial:
If you are considering the 2x 60Amp version (thanks for adding plenty of information in the question, by the way) then the fastest baud rate is 384kbps - or 48k commands per second. The Arduino will of course not be churning data continuously because it'll be busy running the rest of the program, but using serial it is theoretically possible to send commands faster than the motor controller's output PWM.
So which is faster?
No idea. Only you can determine this, and I doubt you'll be able to determine the answer without wasting your time on some experiments.
The motors will have an inherent mechanical dampening thus creating an overall bottleneck in the whole system response time. I can almost guarantee that both PWM and Serial methods will be much faster than the response time of the motors themselves.

The fastest would be “Simplified Serial Mode” at 38400 bps.
In this mode, a command is a single byte, transmitted as ten bits
(1 start + 8 data + 1 stop), which would take 0.26 ms to be transmitted.
Compare with the ≈ 1 ms lag you would get with an analog
filter. As per the data sheet, the caveats are:

resolution reduced to 7 bits
the communication may not be reliable at this fast speed.

Update: The fastest may actually be PWM, if you “cheat” a little bit
with the analog filter. The Sabertooth datasheet recommends

PWM frequency = 1 kHz
filter with 10 kΩ + 0.1 µF.

This gives a time constant RC = 1 ms, which is one PWM period.
You can then expect a worst case ripple of 1.22 V peak-to-peak.
The datasheet says you can increase the frequency or the capacitance
beyond those minimum recommended values. In both cases you would get
less ripple. But if we assume that this level of ripple is acceptable,
we can make things faster by decreasing both the PWM period and the
filter's time constant.
The trick is to configure the PWM output to run as fast as possible. The
outputs of the Uno can run as fast as 62.5 kHz at 8-bit resolution,
but for this we have to configure a timer using low-level port access,
instead of relying on the analogWrite() Arduino function. I would
rather avoid messing with Timer 0, because that would break all the
Arduino timing functions (millis(), micros(), delay() and
delayMicroseconds()). Here is an example program that uses Timer 2 to
output two PWM waveforms at 62.5 kHz on outputs 11 (aka OC2A) and 3
(aka OC2B):
void setup() {
    DDRB  |= _BV(PB3);    // OC2A = PB3 = Arduino 11 as output
    DDRD  |= _BV(PD3);    // OC2B = PD3 = Arduino  3 as output
    OCR2A  = 127;         // output A starts at 2.5 V
    OCR2B  = 127;         // same for output B
    TCCR2A = _BV(COM2A1)  // output A in non-inverting mode
           | _BV(COM2B1)  // same for B
           | _BV(WGM21)   // fast PWM
           | _BV(WGM20);  // ditto
    TCCR2B = _BV(CS20);   // clock with no prescaling
}

void loop() {
    // Full forward both motors.
    OCR2A  = 255;
    OCR2B  = 255;
    delay (1000);

    // Stop.
    OCR2A  = 127;
    OCR2B  = 127;
    delay (1000);
}

You could then smooth these outputs with an RC filter of
2.2 kΩ and 10 nF. That would give a time constant of
22 µs, longer than the PWM period which is 16 µs, and a
worst-case ripple of 0.9 V peak-to-peak.

Both are (relatively) slow.  When speed is of the essence, use
port manipulation. This can execute a pin change as fast as a single clock cycle--faster than any library.

pwm is faster.
PWM is directly to the port. Serial goers to a buffer is send char by char and the receiver needs to wait for all the data to arrive.


text:
Arduino how to get amount of elements in an array?
Hello  have an array of strings that loads strings from a txt file on an sd card.
The txt file on the SD card can change from time to time(not while the Arduino is running).I want to be able to get the amount of elements in the array after the txt file has been loaded into the array. The txt file has lines of txt in it. Each line in the file is put into a string in the array. I want to be able to get the amount of elements in the array how can I do this?

This is your third post on basically the same subject. If I attempt to "read-between-the-lines" you are trying to implement a simple shell. You need to rethink how command lines are entered. It is not a very good idea to read the whole file into a vector of strings. Even worse is using the String class. Cheers!

You can't. That concept does not exist in C.
An array has a fixed size - as such you know how many elements are in it, since that is the number of elements you created it with.
String myStrings[4];

That is an array of 4 String objects. It has 4 elements. It will always have 4 elements.

so could I set the array size to say 400 and only load 100  lines of text?

If you have the memory to store that kind of thing.

numElements = (sizeof(array) / sizeof(array[0]));

This is not working for String array.


text:
How to have arduinos work together?
I want to have an Arduino based game you can play on a nokia 5110 screen. The problem is you cant make a medium sized game on an Arduino because the flash size is only 32k. I sit possible to have multiple Arduino's connected to each other, communicating to make it possible to have a bigger game. If it is possible how does it work?

You could store things like bitmaps, and level data in an external EEPROM.

You can. Probably the easiest solution is so make them communicate through serial connection. Or SPI. Just divide the visualization part (so all the bitmaps and the screen driver) and the input/game logic part and make them communicate. Or, if you can, follow @Gerben 's advice and use an external EEPROM for the big amount of data (even if screen libraries are quite big sometimes).

You can make quite an impressive game.

Features

Based on ATmega328P running at 16 Mhz (same as Arduino Uno).
The game has a display resolution of 104x80 with 256 colors.
Video mode is tile based and supports up to 3 sprites per scan line.
Sprites are multiplexed so there can be unlimited number of sprites vertically on the screen.
4 audio channels with triangle, pulse, sawtooth and noise waveforms.
Chiptune music playroutine and sound effects.
NES controller support.

Video of it in action:
https://www.youtube.com/watch?v=sLvgW_zb6bQ
Original post on the Arduino forum.

So, before you start wanting to connect lots of Arduinos together, investigate what can be achieved with just one. :)
The first thing to do, as others have mentioned, is to store static information into PROGMEM (see Putting constant data into program memory (PROGMEM) for more details).
If Petri Häkkinen can get his title screen, levels, sprites, music, and game logic into an Atmega328P you can too! Have fun!

Yes and no.
Yes you can make Arduinos communicate with each other and send messages to each other.
Can you use that to make a game?  Possibly.
Is it worth the effort?  No.
It would be a huge amount of work and be overly complex when you could just use a bigger Arduino, like a Mega2560 or a Due.

You can have two Arduinos communicate with each other but it is fairly complex.  See this instructable.  One process is using the I2C protocol.
A far easier option is to use a larger Arduino model.  Consider the Mega 2560 since it has 8 times the Flash memory.

Instead of I2C use serial. Much faster and more lightweight.


text:
Can you send binary data to arduino AtMega328p?
I was wondering if its possible to send binary data to an Atmega328p. I don't want to send Arduino code or C code just binary. Is it possible to programme the ATmega328p using binary and how?

You can send a pre-compiled binary yes.
But are you sure you don't mean assembly or HEX?
It would be a shame to only use the 0 & 1 of your keyboard for programming.
And why would you like to achieve this?

Voting to close as it is entirely unclear what the goal here is.  Binary communication is of course possible, but what does it mean to "programme" ?   To author something?  To load the flash??  To communicate with a bootloader, and if so which one???

The serial port is binary data.
Because we humans can read text data easier than binary data we mostly send text. This way we only use a very small amount of the possible band with.
The serial monitor translates your input to binary and the binary input of the arduino to text. If you write a program that uses the serialport directly you can communicate in binary without a prolem.

You should rephrase your answer. specifically everything after the 1st sentence. Bytes sent via the serial port are implicitly binary; the interpretation on the receiver's end is a different thing entirely and has nothing to do with bandwidth. The serial monitor displays the ASCII character equivalent to each byte received if it can, else you see gibberish for bytes that don't fall within the printable range, barring a few. Also, I dont think the OP is talking about serial communication but rather how code is burned into the ATmega chip over USB.

When you upload your sketch using the IDE, it has been converted from C++ into "binary". So yes, it is possible. In fact that is the only way it is done.

I don't want to send Arduino code or C code just binary.

The job of the compiler is to convert your C code into binary, and that happens automatically.
You an also use avrdude to upload a xxx.hex file (a file containing pure machine code).


text:
Arduino substring not working
Hello  I have an Arduino programme where a string is loaded from an SD card. That all works fine. I want to see if the string that has been loaded contains a certain phrase. I am using substring but it doesn't seem to be working. What am I doing wrong? Here's my code:
file = SD.open("/classes/basic.txt", FILE_READ);
 Serial.print("Reading, Checking and Compiling \n");
  while(file.available()) {
   character23 = file.read();
   content.concat(character23);
  }
if (content != "") {
  l1 = content;
  Serial.println(l1 + "\n");
}

if(l1.substring(0) == "print"){
  printlnMethod();
}
file.close();

it all works until it gets to l1.substring and that doesn't work because the method inside doesn't run. The string that gets loaded into the Arduino from the SD card is : println("hello world");
What am I doing wrong?

Substring takes either one or two arguments.
In the single-argument version that you are using the argument specifies the start of the substring. The substring then contines to the end of the string.  So, since you are asking it to start at index 0 the returned value is the entire string - from 0 to the end.
Instead you probably want to use the two-argument version. In that version you provide two numbers - the index in the string to start from, and the index in the string after the last character you want.  So if the string starts with "print" you then want to use l1.substring(0, 5) to get the characters 0 to 4 inclusive.

I already tried that and it didn't work

Try printing what substring returns so you can see what it's really doing. Your string might not be exactly what you think it is.

I'm not sure how to return a substring

Serial.println(l1.substring(0,5));