text:
Arduino original motor shield can not supply enough torque to the motor?
I am using original Arduino motor shield L298P with Arduino uno.
I disassembled an electric screw driver which came out with a 4.8 v battery pack and a 4.8v specified DC motor.
I connected battery pack to the Vin and Ground pins of the motor shield, and connected the DC motor to A channel of the shield.
The thing is when I run a test code with PWM 255, the torque of the motor is way too low compared to connecting the motor directly to the battery pack. I also changed the batteries to a common 1.2v rechargeable 4 batteries connected in parallel. The result is the same.
What might be going wrong?
I also paste the code I am using below. Thanks in advance.
const int motorPin = 3;
int Speed;
int flag;
void setup()
{
pinMode(motorPin, OUTPUT); //Set pin 3 as an OUTPUT
Serial.begin(9600); //Init serial communication
//Print a message:
Serial.println("Give a number from 50 to 255."); //Why minimun value 50?     Because with values below 50 the motor doesn't spin ;)
Serial.println(""); //Blank line
}

void loop()
{
//Check if incoming data is available:
if (Serial.available() > 0)
{
  // If it is, we'll use parseInt() to pull out only numbers:
  Speed = Serial.parseInt();
  flag=0;
}

//Valid range is from 50 to 255
if (Speed>=50 && Speed<=255){
    //Send PWM value with analogWrite to Arduino pin 3 and print a message to serial monitor
    analogWrite(motorPin, Speed);
    //Print message only once
    if (flag==0){
        //Print PWM value
        Serial.print("Motor spinning with ");
        Serial.print(Speed);
        Serial.println(" PWM");
        flag=1;
    }
}

delay(1000);
}

This is not at all surprising - screwdrivers made to run off of low voltages have to draw very high currents under load.  A L298 has both limited current handling, and uses bipolar transistors which when you count both elements active in a bridge add up to a substantial voltage drop inside the chip.  You can try adding a 5th cell but the current limit remains.  If you don't need reversing you can consider a single logic-level NFET with good performance.  If you do need reversing, you can "pick any two" of performance, simplicity, or low cost.

According to the motor shield page:

To avoid possible damage to the Arduino board on which the shield is mounted, we reccomend using an external power supply that provides a voltage between 7 and 12V. If your motor require more than 9V we recommend that you separate the power lines of the shield and the Arduino board on which the shield is mounted. This is possible by cutting the "Vin Connect" jumper placed on the back side of the shield. The absolute limit for the Vin at the screw terminals is 18V.

According to you:

I disassembled an electric screw driver which came out with a 4.8 v battery pack and a 4.8v specified DC motor.
I connected battery pack to the Vin and Ground pins of the motor shield, and connected the DC motor to A channel of the shield.

That's a lot less than 7V.

Also, from the motor shield page:

Max current   2A per channel or 4A max (with external power supply)

How much current does your screwdriver use?

From the Arduino playground:
Arduino: What Adapter?
by djmatic
Ever since the dawn of Arduino, one question has been asked over and over again: "what kind of DC adapter can I use to power my Arduino?"
The short answer is: 9 to 12V DC, 250mA or more, 2.1mm plug, centre pin positive.
The long answer is that an off-the shelf Arduino adapter:
must be a DC adapter (i.e. it has to put out DC, not AC);
should be between 9V and 12V DC (see note below);
must be rated for a minimum of 250mA current output, although you will likely want something more like 500mA or 1A output, as it gives you the current necessary to power a servo or twenty LEDs if you want to.
must have a 2.1mm power plug on the Arduino end, and
the plug must be "centre positive", that is, the middle pin of the plug has to be the + connection.
These important details are often contained right on the adapter.
Current rating: Since you'll probably be connecting other things to the Arduino (LEDs, LCDs, servos) you should get an adapter that can supply at least 500mA, or even 1000 mA (1 ampère). That way you can be sure you have enough juice to make each component of the circuit function reliably.
One final note. The Arduino's on-board regulator can actually handle up to 20V or more, so you can actually use an adapter that puts out 20V DC. The reasons you don't want to do that are twofold: you'll lose most of that voltage in heat, which is terribly inefficient. Secondly, the nice 9V pin on the Arduino board will actually be putting out 20V or so, which could lead to potential disaster when you connect something expensive to what you thought was the 9V pin. Our advice is to stick with the 9V or 12V DC adapter.
Electronicalifragilistic: I use a power supply from an old HP laptop that I scrapped. The plug is center positive and puts out 12V. Fits perfectly into Arduino connector. Packs a Wallop - most laptops draw 2-2.5 amps. That ought to run your screwdriver.

Don't just copy text from somewhere else, especially when the recommendations it makes are unsuited to the question at hand.  The actual issues here have been explained already, and many times previously both here and at EESE.


text:
CC3000 gets wrong address when connecting to wireless AP
I tried using both the SparkFun and Adafruit CC3000 libraries first with what I actually wanted as a program, but when that didn't work, the examples for those libraries, and I always seem to get the same problem.
The CC3000 will connect to my AP, which uses a private address in the range 172.24.1.1/24, and somehow it will end up with the address 192.168.1.64.
I know that it is connecting, since iw event lists the device MAC address as it connects.
The only changes I have made to the source code at this point are the ssid and password, and changing the interrupt and vbat pins to match the configuration of the tinyduino cc3000 board.
The device has firmware 1.34. Here is the code.
The specific output I get from the arduino is as follows (Note I commented out the disconnect at the bottom):
Connected at 115200

---------------------------------
SparkFun CC3000 - Connection Test
---------------------------------
CC3000 initialization complete
Connecting to: my_wifi_ap
Connected!

CC3000 MAC Address: 70:FF:76:04:B9:5B
IP Address: 192.168.1.62
Subnet Mask: 255.255.255.0
Default Gateway: 192.168.1.254
DHCP Server: 0.0.0.0
DNS Server: 192.168.1.254
SSID: my_wifi_ap

Finished connection test

running iw event -f on my AP before running a connection test gives me the following output:
wlan0: new station 70:ff:76:04:b9:5b

When another device, like my phone, connects to this AP, we get 172.24.1.xx, where xx is whatever number between 50 and 150 that DHCP assigns us.
Edit:
Also, if I comment out the disconnect at the end of the test, I can see the device is sending keepalives every three or four seconds using:
iw dev wlan0 station get 70:ff:76:04:b9:5b  //(inactive time never exceeds 4000ms).

I can't ping 192.168.1.64 because that network is obviously unreachable, but trying to ping 172.24.1.64 gives me a exception:
icmp open socket: Operation not permitted

Output from Adafruit Example:
RX Buffer : 131 bytes
TX Buffer : 131 bytes
Free RAM: 1221

Initialising the CC3000 ...
Firmware V. : 1.32
MAC Address : 0x70 0xFF 0x76 0x04 0xB9 0x5B
Started AP/SSID scan

Networks found: 20
================================================

...

SSID Name    : my_wifi_ap
RSSI         : 83
Security Mode: 3

SSID Name    : my_other_wifi_ap
RSSI         : 67
Security Mode: 3

...

================================================

Deleting old connection profiles

Attempting to connect to my_wifi_ap
Started AP/SSID scan

Connecting to my_wifi_ap...Waiting to connect...Connected!
Request DHCP

IP Addr: 192.168.1.62
Netmask: 255.255.255.0
Gateway: 192.168.1.254

The actual device being connected to is a Raspberry Pi AP, which was set up with DNSMASQ and hostapd. The configuration works, and has been proven to work with other embedded networking devices.

What device is your AP? Can you query it for the IP address of the new station? Can you post the output from the Adafruit example?

I'm voting to close this question as off-topic because it is about CC3000 firmware versions and not about Arduino.  Additionally the poster has long abandoned the question without accepting even their own apparent solution and and has not logged in for over a year, meaning that this off-topic question is likely to remain permanently derelict.

I realized that I was using firmware v 1.34 on the board, which is what it was configured with when I got it, and decided I would try to downgrade it to one of the fir;ware sets supplied by adafruit to see if that would work.
The firmware modifying program didn't actually compile on the desktop version of the arduino ide, so I decided to use codebender instead.
I'm not sure whether or not I should be disappointed or relieved, but downgrading the firmware actually made it work. I used the file titled driverpath_1_11, which I believe the libraries refer to as firmware version 0x113 or 0x118, which identifies itself as firmware version 1.24, which somehow actually worked.
The solution is here: https://codebender.cc/sketch:318229
The pins have been changed to correspond with the fixed pings used by the tinyduino.

Please accept either your answer or the other so that the question shows as resolved and does not keep getting churned up for attention.

Welcome to the wonderful world of Adafruit software. Some genius decided that the CC3000 should save the first address it is ever given to nonvolatile storage, and use that ever since no matter what DHCP may subsequently tell it. Check the library source.

I solved it by downgrading the firmware to one that was suggested for use with the adafruit library, but that actually seems like an equally plausible reason as to why it wasn't working. Not sure why the Sparkfun library also failed to work, too, but that one is pretty clearly a WIP.

source: Stack Exchange

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

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

sort: votes


text:
Arduino Nano (clone) not recognized
Asking here cause I ran out of options in searching. My Arduino Nano clone isn't recognized by my computer anymore. It was, until I plugged into a Windows machine, that did not recognize it... and now even my Linux Mint distro doesn't detect the Nano at all. Here's the thing, though: the green power LED still lights up and, if I connect my DC motor to it like I used to before, the LED turns off and the motor is powered only a little bit, with less speed than if it were powered by a 1.5V battery.
My voltimeter reads a 2.18V out of the 5V pin.
Here's all I did: uploaded a sketch to power a 5v motor, it worked, unplugged the Arduino, took it home to my Windows machine on the casing I got it from my school, plugged it there, then it didn't detect anything. Go back to the lab today, plug it in, doesn't detect it there either.
From there, I've replaced USB cables, tried different USB ports, checked with lsusb and dmesg, tried finding it using the FTDI tool (the chip underneath is FTDI), then tried powering it from a phone charger, but the voltage readings at the 5v pin still are around 2.18V with that. Nothing seems to give this little thing an output greater than 2.18V.
The only thing I haven't tested is powering it through the VIN pin.
I came across other questions of similar problems but nothing that seems quite like mine... since they all either are able to detect the device but it is displayed as an unknown device or can't recognize the device at all but their power LED does not turn on.
Any ideas on what is going on?

When powered by a USB port, the 5v should be coming fairly directly from the USB, possibly via a diode.  So that suggest a problem with the diode, failure of the connector or PCB or its solder, or an overload (perhaps from a damaged chip) causing the USB VBus itself to sag, or an issue with the measurement itself.

How is/was you motor wired up?

This is why you should not power motors from an Arduino's power supply, regulator, or even simply power nets.

Just talking.. Have your flywheel diode been there? Meaning across the Motors terminals?
Because if not that might have broke something.

It sounds like a blown protection diode MBR0520 in between USB and +5V of the nano.

This answer pointed me towards a ton of other people experiencing the same problem (usually after accidentally shorting the 5V and ground pins) and this is exactly what it turned out to be for me as well. It seems to be commonplace with clones. Replacing the diode in question (which protects the USB port in the event of an external power supply also being connected) fixed the problems for me.

Apart from 5V pin, the rest sounds like your FTDI clone chip might be bricked. Check your device VID (under Device Manager -> Device Properties -> Details tab -> under Property select Hardware Ids). If VID and/or PID is 0000 than it is.
It is possible restore the original VID/PID (thus recover the Arduino). Google for "Fix bricked FTDI", there are many instructions like this: http://internetofhomethings.com/homethings/?p=987
Most of these cheap Arduino Nano clones have also fake FTDI IC and at some point FTDI (the vendor) released new driver which bricks such clones by setting VID/PID of the chip to 0. This effectively makes the IC undetectable / incompatible with original FTDI drivers. That is why it is not recognized on a PC where it was working earlier.
http://hackaday.com/2016/02/01/ftdi-drivers-break-fake-chips-again/
After recovery, make sure to use older FTDI driver.

What was your schema? did you try to control 5V motor from arduino directly.
Now assuming that
$ lsusb

doesn't show something like:
Bus 002 Device 005: ID 1a86:7523 QinHeng Electronics HL-340 USB-Serial adapter

It is generaly a bad idea to control any mechanical (magnetic) device without using transistor and maybe a diode to protect against current in an opposite direction
standard DC motors can generate quite a nice voltage if turned mechanically (during transport) or even current increase if motor is blocked when powered.
TO me it sounds like you have burned your chip. USB on most computers has got an over-current protection resulting in lover voltage if something you connect has very low resistance.
2.8volt is more then enough to lit-up green LED on a damage MCU, but probably not to power the FTDI chip wired for 5V

Standards compliant USB ports will only supply 100mA unless a higher current is negotiated by USB.
I suspect that you problem is the USB serial (Chinese Nano clones often have cheap chips). This happened to one of my Nano clones.

I'll go to the maintenance lab tomorrow at my school, and see what they tell me. It's rather strange, since this is the second Nano that has some problem on my end.

It may be caused by the cable. In my case it was. Not all cables have data wires.

The OP indicated that it worked before so... how should the cable change (except mechanical cutting/breaking which would probbly affect other lines too)

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

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


text:
I just bought a TFT screen is it still possible to use the serial port 1 and 0?
so I have a question regarding the TFT touch screen... I would like to use the serial ports 1 and 0 (on my UNO) to transmit data to my mega... however it take up those ports. on the back of it, it shows what each prong should occupy. However, nothing is noted to be required for those ports. is it possible to clip those prongs off and still have the screen be usable or are they important to keep?

Please edit your question, and specify the brand and model of TFT touch screen you have, when you edit the question.

Yes, need more information for any kind of definitive answer..  What kind of Touch Screen and what kind of Arduino?

Yes, you can use those pins. Just because there are physical pins on the shield doesn't mean they are actually used. If nothing is written next to them then yes you can use them.
Be warned though that those pins are used for communication with your PC - and that includes uploading sketches - so you may experience problems doing things like that while your Mega is connected to those pins.


text:
LED Pin 13 Input or Output?
It is not clear to me whether Pin 13, corresponding to the LED, should be driven by an external voltage or not.
From the documentation,

LED: 13. There is a built-in LED driven by digital pin 13. When the
  pin is HIGH value, the LED is on, when the pin is LOW, it's off.

However, in the "Blink" example code I am running, the Pin 13 appears to be driven by the ATmega328:
void setup() {
  // initialize digital pin 13 as an output.
  pinMode(13, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(100);              // wait for a second
  digitalWrite(13, LOW);    // turn the LED off by making the voltage LOW
  delay(2000);              // wait for a second
}

If I now attach a voltage source to Pin 13, will there be contention issues?

Like any other I/O pin, there should be no problem driving this pin (and
thus the builtin LED) from an external source, as long as you make sure
it is in INPUT mode. If the pin is set to OUTPUT you will likely
damage the Arduino.
Warning: If you have the Blink example already loaded in the
Arduino, the pin is in output mode. Be sure to upload another program,
that does not set pin 13 to output, before connecting anything that
could drive pin 13.

It would be good defensive - and documentary - practice to explicitly set it to INPUT during setup() rather than depending on the default.


text:
Which (Official) Arduino IDE to use?
I have bought an Arduino UNO that turned out to be the Italian version (Arduino SRL) not the American one (Arduino LLC).
Now when I go to arduino.org and arduino.cc, they both have different versions of the IDE!
So, which one should I use (if they are even different) ?

Neither. Use UECIDE ;)

Seriously though, the real answer is "It depends which side of the argument between the two Arduino parties you are on". Personally I am on the side of the .CC camp, so I would recommend to use the .CC version. Someone on the side of .ORG would recommend the .ORG version to use.

Possibly unnecessary warning: if you are expecting to have a coding experience similar to other IDEs, you might be surprised that there are "magic" includes rules and what would normally work in a typical GNU-like project might not work. This is meant to simplify the life to beginners, but not everyone likes it. The alternative is to use a plain Makefile and your favorite means to deal with Makefile - based projects.

.CC are open and welcoming. .ORG are sneaky and underhanded. For instance they create the same IDE but with a higher version number, so it appears newer than the .CC version. They also include (or have attempted to include) code to stop you being able to use non-.ORG boards.

Personally I would use the Arduino.CC version. However I'm going to close this question as being primarily opinion-based. Sorry about that.

You can use both IDEs no matter of the origin of the UNO even fake ones runs with the IDEs.
The arduino.org IDE is just a fork of the arduino.cc.
But arduino.org has many Board which are only run with the .org IDE.


text:
Arduino IDE/Visual Micro - Undefined reference to constructor
I am using Visual Studio Community 2015 with the newest version of the Visual Micro Arduino Plugin, however I also tried compiling my code in the Arduino IDE.
When compiling my code, there is the following error:
Compiling debug version of 'Autonomous_Car' for 'Arduino/Genuino Uno'
Autonomous_Car.cpp.o:In function `setup
Autonomous_Car.ino:undefined reference to `List<UpdateAble>  List()
Autonomous_Car.ino:undefined reference to `List<UpdateAble>  ~List()
collect2.exe*:error: ld returned 1 exit status
Error creating .elf

Some info

Adding #include "List.cpp" fixes the error, however this does not seem like valid C++.
The files do not lay in any sub-directory
In my Project Explorer both List.h and List.cpp are added to the project.
I also removed both files from the project, deleted them and added them again
I deleted the ´%AppData%\Local\Arduino15´ directory
I am fairly new to C++ and Arduino, there might be something obvious, what I just can't find

Autonomous_Car.ino
#include "List.h"
#include "UpdateAble.h"

void setup()
{
    List<UpdateAble>* myList = new List<UpdateAble>();
    myList->GetCount();

    delete myList;
}

List.h
#ifndef _LIST_h
#define _LIST_h

#if defined(ARDUINO) && ARDUINO >= 100
#include "arduino.h"
#else
#include "WProgram.h"
#endif

template <class T>
class List {
public:
    void Add(T &item);
    bool Contains(T &item);
    bool Remove(T &item);
    void Clear();
    int IndexOf(T &item);
    T* GetItem(int index);

    inline int GetCount() { return count; };
    inline int GetCapacity() { return capacity; };

    List();
    ~List();
private:
    void EnsureCapacity(int capacity);

    int count;
    int capacity;
    T** items;
};

#endif

List.cpp
#include "List.h"

// Constructor
template <class T>
List<T>::List() {
    List::capacity = 4;
    List::count = 0;

    List::items = new T*[List::capacity];
}

// Cleanup
template <class T>
List<T>::~List() {
    delete[] List::items;
}

template <class T>
void List<T>::EnsureCapacity(int capacity) {
    if (List::capacity < capacity) {
        // Kapazität verdoppeln
        List::capacity = List::capacity * 2;

        // Speicher für neues array reservieren
        T** newArray = new T*[List::capacity];

        // Array kopieren
        for (unsigned int i = 0; i < List::count; i++) {
            newArray[i] = List::items[i];
        }

        // Speicher von alten array freigeben und neues array zuweisen
        delete[] List::items;
        List::items = newArray;
    }
}

// Adds a new item to the list
template <class T>
void List<T>::Add(T &item) {
    List::EnsureCapacity(count + 1);

    List::items[count] = item;
    List::count++;
}

// Gets whether the list contains an item or not
template <class T>
bool List<T>::Contains(T &item) {
    return List::IndexOf(item) != -1;
}

template <class T>
bool List<T>::Remove(T &item) {
    int index = List::IndexOf(item);

    // If the item does not exist, we cannot remove it
    if (index == -1) return false;

    // Move every item behind our item one further
    for (int i = index + 1; i < List::count; i++) {
        List::items[i - 1] = List::items[i];
    }

    List::count--;
}

// Release the heap
template <class T>
void List<T>::Clear() {
    for (int i = 0; i < List::count; i++) {
        delete List::items[i];
    }

    delete[] List::items;
}

// Gets an index of an item, -1 if not found
template <class T>
int List<T>::IndexOf(T &item) {
    for (int i = 0; i < List::count; i++) {
        if (List::items[i] == item) {
            return i;
        }
    }

    return -1;
}

template <class T>
T* List<T>::GetItem(int index) {
    if (index < List::count && index >= 0) {
        return List::items[index];
    }

    return 0;
}

I'd be very glad, if we can find the solution.

You're using a template class. A template class is a special corner case that breaks the "code in .cpp and definitions in .h files" rule.
Because it's a template it can't be pre-compiled - it needs to be specially compiled each time it is used, so that it can get the right values compiled in to the template place-holders, which are provided by the CU that has the template class included with it.
Because of that it is one of the rare cases where the code has to be in the header file.
For a full example you can take a look at my Average library which is a fully templated class.


text:
Two-wire communication (I2C) between Arduino Micros
I am attempting to communicate data via I2C between two Arduino Micros, but can't seem to get the "slave" device to detect a Wire.onRecieve() event.
Per the specification on this site [http://www.takktile.com/tutorial:arduino] (and verified against Arduino's own site) I am using pins 2 and 3 as SDA and SCL for I2C. I have pin2 of Arduino 1 (ARD1) connected to pin2 of Arduino 2 (ARD2), and pin3 of ARD1 connected to pin3 of ARD2.
ARD2 acts as slave, ARD1 acts as master.
I am reading in a text file from SD on ARD1. On ARD1, you then press a button to initiate transfer. ARD1 lights a red LED to indicate the transfer is underway. When I initiate the transfer, it remains solid (indicating it never gets past endTransmission to where the LED is supposed to be turned off).
Here is the code for ARD1:
// include the SD library:
#include <Wire.h>
#include <SPI.h>
#include <SD.h>
// personal debugging routines
#include "debug.h"
/*
 *
 *  THIS IS THE SLAVE RECEIVING MODULE
 *  IT WILL WRITE DATA TO AN SD CARD
 */

// GLOBAL VARIABLES
const int chipSelect = 10; // 10 because this is an Adafruit SD module.
File data;
int buttonA; // the button
char c;

void sd_readstart() {
  unsigned char i = 0;
  // Open serial communications and wait for port to open:
  Serial.print("\nInitializing SD card...");
  if (!SD.begin(10)) {
    Serial.println("Card initialization failed.");
    errorblink();
    return;
  }
  Serial.println("Initialization successful.");

}

void setup() {
  pinMode(11, OUTPUT); // setup for blink
  pinMode(12, OUTPUT); // setup for blink
  pinMode(10, INPUT); // button
  Wire.begin(8); // intitalize this device as a slave on addr .
  Wire.onReceive(receiveEvent); // when data is recieved, run recieveEvent(int).
  Serial.begin(9600);
  sd_readstart();
}

void loop(void) {
  // short blink to confirm this is going down correctly
  buttonA = digitalRead(10);
  if (buttonA == HIGH) {
    // button open
    blink(100,1000);
  } else {
    // button pressed

  }

}

void receiveEvent(int howMany) {
  data = SD.open("testoutput.txt");
  digitalWrite(12,HIGH);
  while (Wire.available() > 0) { // loop through all but the last
    c = Wire.read(); // receive byte as a character
    Serial.print(c);         // print the character
    data.print(c);
  }
  data.close();
  digitalWrite(12,LOW);
}

Here is the code for ARD2:
// include the SD library:
#include <Wire.h>
#include <SPI.h>
#include <SD.h>
// Software Serial library:
#include <SoftwareSerial.h>
// personal debugging routines
#include "debug.h"
/*
 *
 *  THIS IS THE SLAVE RECEIVING MODULE
 *  IT WILL WRITE DATA TO AN SD CARD
 */

// GLOBAL VARIABLES
const int chipSelect = 10; // 10 because this is an Adafruit SD module.
File data;
int buttonA; // the button
char c;

void sd_readstart() {
  unsigned char i = 0;
  // Open serial communications and wait for port to open:
  Serial.print("\nInitializing SD card...");
  if (!SD.begin(10)) {
    Serial.println("Card initialization failed.");
    errorblink();
    return;
  }
  Serial.println("Initialization successful.");

}

void setup() {
  pinMode(11, OUTPUT); // setup for blink
  pinMode(12, OUTPUT); // setup for blink
  pinMode(10, INPUT); // button
  Wire.begin(8); // intitalize this device as a slave on addr 8.
  Wire.onReceive(receiveEvent); // when data is recieved, run recieveEvent(int).
  Serial.begin(9600);
  sd_readstart();
}

void loop(void) {
  // short blink to confirm this is going down correctly
  buttonA = digitalRead(10);
  if (buttonA == HIGH) {
    // button open
    blink(100,1000);
  } else {
    // button pressed

  }

}

void receiveEvent(int howMany) {
  data = SD.open("testoutput.txt");
  digitalWrite(12,HIGH);
  while (Wire.available() > 0) { // loop through all but the last
    c = Wire.read(); // receive byte as a character
    Serial.print(c);         // print the character
    data.print(c);
  }
  data.close();
  digitalWrite(12,LOW);
}

For completeness, here is my debug.h:
void blink(int h, int l) {
    digitalWrite(11, HIGH);
    delay(h);
    digitalWrite(11, LOW);
    delay(l);
}

void errorblink() {
  unsigned char counter = 0;
  while (counter < 4 ) {
    digitalWrite(12, HIGH);
    delay(50);
    digitalWrite(12, LOW);
    delay(50);
    digitalWrite(12, HIGH);
    delay(50);
    digitalWrite(12, LOW);
    delay(50);
    digitalWrite(12, HIGH);
    delay(50);
    digitalWrite(12, LOW);
    delay(1000);
    counter++;
  }
}

void goodblink() {
  unsigned char counter = 0;
  while (counter < 4 ) {
    digitalWrite(11, HIGH);
    delay(50);
    digitalWrite(11, LOW);
    delay(50);
    digitalWrite(11, HIGH);
    delay(50);
    digitalWrite(11, LOW);
    delay(50);
    digitalWrite(11, HIGH);
    delay(50);
    digitalWrite(11, LOW);
    delay(1000);
    counter++;
  }
}

I did attempt to do the minimum working example of Wire from the examples in the Arduino IDE. That didn't work either, which is to say that I didn't see any text in the serial monitor on ARD2 when I uploaded the slave reciever sketch that comes with the IDE (with send master running on ARD1) which makes me wonder if I'm doing something horribly, fundamentally wrong in hardware rather than just in software.
I hope it's not inappropriate to post up the more advanced example in order to get feedback on the larger picture of what I'm trying to accomplish -- moving a text file from the SD card on one arduino to the SD card attached to another.

You don't mention having the external explicit pullup resistors required for I2C.

Indeed I didn't. That may be the horrible, fundamental thing I overlooked. Can you elaborate?

I2c is an open collector setup. The pins go low, or open/input/hi-z, and let the line/bus free. Without a pull up on each line to VCC, the line never goes high. Pull up resistors are required. 4.7k typical.
Op's crudely drawn diagram is the correct way for a 5V I2C bus:

Keep in mind both arduinos/power supplies must have their grounds connected, as a reference ground voltage.

Am I correct in imagining something akin to the crude schematic I drew here:
http://imgur.com/qhO2W4y

@BradleyEvans yup. See https://learn.sparkfun.com/tutorials/i2c

Thanks. This was, indeed, my problem.
With respect to the larger problem, is my intuition correct that the data transferred cannot be very large? I was trying to push a multiparagraph text file through.

@BradleyEvans You can transfer as much data as you want, if you are willing to wait long enough …

@bradleyevans you do it 8 bits at a time, as fast as the library allows you too. Standard i2c is 100 kHz to 400 kHz so that pretty snappy compared to human speed,  but SPI or fat i2c or serial/uart can be faster.

For clarification, what I was wondering after was how the Wire library works in Arduino.
Wire.beginTransmission() starts a transmission.
Wire.write() starts putting bytes together for transmission
Wire.endTransmission() actually tosses the transmission out over the wire.
I was trying to fit a full text file in between begin and end, which was too much for my Arduino Micro's memory. Breaking it up into 10 byte chunks and running it while(data.available()) let me transfer the whole thing.

The I2C protocol and hardware don't care how much data is transferred.
The time you have for the transfer, or the transfer rate is much more important; you might get bored waiting, but it won't.
You might get over 100k bits/second transfer (allowing time to write to the SD card) if that's enough then it's fine.
The significantly faster option, using Arduino's, is SPI to SPI, and you are likely using SPI for the SD card, so I2C is a reasonable alternative, and makes your hardware and software simpler.
The only faster interface on the Arduino, excluding SPI, is the UART. That might be a bit tricky to use while you are developing, testing and debugging your software.

I had initially started with UART but it proved a tad too complex for the short time I have with this project. Thanks for the background.

authors: Женя Сиротенко


text:
Using the Logging library, sometimes doesn't exit setup()
This has been a hard problem to diagnose, so I hope I'm giving enough info here.  I'm trying to write a program for the Arduino (a lighting controller) using a bit of OO.  There are several classes in my library, and some extend others.  I'm a long-time programmer (mostly Java) but this is my first big Arduino project.
I'm using the Logging library at various points in the main program, as well as the objects, and that's where it get complicated.  Depending on where I put calls to the logging library, or even Serial.print(), it either all works, or what gets sent to the serial port is a bit garbled, and the board never enters loop() (I'm not sure if that means that it's crashing in setup() or not).  This library hasn't been touched in 4 years and there are pending merge requests, so I don't think I'll get answers from the developer.
I have a sneaking suspicion that the root of the problem is that Logging.h ends with instantiating the logger ("Logging Log = Logging();") so multiple instances of the logger may be created and the serial port is being reset several times, possibly at different port speeds.  I thought it was bad form to initialize object, or even have any running code, in a .h file.  Is this a possibility, and do I have any options to fix this?
Are there any good alternatives for printing outputs at different debug levels?
I would hate to have to pass the logger instance in as a parameter to my classes, or have to write setLogger() methods for all my classes.
Thanks.

Logging.h ends with instantiating the logger ("Logging Log = Logging();") so multiple instances of the logger may be created and the serial port is being reset several times, possibly at different port speeds.

I think you are mistaken, or have done something wrong with the library files.  Logging.cpp ends with the instantiation, not Logging.h.  Logging.h only has an extern reference to the instantiated object.
So some guesswork:
If you try and do anything with logging or serial access (or indeed anything more than just setting a few variables) within the constructors of your objects, and you instantiate those in the global scope, you won't have full access to the serial port - if any access at all.  You can only use the serial port once Serial.begin(...) has been executed in setup, and global constructors are executed before setup() is run.
It is for this precise reason that 99% of Arduino libraries have a .begin() method which does all the work a constructor would normally do. The constructor is only used (if at all) for storing some default settings (pin numbers, etc) that are used later on. That way you have full control over what gets executed and when.

Yup, I see that extern is used in Logging.h.  My bad, thanks.  I DO have a constructor that calls a setter method on another class, and I have a Log line in the setter method of that second class.  Maybe that's the problem.  Not sure how to get around that, since I do want debugging.  Maybe the answer is to create a .begin() method that does the same thing without the debugging.   Thanks again @Majenko

The constructor (called in a rather weird way) doesn't do anything, so I don't think that is the issue.
Logging.h:
    /*!
     * default Constructor
     */
    Logging(){} ;

Logging.cpp:
 Logging Log = Logging();

You should be calling Log.init(whatever) once in your code (as in the example). Are you doing that?
Please post a Minimal, Complete, and Verifiable example.
Without any posted code, we can only guess at what you are doing.

I thought it was bad form to initialize object, or even have any running code, in a .h file. Is this a possibility, and do I have any options to fix this?

That is not done in the library you linked to.

Any logging libraries that you recommend @nick-gammon? Asking because this one hasn't been updated in ~5 years. (looking for debug/info etc levels of logging to serial output)

Well, I did a bit of work on debugging using a second Arduino using SPI or I2C. That (fairly quickly) lets you output debug messages via another processor, which has minimal impact on the board under test (it depends a bit on whether you have I2C or SPI free). You could modify the function calls to take a log level conceivably. You might want to post this as a new question to get comments and suggestions from others.


text:
80 Apple Homebuttons and a steppermotor
I am graduating in a month and I want to make an installation with 80 apple homebuttons which are connected to a stepper motor. The idea is that each button that is pressed, turns the stepper motor the same amount of degrees each time. Also, each button is connected to an LED which must stay on, even if the button is pressed again and the motor too must not react. Once all 80 buttons have been pressed, the installation should switch off after a minute or so.
I am not sure how to connect 80 inputs to the arduino. Does anyone have any idea?

Start small and figure out exactly what your program should do.  Most keyboards (and comparable devices) with more than a few keys use matrix scanning, which need not match their physical layout.

Why on earth would you use an Apple homebutton? That'll become unnecessary expensive. All the LED's should be controlled at the same time? Or should it be possible to control them individually?

There are input shift registers, however I have no idea what an "apple homebutton" is. I'm going to close this question. Feel free to edit it with new information. Thanks for your understanding and cooperation!

Why Apple home buttons?
Finding out how to get input/output from these things and wiring them in a reliable way may cost you some time (and quite some money).
I don't see how they would have other features than regular buttons.
(You won't get the fingerprint-scanning thing working, I'm afraid.)
Start small
It'll be quite a project to do in one month (especially when you're new to Arduino).
If you start out with 80 buttons and stuff, it will probably end up in a mess, and you'll be unable to show your prof anything.
You should however, order the 80 push-buttons (I shouldn't order the Apple ones, if you don't already know how they work) and LED's. Since they might take some shipping time.
Get yourself a solder-less breadboard, maybe 3 buttons, some LED's and a stepper (if you don't have one already).
Depending on your type of stepper, you may need something to drive it.
Start project
Use two buttons or so, if you press one, it would go clockwise, if you press the other, it would go counter clockwise.
Make sure you pull up or down the button inputs, to be sure that they are not floating when the button is not pressed.
Find a way to drive the steppers, you'll most likely use Arduino libraries for this.
Code will be something like:
if(digitalRead(button1))
  stepper.step(steps++);
if(digitalRead(button2))
  stepper.step(steps--);

Scaling up - alternative
You could use the 80 buttons for each angle of the stepper.
But you could also use a keypad and LCD (or 3x 7segment display) to display a value typed in, and then send it to the motor.
Scaling up
In the case of the 80 buttons.
You could use 10 outputs in combination with 8 inputs.
With each output, you can energize a row of buttons, and with each input you read the columns. This way you only need 18 pins to read all keys.
I'm not sure if you want to control all LED's at the same time, or individually.
Or use shift registers or I/O expanders (JayEye).

Hi Paul. I will only be using the glass top of the buttons! These have a plate which you can click on top of an Arduino button. I am not using the iPhone 6 buttons with the Touch Id, but just want them for aesthetic reasons. Thanks so much for the advice!

Ah, good, I guess, as long as it's not making your project too expensive or too difficult ;) but I think you'll manage that. Do you still have any questions/doubts?

You see I wasn't sure whether a Raspberry Pi or an Arduino would be the best option. Now I guess my best option is to go with the Rasperry. I wanted to know where to start and then I can always find ways to get where I want to be, but as you say yourself - I don't want it to become expensive, so I need all the help I can get. I will definitely be back with further questions once I have the right equipment. Thanks so much!

Paul, jij zit gewoon op de HAN! Ik op ArtEZ

@MissySkae (Klopt ;) )
Hmm, About the Raspberry Pi, there is no actual need to make it any more complicated than it is. You can, however, use processing on the Raspberry Pi to control the GPIO pins of the raspberry. You could even make a fancy "Graphical user interface", since a Raspberry has HDMI output. If you're familiar with the Raspberry Pi, then why not, if you're not familiar, you'll need to learn a new "trick" which is a good thing, but you're really going to have to look at whatever time you have left.

@MissySkae, I've you have some buttons, stepper and an Arduino, you should just really try to get something basic working. From that you can expand to something more complicated.
If you start out with thinking about something complicated, and try to do it all at once, you might not even get started at all (since you know, you might just as well use a xbox controller to move the stepper? xD). I might do some tests when I'm home, but I'm not sure since I'm pretty busy with my internship.

If you follow JayEye's approach (ie, use five MCP23017 units to connect 80 switches, and five more to connect 80 LEDs) the wiring and the software should be fairly simple.  But dealing with all the wires will be a problem unless you use a custom printed circuit board to mount all the switches, LEDs, wiring traces, and connectors.  If you have experience with and hands-on access to printed circuit manufacturing equipment, and fast access to the parts you need, that approach should be ok.
A worthwhile alternative is to scale the project back slightly – say to 64 switches and LEDs instead of 80 – and use two Arduino Mega2650's, one to connect to switches, and another to connect to LEDs.  Or you could use one Mega to handle the first 32 switch-and-LED pairs, and another, identically-wired, to handle the other 32.  The two Mega's could communicate by I²C or via RxD-TxD connections (Arduino Mega's have four hardware serials ports, IIRC).  If you plan to wire stuff up with jumpers and breadboards, this probably would be among the simpler, faster, and cheaper approaches.  The modularity of building two identical units (except that only one of them will have the stepper driver attached) improves reliability and ease of debugging.  You could also use four or five identically-wired Uno or Nano boards.
Note, however, that you are likely to have serious reliability problems if you connect up 80 switches and 80 LEDs via breadboards and jumper wires.   As Chris Stratton suggested, start small.  For example, wire up a dozen or two dozen switches and LEDs on a single Mega.  This will let you see how much of a mess the wiring will be, and whether the original scale is practical.  It will also allow tracking down software bugs on a hardware system that is small enough to allow some confidence that the hardware is working.  If you build an 80-unit system before debugging the software, you are likely to run into problems where hours or days go by while you try to sort out whether the problem is due to a software error, a wiring error, or some combination of both.
Note that use of Charlieplexed connections or matrix connections would let you get by with about 10-20% as many IO lines as the direct-connect methods listed above.  However, unless you have used Charlieplexed or multiplexed LED displays and matrix-connected switches successfully in previous projects, and have experience with building and driving circuit boards, the likelihood of getting the project done on time is rather lower than for the other methods mentioned above.

Thanks! I am well aware that it is a lot. There is expertise at school to help out, I just wondered what the options are. I have already made a circuit with one home button, an LED and a 9v battery. I am going to make my own custom circuits and solder everything together, so that has been thought about. Thanks so much for helping me!

Sure.  Note, please upvote any of these answers that you find useful.

I have no idea what an apple homebutton is, but the easiest way to add more GPIO pins is to use something like an MCP23017; it connects over I2C and gives you 16 GPIO pins. Use five of them and you have your solution.

Why not shift registers? :
But the MCP23017 is indeed a viable/nice solution.

Thanks! I will definitely try this out! The home button is the button which belongs to the iPhone. I have made a simple circuit with on button, an LED and a 9v battery and that works perfectly, so now I just need 80 buttons which send a signal to the Arduino and the stepper.


text:
IF, ELSE IF functions not working with analogRead
not sure what is going wrong in the code below, but it's a simplified code of a larger piece I'm trying to debug. I notice that the code seems to skip to the else statement even though the if statement is valid.
Potential is set to analogRead(A0)
while (potential < 1023) {
Serial.println(analogRead(A0));
if (potential < 1023) {
  if (potential > 200) {
    Serial.println("cool");
  } else {
    Serial.println("low");
    lcd.print("hello");
    delay(1000);
  }
}

Results in serial monitor show
235
low
324
low

I've also tried if (potential < 1023 && potential > 200) and if ((potential < 1023) && (potential >200)) to no avail.
Can anyone help, let me know what's going wrong or suggest a fix to this?

Did you forget to read into the variable?

Indeed, the comparison appears to be based on an old value (or maybe an initial 0), not the new value you are printing but never assigning to "potential".  You should probably do the analog read to potential and print that, rather than directly print the return value.

@ChrisStratton and Ignacio
Thanks guys, I added the variable into the while loop and it worked

If in while loop, analogRead needs to be reassigned so it is constantly read.
int potential = analogRead(A0);

void setup() {
  while (potential < 1023) {
    potential = analogRead(A0);
    ...
    }
}

Thanks guys for the help!

I'm not sure what you're trying to achieve with that while.
But this will result in none of your other code being executed until potential is above 1022, which sound rather weird. (Unless it's for some kind of safety mechanism).
The problem is that you do send the new value over serial.
But you do not assign that new value to the variable 'potential'.
Basically, you see something completely different as what is actually happening.
You should do Serial.println(potential); to be sure that you print the value of 'potential'.
And you should assign the analogRead(A0); to your variable potential.
I've also taken away the while since I think it would be misplaced. And I worked around it, so it doesn't block your complete sketch.
void loop() {
  potential = analogRead(A0));
  Serial.println(potential);

  if (potential < 1023) {
    if (potential > 200) {
      Serial.println("cool");
    } else {
      Serial.println("low");
      lcd.print("hello");
      delay(1000);
    }
  }else{
    //Code that won't run if potential < 1023
  }

  //Other code that can run "simultaniously".
}

Thanks for the answer, I'd like to explain a bit more about what I'm trying to achieve.
I want to make sure it doesn't go on to the next part of the code till the potentiometer has been turned all the way to the end (1023). So the whole chunk in my question was part of void setup actually, which also explains why I needed the while for the loop.
I set potential as a global variable, do I need to define it again in the setup scope?

Hi Paul,
I reintroduced the variable into the while loop and it worked.

@Sarahhyy Ah, okay, that other part of the code wasn't shown before ;)
Please consider accepting this as an answer, if it solved your problem.


text:
MIDI controlled analog RGB LED strip (code problem)
I have a an Arduino Uno doing PWM on an RGB analog LED strip ala the Adafruit guide: https://learn.adafruit.com/rgb-led-strips?view=all. I've written a sketch that accepts MIDI data over USB and uses it to control the LEDs.
#include <MIDI.h>
#include <midi_Defs.h>
#include <midi_Message.h>
#include <midi_Namespace.h>
#include <midi_Settings.h>

#include <MIDI.h>

MIDI_CREATE_DEFAULT_INSTANCE();

#define REDPIN 5
#define GREENPIN 6
#define BLUEPIN 3

byte commandByte;
byte noteByte;
byte velocityByte;

byte noteOn = 144;
byte noteOff = 128;

int colorGroup;
int pColor;
int sColor;

void setup()
{
    pinMode(REDPIN, OUTPUT);
    pinMode(GREENPIN, OUTPUT);
    pinMode(BLUEPIN, OUTPUT);
    MIDI.begin(1);
    Serial.begin(115200);
}

void checkMIDI(){
  do{
    if (Serial.available()){
      commandByte = Serial.read();//read first byte
      noteByte = Serial.read();//read next byte
      velocityByte = Serial.read();//read final byte
      }
    }
  while (Serial.available() > 2);//when at least three bytes available
}

void updateLights(){
  colorGroup = noteByte/42;
  pColor = noteByte%41*127/41;
  sColor = 127 - pColor;
  pColor = pColor*velocityByte/127;
  sColor = sColor*velocityByte/127;
  if (commandByte == noteOn && velocityByte > 0){
    if (colorGroup == 1){
      analogWrite(REDPIN, pColor);
      analogWrite(GREENPIN, sColor);
      analogWrite(BLUEPIN, 0);
    }
    else if(colorGroup == 1){
      analogWrite(GREENPIN, pColor);
      analogWrite(BLUEPIN, sColor);
      analogWrite(REDPIN, 0);
    }
    else{
      analogWrite(BLUEPIN, pColor);
      analogWrite(REDPIN, sColor);
      analogWrite(GREENPIN, 0);
    }
  }
  else if(commandByte == noteOff || velocityByte == 0){
    analogWrite(REDPIN, 0);
    analogWrite(GREENPIN, 0);
    analogWrite(BLUEPIN, 0);
  }
}

void loop()
{
    checkMIDI();
    updateLights();
}

Currently this code will turn the lights on and off in accordance with noteOn and noteOff messages. However, the color doesn't seem responsive to the note value and the brightness doesn't seem responsive to the velocity value. I suspect that the problem has to do with my arithmetic combined with the data type (maybe a problem with the order of operations), but I haven't been successful in debugging this.
The idea behind the RGB control is that I take the possible note values (0–127) and map it onto three different combinations of colors: R+G, G+B, and B+R. That's three groups of 42 values: 0-41, 42-84, and 85-127. Then I rescale the 42 values onto 0-127 for the intensity values of the LEDs. Finally I scale the intensity of all the colors by the velocity value over its possible max value.

I suggest that you write separate test programs for MIDI input and LED control, before trying to combine them together.  That is, write a sketch to report back on Serial what MIDI data was read, and a sketch to cycle the LEDs through obvious patterns.
For example, if you read 10,20,30 as the three MIDI bytes, output "Got 10,20,30" (or similar).  If that appears to be working, then add your arithmetic and output the results of colorGroup, pColor, and sColor calculations.
Note, the comment after do{ ...} while (Serial.available() > 2); says //when at least three bytes available, which does not correctly represent what that do loop does.  When one or more bytes are available, that loop immediately reads three bytes (getting a value of -1 for any not-available byte).  To do the read only if three bytes are available, get rid of the do{ ...} while construct, and instead say if (Serial.available() > 2) { <read 3 bytes> }.
Note, use parentheses in expressions like pColor*velocityByte/127.  IIRC the C spec allows evaluation of that as either (pColor*velocityByte)/127 or as pColor*(velocityByte/127).  Since velocityByte/127 can only evaluate to 0 or 1, the result of the latter form is either pColor or 0.
Note, your code shows if (colorGroup == 1){ twice.  Change 1 to some other number in the second instance.
To cycle the LEDs through obvious patterns, you could have three different sketches, one that gradually raises and lowers the PWM level on Red, one that does the same for Green, and another for Blue.

Thanks. I haven't tried these suggestions yet, but I'm fairly certain a combination of the errors you pointed out is the source of problems, and also I was unaware that you could print with the Arduino back to the computer over USB. That will be very helpful for debugging (which I'll do w/ the functions separate/piecemeal as you suggested).

Okay – slight problem. Because I am sending MIDI over the USB, I think the serial monitor is not working properly, or is interfering with the incoming MIDI data. I was able to use the serial monitor to check that the arithmetic is working properly, but when I use it to simply print the incoming MIDI data bytes, it will print different sorts of nonsense (e.g. it will print "144" [noteOn] as "14" and then it will pause and print another "4").
I'm unsure how to use the serial monitor concurrently with a MIDI to serial converter.

I figured out a solution. Hairless has a debug window that interprets MIDI data outgoing and incoming. If I use Serial.write (rather than print) then Hairless will show both the outgoing MIDI and the MIDI that's echoed back from the Arduino!


text:
How do I read from /dev/ttyACM0 in Linux without a terminal emulator?
I just bought an Arduino Due and I'm having trouble reading from a simple serial IO program.
I have a SparkFun RedBoard which is like an Uno. With that, I just ran a "stty" command to configure the baud rate and other terminal settings, and then I could do "cat /dev/ttyUSB0". Actually I have a C++ program which opens "/dev/ttyUSB01" and reads from it like a normal file.
Now, with the Due, the device is "/dev/ttyACM0" and there have been a few snags. One of them is that after programming the Due, and running stty, I have to open /dev/ttyACM0 using the screen program:
screen /dev/ttyACM0 115200

and then kill screen, before cat /dev/ttyACM0 will work. Otherwise, cat prints out one byte and exits; rarely it prints out 10 bytes or a line, or sometimes it prints nothing.
This is a bit annoying and I can't figure out what screen is doing to the device which I can't seem to accomplish using stty. My stty command is:
sudo stty -F /dev/ttyACM* 115200 -parenb -parodd -cmspar cs8 -hupcl -cstopb cread clocal -crtscts \
-ignbrk brkint ignpar -parmrk -inpck -istrip -inlcr -igncr -icrnl ixon -ixoff -iuclc \
-ixany -imaxbel -iutf8 \
-opost -olcuc -ocrnl -onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0 \
-isig -icanon iexten -echo echoe echok -echonl -noflsh -xcase -tostop -echoprt echoctl \
echoke -flusho -extproc

I got this by running stty -a < /dev/ttyACM0 after using screen to initialize as above.
I thought it might have something to do with serial auto-reset, so I tried using a resistor between 3.3V and RESET, but this did not fix the problem.
I should note that cu from the uucp package is able to read continuously from /dev/ttyACM0, but unlike screen it does not leave the terminal set up in such a way that a subsequent cat command will work.
$ cu -l /dev/ttyACM0 -s 115200
<continuous stream of data>
$ killall cu             # (from another shell)
$ cat /dev/ttyACM0 | hexdump -c
<e.g. 7 bytes>
$

With screen, cat would have printed an infinite stream. Any ideas how to accomplish this setup without using screen?

You can have stty dump the settings established by screen for future use. See its man page for details.

I thought you'd missed my use of stty -a but then I saw that there's a stty -g ("print all current settings in a stty-readable form"). It doesn't really seem to be documented, but now I see that I can pass the output of stty -g as an argument to stty: stty "0:0:18b2:0:3:1c:7f:8:4:0:1:0:11:13:1a:0:12:f:17:16:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0:0" -F /dev/ttyACM0. This indeed works, where copy-pasting from stty -a didn't work because I missed the min 1 bit. However, I'm glad for @jantje's solution because now I understand what was going wrong and plus I have a readable command-line.

I have had very similar problems with my yun(shields) and I found the stty command to be very crucial for a good working.
I use following command and it works with mega and due on the yun
stty -F ${PortName}  ${SerialSpeed}  raw -clocal -echo icrnl

Since I call these I can redirect from and to /dev/ttyxxx without problems.
As far as I can see you mis the raw.

That seems to work for me. In fact I narrowed it down a bit: if I just stty -F /dev/ttyACM1 115200 min 1 then it works. The min 1 is part of the definition of stty raw. So I guess the Arduino IDE was putting the terminal into a mode where reads could be non-blocking. I guess I'll use your whole stty command in the future though - the other options look useful, although may I ask why you have icrnl?
Anyway, thank you!

To be honest.... I think you understand far more about this then I do. I started like you; with running a program (minicom in my case) and then querying stty. After 2 years of playing with the yun shield I ended up with these. I'm happy to see they work for you as well. But it is based on trial and error not on knowing. So I can't answer your question.

Well, I'm not sure, but I confess I had a recent issue with a mysterious glitch appearing in my software-oscilloscpe trace around X=13. It went away when I removed the icrnl setting :)


text:
Is it possible to receive a 9 bit protocol on the Arduino Uno with Arduino?
I want send and receive a 9 bit async-serial protocol with 4800 baud on my Arduino Uno, i have read on the specification from the ATmega328P that the uart can do that.
My aim is that when my Uart receive the 9th bit as a 1 he must throw a interrupt. On this interrupt i can recognize that this byte was an adress byte.
When he receive a zero he sould do nothing spezial, only transmit it as hex-byte over usb to the pc.
My Problem now, i can´t initialize the Uart right because the command Serial.begin(4800, config) is not enough, i must throw the interrupt and translate the data to hex-bytes.
My Question can i modify the Serial.begin() source code respectively where can i find the source code for the Serial.begin function?
When there is no possibility to change the code has someone a other option for me to send and receive the 9 bit protocol with an Arduino Uno?

How are you connecting the the '328p's UART?  I don't think you will get 9 bits through the '16u2 USB-serial chip on the Uno unless you modify its firmware, and you'd have to see how to get the USB side of things to support it.   Your functional description isn't very clear either, but it sounds like you would need to modify the serial receive ISR away from the usual Arduino one.  On the other hand, if what you want is for the Uno to be a bridge between some serial device and a PC, you will actually need to use and modify a software serial implementation or use a Leonardo instead of Uno.

If you want to set the UART to 9-bit mode, you will have to set the
UCSZ02 bit of the _ucsrb register to 1 in
HardwareSerial::begin().
For example:
void HardwareSerial::begin(unsigned long baud, byte config)
{
  // Mostly unchanged... but by the end:
  sbi(*_ucsrb, RXCIE0);
  cbi(*_ucsrb, UDRIE0);
  sbi(*_ucsrb, UCSZ02);  // set 9-bit data mode
}

Notice that you do not need to modify the Arduino core library for this:
you could set that bit in your setup(), right after calling
Serial.begin().
Then, in the HardwareSerial::_rx_complete_irq() interrupt
handler,
you will have to read the 9th bit as the RXB80 bit in UCSR0B, before
reading the low byte from _udr (emphasis in the datasheet). For
example, you could replace the line unsigned char c = *_udr; by:
bool is_address = UCSR0B & _BV(RXB80);  // read 9th bit first
unsigned char c = *_udr;                // then the other bits
if (is_address) {
  do_something_with_address(c);
  return;
}

where do_something_with_address() is the stuff you wanted to do in
another interrupt (no need for that, you are already in interrupt
context).
It is worth noting that, with an Arduino Uno, you will not be able to do
all this while sending data to the PC. This is because the communication
with the PC uses the only UART of the ATmega328P.

When i have insert a 1 in UCSZ02 what must i do with code? Must i patch my Arduino, or how can i add the bit at my Arduino?                                   I didn´t know how i read the RXB80 bit as 9th bit have you a example for me pls.

@sniffi: I added some examples of untested code to the answer.

Can i use the Arduino mega 2560 for that? He has 4 uart´s or can i expand my Uno with a uart?

I do not know about chips that could be used to add an UART to an Uno. They may exist, and if so they should be usable if they can be interfaced via I2C or SPI at 5 V. A Mega2560 is probably an easier solution. It's UART number 0 is used for communication with the host computer, so you can use any of the other 3 for your 9-bit protocol. Just make sure you tap into the correct registers, e.g. you set UCSZ12 and read RXB81 on UCSR1B if you use UART1.

It sounds like you want some device with a 9-bit protocol to send data to an Arduino, and then the Arduino to forward that data (perhaps in a slightly different format) to a PC.
People who want to connect their Arduino to two serial devices at the same time (and the PC counts as one) generally either:
Change the hardware to accept multiple serial devices
While the Arduino Uno has only one hardware serial port, the following (and probably many others) have 2 or more hardware serial ports:

Arduino Mega 2560 (USB and 3 other hardware serial ports)
Arduino Leonardo (USB and 1 other hardware serial port)
Teensy LC (USB and 3 other hardware serial ports) ("serial 9-bit on the t3")

("Sending and Receiving 9-bit Frames with Arduino" uses the hardware approach).
Change the software to accept multiple serial devices
In principle, it's possible to tweak SoftwareSerial to handle 9-bit data.
Several people have talked about it

"9bit SoftwareSerial library modification"
"Altering New Soft Serial NSS for 9 bit- cans of open source worms"

The Max3140 is a very capable USART with built-in full/half-duplex RS-485 drivers that interfaces to a uController via SPI. They are a bit pricey and you would have to make a board, solder, etc..
Another solution would be to dedicate a simple and inexpensive minimal Arduino-compliant board (like a Pro-Mini) to interface with the "main" Arduino via I2C or SPI, and program the Pro-Mini for 9-bit addressing mode and add the RS-485 driver. Pro-Mini or Nano clones are dirt cheap, but it is not even that expensive to use an authentic Arduino product and support their great contributions ;-).


text:
How to rewrite code in millis?
I am currently working on a project that makes a plateua move back and forth using a stepper motor. On this plateau I have attached LEDs that create patterns.
However, the plateau should be moving whilst the pattern is changing. With my current code this is not happening. I know that I have to work with millis, but when I am completely lost on how to do it. Could someone help me?
Here is my code:
#include <AccelStepper.h>

AccelStepper stepper(1, 42, 38);

int i;
int microStep = 46;

int currentAnimation = 0;
int count = 0;
int button = 13;

int state = LOW;
int lastState = LOW;

//bytes for patterns
byte a = B11110000;
byte b = B00010000;
byte c = B01000000;
byte e = B10100000;

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

void setup()
{
  DDRH = B1111000; // set PORT 6-9 of arduino mega high
  DDRB = B11110000; // set PORT 10-13 high

  stepper.setMaxSpeed(900.0);
  stepper.setAcceleration(400.0);

  pinMode(button, INPUT);
  state = digitalRead(button);

  pinMode(microStep, OUTPUT);
  digitalWrite(microStep, HIGH);
}

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

void loop()
{
  //This should happen constantly
  stepper.runToNewPosition(2000);
  delay(500);
  stepper.runToNewPosition(0);

  // These are the patterns, that should be played whilst the stepper is running. The patterns chaneg when you push the button
  if ( state == HIGH & lastState == LOW )
  {
    currentAnimation++;
  }

  if (currentAnimation % 3 == 0)
  {
    same();

  }
  if (currentAnimation % 3 == 1)
  {
    left();
  }
  if (currentAnimation % 3 == 2) {
    faster();
  }

  lastState = state;
  state = digitalRead(button);
}

//--------------------------------------------------------------------------------------------------------------------------------
//PATTERNS
void same() {
  for (int k = 0; k < 10; k++) //plays 10 times
  {
    PORTH = a;
    PORTB = a;
    delay(100);
    PORTH = 0;
    PORTB = 0;
    delay(100);
  }
}

void left() {
  for (int z = 0; z < 10; z++)
  {
    PORTH = e;
    PORTB = e;
    delay(100);
    PORTH = ~e;
    PORTB = ~e;
    delay(100);
  }

}

void faster() {
  for (int z = 0; z < 256; z++)
  {
    PORTH = z;
    PORTB = z;
    delay(100);
  }
  PORTH = 0;
  PORTB = 0;
}

The problem is that the animations (or actually the delay in them) will block the other code from running. But could you expand a little on what timing you want to achieve? You'll want to run stepper.runToNewPosition(xxx); every 500ms, and change the pattern each 100ms?

Actually, https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay explains it rather well.

The basic pattern goes like this:
when you start the timer, you essentially store the current millisecond.
After this, in your loop code, among other things you should check if the time has passed by comparing current millisecond with the stored one. If their difference is equal or bigger of the desired delay interval, then the time has passed.
Make sure you use unsigned long variables to store times and check if time has passed with the condition used below (if(millis() - mark >= interval ){...}) so you will not have problem even after millis() rolls over.
If you need more help, do not hesitate to ask.
unsigned long interval=2000; //2000ms
unsigned long mark;
boolean enabled=true;

void setup() {
    Serial.begin(9600);
    Serial.println("starting timer");
    startTimer();

}

void loop() {
    check();
}

void startTimer(){
    mark=millis();
}

void check(){
    if(enabled){
        if(millis() - mark >= interval ){

            enabled=false;
            Serial.println("time elapsed");
        }

    }
}

Hmm, this code will only run once, instead of in 2000ms intervals. I'm not sure if you/he were/was aiming for that.

it only aims to demonstrate the way one would use millis() to measure time.
Apart from that, it is easily modifiable to auto restart ->
just replace line enabled=false; in check() with startTimer();

Ah, that's what the startTimer() function was for, I thought it was pretty silly to set up the mark in a function. You've got my vote, it's a good answer. It's very much like the blink tutorial.

It'd be fairly easy to create a library that allows multiple timers which can be easily started and checked. Which is a nice idea if you're going to have a lot of these projects.

You could try something along these lines, I haven't put all of the code in, but just how this could be done for the sweep timer using millis().
unsigned long sweepTime;
unsigned long animationTime;
int stepperPosition;

void setup()
{
    //... other setup code
    sweepTime = millis();       // initialise the variables for the sweep timer, and the animation timer
    animationTime = millis();
    stepperPosition = 2000;     // initialise the next stepper position
}

void loop()
{
    if (millis() - sweepTime > 500) //  check if more than 500 milliseconds have elapsed since last time we ran this.
    {
        stepper.runToNewPosition(stepperPosition);  // change stepper position
        sweepTime = millis();           // reset timer variable
        switch (stepperPosition) {      // need to change the value of the next position to set the stepper to
            case 0 :
                stepperPosition = 2000;
                break;
            case 2000 :
                stepperPosition = 0;
                break;
        }
    }
    //... continuation of loop code
}

Additionally, I don't have my arduino with me, so can't verify the correctness of the code.

You're missing a case label on the second case of your switch. I would've used a if-else statement anyway.
And the time variables should be unsigned long rather than long.

@Paul. Thanks for feedback, I have changed and corrected. I tend to use if-else for boolean comparisons - you're probably right in this case, but I personally think the switch allows for additional sweep values in the future.

switch-case statements are extremely useful if you're skipping through states, and when you declare these states in an enum, the compiler even tells you whenever you did not implement one of the states, which is nice. I get your point, but if it's two things, a if-else is smaller and more logical. You could also argue that if-else is better since you can add other conditions to it ;) which isn't quite possible in a switch-case. But I agree that if-statements are often mis-used xD

Since microcontrollers typically only have one "core" or "thread" they can only do "one thing at a time".
A microcontroller will step through your code and do everything in order (if you don't call interrupts).
Basically, when you put in a for-loop (or any other type of loop) or a delay, it will only continue with the rest of your code when that is done.
To solve this, and "do two things at a time" (or actually rapidly switch between things) you'll need either interrupts or non-blocking code (or both).
Interrupts
I see you're doing some direct port manipulation, which is really nice. You're writing bytes directly to the control registers of the microcontroller.
You can leverage on that, to set up a timer (check the ATMega328P datasheet). You may make this timer give an interrupt each 100ms, and execute a "frame" of your animation at that point. And the next frame at the next interrupt. So that the time between each frames can be used for other code.
Non-blocking code
Arduino has built-in millis(); which is basically an interrupt that fires every millisecond to keep track of the passed milliseconds. So you can use this instead of fiddling around with the timers (which may very well cause some of the Arduino's functions to fail (like millis() or the servo library).
To write non-blocking code, you'll not use delays, since they effectively throw away "processor time" by doing "nothing-instructions" all the time.
But if we take out the delays, the for-loops will run too fast. And a for-loop also doesn't really work without the delay. Because even if you use millis and wait for half a second, you can't do anything in between.
So we'll have to break up your code (specifically the animations) in chunks of code that can be executed withouth a delay. With only the need to delay in between these chunks.
Frames
Let's split up your animations in "frames". One of your animations same() works by PORTH&PORTB = A for 100msec and low for 100 msec.
void sameAnimation(unsigned char frame){//plays 20 times (1x on, 1x off) instead of 10x on-off.
  if(frame%2==0){//If even
    PORTH = a;
    PORTB = a;
  }else{//if not even.
    PORTH = 0;
    PORTB = 0;
  }
}

So based on the frame of the animation, the port will go high or low.
Now we look at the complete code, we have to change the motor every 500ms and have to change the animation frame every 100ms. And check a button.
We could put these in an interrupt that fires every 100ms, which would get reliable timing and minimum software overhead.
Or use the millis(); (checked against the previous milis) to check if the last update was 100ms ago.
My go at the code is below, but you should be able to figure it out yourself.
void loop()
{
  unsigned char currentFrame = 0;

  //Could be done every round.

  lastState = state;
  state = digitalRead(button);
  if ( state == HIGH & lastState == LOW )
  {
    currentAnimation++;
    PORTH = 0;
    PORTB = 0;
  }

  // These are the patterns, that should be played whilst the stepper is running.

  if(millis() - previousMillis > 500){// Should change every 100ms
    previousMillis = millis();

    if (currentAnimation % 3 == 0)
    {
      sameAnimation(currentFrame++);
    }
    if (currentAnimation % 3 == 1)
    {
      leftAnimation(currentFrame++);
    }
    if (currentAnimation % 3 == 2) {
      fasterAnimation(currentFrame++);
    }

    if(currentFrame % 5){//Should change every 500ms, so every 5 frames.
      if(forward){
        stepper.runToNewPosition(0);
        forward = false;
      }else{
        stepper.runToNewPosition(2000);
        forward = true;
      }
    }
  }
}

//--------------------------------------------------------------------------------------------------------------------------------
//PATTERNS
void sameAnimation(unsigned char frame){//plays 20 times (1x on, 1x off) instead of 10x on-off.
  if(frame%2==0){//If even
    PORTH = a;
    PORTB = a;
  }else{//if not even.
    PORTH = 0;
    PORTB = 0;
  }
}

void leftAnimation(unsigned char frame) {
  if(frame%2==0){//If even
    PORTH = e;
    PORTB = e;
  }else{//if not even.
    PORTH = ~e;
    PORTB = ~e;
  }
}

void fasterAnimation(unsigned char frame){
  PORTH = frame;
  PORTB = frame;
}

The button
Checking the button every round isn't really needed. You can use an interrupt on that pin, so that the code to check it's state and go to the next frame only happens when the button is actually pressed. (interrupt triggered on rising edge?).


text:
Read int from Serial
with the following sketch I should be able to read and store what is entered in the Serial monitor
void setup() {
  Serial.begin(115200);
  while(!Serial);
}

void loop() {

  Serial.println("Enter Zone Number: ");
  while(!Serial.available()){
  }
   int zone = Serial.parseInt();
   Serial.println(zone);

}

if I enter "1" I would except this:
Enter Zone Number:
1

but unfortunately I have this:
Enter Zone Number:
1
Enter Zone Number:
0

What am I missing?

.parseInt() reads incoming text up until either it times out or until it reads something that isn't a number.
You are sending a number, and most likely a line-ending. If that line-ending is a simple \n then that will trigger the "end of number" and will be discarded and the number returned.  However, if you are sending \r\n (i.e., CRLF) then you effectively have two line endings there:
1\r\n

Parsed as:
1\r => return 1
\n => return 0

Relying on the (poorly written) Arduino stream parsing routines is not good. Not only are they blocking, but often they just don't work right.
Instead you should be reading the serial properly, taking account of line endings, and then converting the string you have read into a number using the likes of atoi().
Tutorial on reading serial:

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

Here is a really nice and simple solution (More robust also concerning line breaks): https://stackoverflow.com/a/20962137/2714285
int x;
String str;

void loop() {
    if (Serial.available() > 0) {
        x = Serial.parseInt();
        str = Serial.readStringUntil('\n');
    }
}

it is a too heavy solution to get rid of one \n

If your goal is speed I understand your point but I first tried the solution of the article of  Majenko and it just didn't work on linux (the \n char was just not recognized). And it's, btw, much more heavy in terms of readability / code / docs to maintain if your work in a team


text:
TMC26XMotorTester:44: error: 'TMC26XStepper' does not name a type
I am working with a TOS-100 Stepper Driver Shield and am attempting to use the pre-written TMC26XMotorTester/Motor/Serial set of files to make it work.
I unzipped the files, copied the TMC26XStepper folder into the library directory in my Arduino folder, and restarted the Arduino IDE (as well as the Arduino and Driver Shield boards).  I also switched the DIR and STEP pins (6 and 7 swapped to match the wiring on my board).
In the TMC26XMotorTester file, I wrote
    #include <TMC26XStepper.h>

so I'm assuming (given everything I've done), that the functions should be available given this file inclusion.
However, I get the error
    TMC26XMotorTester:44: error: 'TMC26XStepper' does not name a type

along with the complete list of functions from the TMC26XStepper.h/.cpp file that were not identified.
Any thoughts?  I'm using Arduino-Uno version 1.6.9.

Make sure the library folder structure is correct. Inside the TMC26XStepper folder there should be TMC26XStepper.h - If it's in a sub-folder within that it won't work. Some libraries are distributed in folders within zip files, especially some on Github.

It was in the TMC26XMotorTester folder as well as the TMC26XStepper-master folder (the 'master' portion is part of the folder name).  When I open the TMC26XMotorTester.ino file (located in the TMC26XMotorTester folder), all 5 files appear in my sketch (the one I just mentioned, Motor.ino, Serial.ino, TMC26XStepper.h and .cpp).

But I still keep receiving an error.

Sounds like you have a mess in your folder structure. Where did you download it from?

Just the Github file uploaded by the designer.   I don't know why this worked, but I switched my #include <> to #include "TMC26XStepper.h" and it worked, and uploaded.

Here's a good explanation regarding how include works.  Likely, the header file was not in the path the compiler was told to use (that is, your library directories are out of whack) but is in the directory where a source code file included it.

Arduino libraries are normally written as a C++ Class.  When you start a sketch you normally tell the compiler where to find that Class and to Instantiate that class.  If the compiler does not find the Class and you attempt to Instantiate it, the compiler will telly you it does not know what to do.  That is, it will tell you the thing you are using (TMC26XStepper) does not describe anything or is not a Type.
Study the structure of Arduino libraries to make sure what you have installed agrees with the common Arduino library.
Also, newer version of the Arduino IDE can download and unpack libraries automatically given both the IDE and the library are setup to do this.


text:
GikFun Arduino Nano locking up on serial I/O
I'm running into a problem with a GikFun Arduino Nano. The symptom appears when I'm reading the receive buffer to clear it after an operation completes. The unit just appears to stop somewhere in the loop function and never continues.
I know that this unit has a CH340 UART on it which seems to have issues.
Any suggestions on what I can do?
OP Edits
This code is more or less based on the code from this Make: article. I originally had this assembled through an Arduino Uno R3 with an HC-06 (Kootek BT2S) module. Everything connected via solderless bread-board.
This entire circuit works properly with the UNO, which I had it running on SoftwareSerial using pins 2, 3. After putting this on a perf-board in a project box using the GikFun Nano, it was not behaving. I had a number of wiring issues, which I resolved, but still had issues communicating on the HC-06/SoftwareSerial. I re-did the wiring using pins 0, 1 for the Serial and removed the SoftwareSerial references. The circuit worked as I expected with the HC-06 working as it had before. But if I issued more than 1-2 commands via Bluetooth the unit would just get stuck. I also tried this without the HC-06 connected and just used the Serial Monitor through the IDE same behavior. It would randomly lock up after clearing the receive buffer.
Code - as requested:
const int statusLED = 13; //the pin you connect your status LED to
const int desiredBaud = 4;//index of your desired baud rate 4 is 9600
char* myPin = "1234";//change to the pin of your choice

const int memRed=0;
const int memGreen=1;
const int memBlue=2;

const int redPin= 9;
const int greenPin= 10;
const int bluePin= 11;
const int cmdLed= 12;

// Max Red - 255
const int max_red = 255;
// Max Green - 90
const int max_green = 255;
// Max Green - 100
const int max_blue = 255;

int red= 255;
int green= 255;
int blue= 255;

unsigned int baudLookup[] =
{
  1200,  //code 1
  2400,  //code 2
  4800,  //code 3
  9600,  //code 4
  19200, //code 5
  38400, //code 6
  57600  //code 7
};

void setup()
{
  Serial.begin(9600);
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);
  pinMode(bluePin, OUTPUT);
  pinMode(cmdLed, OUTPUT);
  pinMode(statusLED, OUTPUT);
  digitalWrite(statusLED, HIGH);

  Serial.begin(9600);
  delay(1500);//wait for reset to complete

  Serial.print("AT");
  delay(1500);//wait for reset to complete
  while(Serial.available()) {
    Serial.read();
  }
  delay(1500);//wait for reset to complete

  digitalWrite(statusLED, HIGH); //SUCCESS!

  digitalWrite(redPin, map( red, 0, 255, 0, max_red) );
  digitalWrite(greenPin, map( green, 0, 255, 0, max_green) );
  digitalWrite(bluePin, map( blue, 0, 255, 0, max_blue) );
}

void loop()
{
  digitalWrite(statusLED, LOW); //fast blink means success
  delay(200);
  digitalWrite(statusLED, HIGH);
  delay(200);

  String stat;
  char buffer[13];
  buffer[12]= 0;
  if( Serial.available() >= 3 ) {
    String stat = String("OK");

    Serial.readBytes(buffer, 3);
    buffer[3]= 0;
    String command= String(buffer);

    Serial.println(command);
    if( command == "GET" ) {
      char outBuffer[7];
      sprintf(outBuffer, " %02x%02x%02x", red, green, blue);
      stat += outBuffer;
    }
    else if( command == "SET" ) {
      if( Serial.available() >= 6 ) {
        Serial.readBytes(buffer, 6);

        int redVal= (getVal(buffer[0])<<4) | (getVal(buffer[1]));
        int greenVal= (getVal(buffer[2])<<4) | (getVal(buffer[3]));
        int blueVal= (getVal(buffer[4])<<4) | (getVal(buffer[5]));

        digitalWrite(redPin, map( redVal, 0, 255, 0, max_red) );
        digitalWrite(greenPin, map( greenVal, 0, 255, 0, max_green) );
        digitalWrite(bluePin, map( blueVal, 0, 255, 0, max_blue) );

        red= redVal;
        green= greenVal;
        blue= blueVal;

        char outBuffer[7];
        sprintf(outBuffer, " %02x%02x%02x", redVal, greenVal, blueVal);
        stat += outBuffer;
      } else {
        stat = "ERR";
      }
    }
    else {
      Serial.println("No Command");
    }
    Serial.println(stat);
    Serial.println("Clearing receive buffer");
    delay(1500);
    while(Serial.available()) {
      Serial.read();
      delay(100);
    }
    delay(1500);
  }
}

byte getVal(char c)
{
  if(c >= '0' && c <= '9') {
    return (byte)(c - '0');
  } else {
    return (byte)(c-'A'+10);
  }
}

You need to show code which experiences the problem.  Even it not happening to a board with a different USB-serial implementation would not be proof against invalid assumptions in the serial code broken by permissible behavior of the converter or its driver.  Of course, a hardware or driver issue is a possibility too, but don't jump straight to assuming that.

I'll post code shortly

This mix of delays and buffer flushing is exactly the kind of invalid assumption I was talking about... it is just asking for unreliability, and your  while loop that reads with delays could easily never terminate.  Instead you should end your commands with something distinct, like a newline, and read until that.  Generally you want to avoid flushing - or at least, only flush until a defined endpoint.  Also, your description of what you were ultimate doing sounds like trying to use the hardware serial pins for both the USB-serial and the bluetooth, which isn't really workable.

@Chris I appreciate your feed back on this and yes assumptions are a total foul up on my part. As for the serial, I disconnected the HC-06 when using the monitor

@Chris ... looking back over this you are 100% spot on with the possible infinite. I'm going to try and gut out some of the stupidity I introduced on this and give it another go. Would you please post an answer so I can at least give you credit for your feedback?

The mix of delays and flushing in your code has a high chance of leading to unreliable operation.  Consider for example:
Serial.println("Clearing receive buffer");
delay(1500);
while(Serial.available()) {
  Serial.read();
  delay(100);
}
delay(1500);

As the loop there can only consume about 10 characters per second, it would be quite easy for something on the far end to produce inputs faster than they are consumed, essentially making the loop infinite.
Time-based delineation of serial messages tends to be quite risky; better reliability is usually had by using a defined delimiting condition - for example, ending each message with a newline character and reading until that is seen.
USB-serial conversion also introduces added challenges for time-based schemes, as it introduces a sense of grouping into packets into a stream which in its native form does not have any.

Chris - again thank you for your help on this - I redid the logic gutting out all of the stupidity and got the program stable. This also included adding a serialEvent() implementation and remembering how to properly use the stdc library. Everything was going swimmingly until I think I accidentally shorted out my HC-06 and fried it. It was working fine before that happened and I've got a replacement on the way.

Glad you made progress and sorry to hear about the accidental toasting.  Just as a last caution, keep in mind that serialEvent() is not an interrupt or thread of its own - it runs only between calls to loop() so doesn't differ much other than visually from checking availability at some point within your loop.

Thanks for the heads up. I took the code that is detailed in the serial event documentation and it was behaving.

The issue would be with whatever you did in your loop() - serialEvent() can only run when that is done taking up time, and so it can only make data available for the next iteration of loop().

And that is exactly what I want


text:
I feel like an idiot, why can't I make a servo move with the boilerplate code?
So I was working on a far more grand project, until I discovered that I couldn't get any of my servos to move.
I've gone back to basics, and am trying to just get the boilerplate code found here, working.
#include <Servo.h>

Servo myservo;  // create servo object to control a servo
// twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop() {
  for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
}

Here are pictures of my setup.

You can embed pictures into your question (I'm not sure of the limit if you don't have much rep - at least one or two). For short code it helps to embed the code as well - I did that for you. You can provide a link so people know where it came from.

The only thing I see that could be the problem is with your servo wiring. It seems that most servos use this kind of wiring  Which is the way that you seem to wire it, but depending on how Radioshack servos are made the signal wire could correspond with a different wire. I imagine this could possibly be on the packaging so I would start by looking there to confirm your wiring.


text:
Circumventing overflow error by pushing data into computer?
It seems in certain applications, for example signal processing, Arduino and other micro-controllers in general run into the overflow error when they're trying to store even moderate amounts of data. It would seem the obvious answer would be to simply take this data, push it onto the computer, and deal with it there instead, where you have much more available computing power. Is this possible with Arduino, or am I missing something that makes it not feasible?

You're missing a reasonable definition of "push".

Sure, if you have a better computer at hand, and a communication channel that can keep up with the data rate, it can indeed be a good idea to hand it off unprocessed.  Or processed just enough to reduce the data rate to what the communication channel can handle.

In theory yes. In practice, depends on your requirements and implementation.

A good example video: https://www.youtube.com/watch?v=ruuxn2u3yao (he's using an Teensy LC rather than an Arduino, but yeah, it's a microcontroller).

One of the "features" of most microcontrollers/microprocessors is that they don't have a whole heap of RAM - this keeps costs down, and lets the manufacturers keep everything on one chip (unlike your PC).
However to "push" data to somewhere that can process it, you need to have a fast communications channel. SPI is quite fast, but you don't generally talk to PCs using SPI. Serial communication is slower, but if it gets converted into a USB interface (such as on a Uno) you can get respectable speeds talking to a PC. Something like 115200 baud is usually reliable, which lets you transmit 11520 bytes per second.
However it depends on what you want to send (ie. how many bytes), how you are going to indicate where one piece of data ends and the next one starts, maybe allow for error detection or correction, and so on.
Say, for example, it takes 5 bytes to send one piece of data (eg. 4 digits plus a delimiter). Now you are down to 11520/5 = 2304 pieces of data per second.
This may or may not be adequate for whatever-it-is you are trying to do.

I'm wondering if the Arduino's with built-in USB (Atmega32u4?) would be faster than "Uart". Polulu claims: Native full-speed USB (12 Mbps), which is quite fast.

Possibly, although I got my Uno to run the ASCII table sketch at 230400 baud. That's only 43.4 µs per byte, and you would probably have trouble acquiring data much faster than that. For example, anything requiring an analog read at default speed takes 104 µs.

Cool, if you do ADC with interrupts, you could send the value while waiting for the other to complete :)

That's right, so you won't take 104 + 43.4 µs. However you still have the limitation of the overall time. You can, though, run the ADC clock faster and still get acceptable results.


text:
Why doesn't my LEDs turn on?
i have just started learning Arduino, so please be patient to me :)
Why doesnt my circuit below doesn't work?

Here's the code:
#define led_green 2
#define led_yellow 8
#define led_red 13

void setup() {
  pinMode(led_green, OUTPUT);
  pinMode(led_yellow, OUTPUT);
  pinMode(led_red, OUTPUT);

  // Strarting all turned off
  digitalWrite(led_green, LOW);
  digitalWrite(led_yellow, LOW);
  digitalWrite(led_red, LOW);
}

void loop() {
digitalWrite(led_red, HIGH);

delay(1000);

digitalWrite(led_red, LOW);
digitalWrite(led_green, HIGH);

delay(1000);

digitalWrite(led_green, LOW);
digitalWrite(led_yellow, HIGH);

delay(1000);

digitalWrite(led_yellow, LOW);

}

I'm trying to reproduce this circuit that I saw in a tutorial:

Thank you.

"I'm trying to reproduce this circuit that I saw in a tutorial" But your connections don't look anything like that.

Is it better now? http://s33.postimg.org/z4xey1jxr/now.jpg

No.  The outputs all are shorted directly to the GND rail, and could damage your arduino.  Also the top-ends of the LEDs are shorted to the bottom ends of the LEDs, so no current will flow through them.

The tutorial you showed has the LEDs "jumping the gap" in the middle. You can't move them to one side like you did. That just shorts them together.

The code  that you posted, is that the same code you put on the Arduino in the image?

If you are doing what is in the first picture then you're doing it wrong.
You have to make sure the led is horizontal, not vertical. The signal is going through the led and not making it into ground. And your ground is in the same lane as your signal.
I think you should learn how breadboards work and then move on from there. Its pretty simple and I think you'll learn it quickly.
For your code part, instead of defining the variables, you could just use int.
 Refer to this as a starter tutorial, https://www.arduino.cc/en/Tutorial/.

This is how your wiring should look like if you followed the tutorial,

Thanks, i 'll look into it... just one thing, though: it looks to me that the led is vertical in the picture of the tutorial!

Haras' circuit is fine.  The 'verticalness' in the pic you posted has the leds bridging the center gap, and the resistors jumping to the common GND rail.  Contrary to your circuit, Haras is twisting the LEDs sideways so both terminals of the LEDs are not shorted together, but are on different 5-tie-point segments on the breadboard.


text:
message received from GSM contains parenthesis instead of curly braces
the GSM code i have been working out is up and running, I use JSON format in sending the data obtained by my sensors, but the JSON message I have been receiving contains parenthesis instead of curly braces.

One or both of your GSM endpoints is incapable of handling ESC prefixes according to GSM 03.38. The only difference between "{" and "}" and "(" and ")" is that the former are signified by a preceding ESC which either is not being generated by the sender or is not being interpreted by the receiver.


text:
Is it safe to power the Uno with 18v?
So I'm aware the Arduino Uno can take 6-20 volts, with a recommended voltage of 7-12. But I have an unregulated 12v power adapter, which puts out about 18v with no load.
Most of the time the Arduino won't be doing much of anything but powering a 16x2 LCD, which should take only a couple mA.* I have a 10k ohm resistor on the back light, so it should only take 0.5mA.
*I don't have a datasheet, but from what I've read 1-2mA is reasonable
The Arduino won't be doing anything else that would draw any meaningful amount of current (except looping to check for input, etc). Online sources generally indicate the power draw when not doing anything is a little under 50mA, so I'm guessing that's about what the current draw will be. Using the formula in this answer, I calculate the power dissipation by the voltage regulator to be (18v-5v)*0.05A=0.65 Watts.

Is this correct?
Is the voltage regulator likely to overheat?

I'm not really concerned about power usage, because it will be plugged into the wall all the time. Also, the Arduino will be out of sight, but will have plenty of air around it to disipate heat (though not access to a breeze).

It won't do any harm to try it at 18V for a while. Most voltage regulators have thermal protection and just cut out if they get a little too hot. If it works reliably, stay with it.
EDIT: Their Uno page warns against overheating the board, so I would test it for a short while and make sure there is no overheating or strong "plastic" smell coming from the board. If there's enough heat to worry, then it's best not to run like that for extended periods.
If 18V is too high, you could get a power resistor (I'd guess say a 10 watt resistor around 24 ohms) to waste approximately half an amp from the power supply. Connect this to the supply, in parallel with the Arduino.  It's wasteful (unless your room needs heating anyway) but will lower the voltage (that reaches the Arduino) a little.

Thank you. I should have mentioned I mean 24/7. Probably a power resistor is the way to go. And no, the room is in no need of heat; we run A/C almost 9 months of the year! So I figure it wastes about double, since it burdens the A/C as well. Partially related (because I like this topic): While the power isn't wasted if heating is desirable, there are more efficient heating methods of heating. Thus, we can't fully shrug it off if we're using a more efficient heating system to heat the room.

By the way if the most efficient performance is required, I would actually recommend getting a 12V supply that is better regulated. You then won't need to waste heat. Or build/buy a switching type converter to bring the current 12-18V down to 5V.  (But both of these are going off the topic.)

Fortunately, power efficiency isn't much of an issue. However, wouldn't a regulated power supply simply waste the power itself (assuming it wasn't a switching regulator)? I'll revisit this answer when I settle on a solution. If you know an advertised power dissipation for the Arduino's regulator, that would be nice (I couldn't find it, though probably there would be a way to look at the Arduino's hardware design and find out what regulator they used).

Because the Uno regulators are said to get hot, I simply assume they're the "standard" kind of linear regulator which wastes any excess voltage as heat. Say it reduces 18V to 5V, it's wasting over two thirds of the total DC input as heat. So a suitable switching regulator unit would be more efficient and run cooler, but also more expensive. (Admittedly I've only cared about this on battery operated applications.)

I'd measure the voltage while attached to the Arduino board. A small load could already bring the voltage down enough to be acceptable.

Well... I think my multimeter lied.Or the power adapter decided to behave. More likely the multimeter; the ohm meter is broken but the volt meter seems to work (usually). It registers 12.34v when the Arduino is running, and only slightly more with no load (the other day it was showing 18v, or for a few moments 20v). Had it been 18v, I think I would have used two 1/4Watt 220 ohm resistors in parallel, to drop the voltage by 5.5v. Then if the voltage drooped to 12v, it would still get 6.5v. Running at 0.05A that shouldn't be much of a problem. Thanks for the help, and sorry for the mistake.

authors: สุทธิชัย อนัมบุตร