text:
Enabling quicker and more accurate MindWave Mobile detection?
Currently I am trying to get a Mindwave Mobile device to operate with an Arduino Uno. I'm following the guide here.
However the sample code given doesn't work very well. I have been trying to get a more consistent output but to no avail.
MindWave Code :
#include <SoftwareSerial.h>     // library for software serial
SoftwareSerial mySerial(5, 6);  // RX, TX
int BAUDRATE = 57600;

// checksum variables
byte payloadChecksum = 0;
byte CalculatedChecksum;
byte checksum = 0;              //data type byte stores an 8-bit unsigned number, from 0 to 255
int payloadLength = 0;
byte payloadData[64] = {0};
byte poorQuality = 0;
byte attention = 0;
byte meditation = 0;

// system variables
long lastReceivedPacket = 0;
boolean bigPacket = false;
boolean brainwave = false;

void setup() {
  Serial.begin(57600);       // Bluetooth
  delay(500);
  mySerial.begin(4800);      // software serialz
  delay(500);
  Serial.print("Communicating... ");
  mySerial.print("Communicating... ");
  mySerial.println();
}

byte ReadOneByte() {
  int ByteRead;
  // Wait until there is data
  while (!Serial.available());
  //Get the number of bytes (characters) available for reading from the serial port.
  //This is data that's already arrived and stored in the serial receive buffer (which holds 64 bytes)
  ByteRead = Serial.read();
  return ByteRead; // read incoming serial data
}

unsigned int delta_wave = 0;
unsigned int theta_wave = 0;
unsigned int low_alpha_wave = 0;
unsigned int high_alpha_wave = 0;
unsigned int low_beta_wave = 0;
unsigned int high_beta_wave = 0;
unsigned int low_gamma_wave = 0;
unsigned int mid_gamma_wave = 0;

void read_waves(int i) {
  delta_wave = read_3byte_int(i);
  i += 3;
  theta_wave = read_3byte_int(i);
  i += 3;
  low_alpha_wave = read_3byte_int(i);
  i += 3;
  high_alpha_wave = read_3byte_int(i);
  i += 3;
  low_beta_wave = read_3byte_int(i);
  i += 3;
  high_beta_wave = read_3byte_int(i);
  i += 3;
  low_gamma_wave = read_3byte_int(i);
  i += 3;
  mid_gamma_wave = read_3byte_int(i);
}

int read_3byte_int(int i) {
  return ((payloadData[i] << 16) + (payloadData[i + 1] << 8) + payloadData[i + 2]);
}

void loop() {
  // Look for sync bytes
  // Byte order: 0xAA, 0xAA, payloadLength, payloadData,
  // Checksum (sum all the bytes of payload, take lowest 8 bits, then bit inverse on lowest
  if (ReadOneByte() == 0xAA) {
    if (ReadOneByte() == 0xAA) {
      payloadLength = ReadOneByte();
      if (payloadLength > 169) //Payload length can not be greater than 169
        return;
      payloadChecksum = 0;
      for (int i = 0; i < payloadLength; i++) {     //loop until payload length is complete
        payloadData[i] = ReadOneByte();             //Read payload
        payloadChecksum += payloadData[i];
      }
      checksum = ReadOneByte();                     //Read checksum byte from stream
      payloadChecksum = 255 - payloadChecksum;      //Take one’s compliment of generated checksum
      if (checksum == payloadChecksum) {
        poorQuality = 200;
        attention = 0;
        meditation = 0;
      }
      brainwave = false;
      for (int i = 0; i < payloadLength; i++) { // Parse the payload
        switch (payloadData[i]) {
          case 02:
            i++;
            poorQuality = payloadData[i];
            bigPacket = true;
            break;
          case 04:
            i++;
            attention = payloadData[i];
            break;
          case 05:
            i++;
            meditation = payloadData[i];
            break;
          case 0x80:
            i = i + 3;
            break;
          case 0x83:                         // ASIC EEG POWER INT
            i++;
            brainwave = true;
            byte vlen = payloadData[i];
            //mySerial.print(vlen, DEC);
            //mySerial.println();
            read_waves(i + 1);
            i += vlen; // i = i + vlen
            break;
        }                                 // switch
      }                                   // for loop

/*
      if (bigPacket) {
        if (poorQuality == 0) {
        }
        else {                            // do nothing
        }
      }
*/
      if (brainwave && attention > 0 && attention < 100) {
        mySerial.print(attention, DEC);
        mySerial.println();

        Serial.print(attention, DEC);
        Serial.println();
      }
    }
  }
}

Often, the serial monitor stops display new values that stems from the Mindwave. Any suggestions on how I could modify the code to get it to run more smoothly will be greatly appreciated.

No use in reinventing the wheel!

Brain is an Arduino Library for parsing data from Neurosky-based EEG
  headsets. Tested units include the Star Wars Force Trainer and Mattel
  MindFlex.
It's designed to make it simple to send out an ASCII string of
  comma-separated values over serial, or to access processed brain wave
  information directly in your Arduino sketch. See the examples for code
  demonstrating each use case.

https://github.com/kitschpatrol/Brain
Install the library, and set it up like this:
#include <Brain.h>

// Set up the brain parser, pass it the hardware serial object you want to listen on.
Brain brain(Serial);

void setup() {
// Start the hardware serial.
Serial.begin(9600);
}

void loop() {
// Expect packets about once per second.
// The .readCSV() function returns a string (well, char*) listing the most recent brain data, in the following format:
// "signal strength, attention, meditation, delta, theta, low alpha, high alpha, low beta, high beta, low gamma, high gamma"
    if (brain.update()) {
    Serial.println(brain.readErrors());
    Serial.println(brain.readCSV());
    }
}

Can't guarantee that it will work, but if you have the TX pin of the bluetooth hooked up to the RX pin of the Arduino I'm pretty sure it will work.

I have just spotted this question because I had a similar issue: the while condition reading Serial data is blocking.
I've rewritten the parsing part a little bit, which you can see here.
This makes it smoother to run things in parallel, but it takes about the same time to accumulate a big packet of brainwave data.


text:
Control arduino with keybaord via computer
I'm brand new to arduino but I'm trying to figure out how to set up a WASD steering system for my robot I made.
I have the physical setup all ready but I don't know the code to use that would allow me to use my computers keyboard. I would like to still have my keyboard attached to my computer while I do this. I.E. I don't want to manually plug the keyboard into arduino.
I asked this on Robotics stack exchange but they said to ask here.
A list of functions/blocks Iof code that is applicable would be the best answer, but I'll take anything that'll get my bot moving :)
Edit I'm using a wireless keyboard, but my arduino is connected via USB.

If you want the keyboard to remain connected to the computer then you need to have the computer tell the Arduino what to do.

Which could be as simple as opening a terminal program such as the IDE's serial monitor and having it pass keystrokes down to the arduino.

You did not mention what kind of communication you intend to setup between the comuter and Arduino: serial (USB), WiFi, Bluetooth... All code needed will first depend on that!

@IgnacioVazquez-Abrams Yes that right. how would I do that. like I said, I not fluent with the language yet. I do Python and Basic.

The problem with using the keyboard is the device would have to be tethered to your computer. If you mean for this "robot" to be an explorer, that limits its choices. If it's an arm or something that stays in place, you're fine using the typical serial libraries to monitor your keyboard for input like Chris suggests.
Unfortunately, I don't know of any way to simply plug in the USB keyboard and take in keys. Usually, serial communication is processed between two systems much like two people texting each other. When you see the light blinking on your phone, you know you have a text and how to open it to retrieve the message. In the case of the Arduino, it's checking for a flag bit called RX for the received message and flags a bit for transmitting a message (TX). Each system then pulls down its message and interprets it. In the case of your sketch, you'll be looking for this flag and schedule an action whenever it's checked. Read about Serial communications here and work through the examples to get a feel for it. Because you probably want a real-time response, it might be worth your while to check out interrupts, as well. These are sudden events that get flagged (such as receiving your text) and get handled immediately instead of waiting for the program to refresh and search for the values manually. As a final note, baud rates are the calculated time frames you and your recipient agree on. It would be difficult to receive a full message if you kept cutting off your friend, so it is with computers. This stuff can kind of be tricky at first, but keep at it. Nothing is more ridiculously satisfying than getting that response character from your device.
There's a neat tutorial for getting your Arduino to work through your iPhone here, but it requires an ethernet board, which means a router and wireless board.
Without knowing what you intend to do with it, it's hard to say how to help, but I hope this gets you into it.

source: Stack Exchange

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

sort: votes


text:
Self answering a Intercom and playing louldy for person to response
We have two labs - one in 1st floor and other at 2nd floor. We are connected by intercom - both the labs has one device each. The issue is that the person who sits near the intercom is busy through out day answering the intercom and reaching out to the person for whom the call is made for.
This is very tiresome and hence I wish to automate this. I have an Arduino Mega 2560 board. My plan is to make Arduino receive the call ask for the person whom the caller is reaching out and play the name loudly over speaker in all rooms of labs (to attended the phone). If the user does not turns up even after 3 repeated times of calling - disconnect the call. If the user answers the phone by picking up the receiver then turn the conversation speaker mode off until call has not ended.
I have Arduino Mega 2560 board which has 4 serial ports but I am not user what would be the circuit to make this functionality workable? What are the extra h/w required and concept of its implementation.

There are several components here, each can be pretty complex by itself; do you want to programatically voice-recognize the person's name? do you know what interface the intercom is using? POTS? do you want the Arduino to play a wave files with every name pre-recorded or do you want voice synthesis? will the person/user answer from his desk or should he reach the intercom itself?

No I do not want to recognize any user voice - it just that when intercom rings the playback should state - "Whom do you want to speak to?". The user would reply with a person name. This name has to be played on an Audio system for the person to attend the call

and the intercom is plain old telephony system or some kind of digital system? if digital, which kind?

Well its plain old telephony type

Let's try to break it down to several components:

Interfacing with POTS (Plain Old Telephony System):
There is a nice article by Joe Doll describing how to interface an Arduino and POTS. POTS involves high voltage during both idle and ringing time (48 V DC, superimposed 90 V AC) and the circuit itself is mostly analog. You can find the required parts and their values in his article, which goes down into the nasty details in a spectacular fashion. Here is the analog circuit, involving the Arduino, from his post:

Consider that there are other projects performing similar task in a different manner, like this one, and this one which specifically explains how to record sound from an old rotary phone.

Play/Record sound from Arduino Mega 2650:
There are many projects that describe how to Play or Record sound using Arduino. Most involve a SD card to store the wav files. There is also the option of an MP3 shield, that comes with a pre-built SD card slot, such as this one. They are fully documented and are easy to interface with.
Code that encapsulates the Logic:
Here you could decide how many times the Arduino should play the recorded name, and what happens if the user won't answer. The disconnection will be done utilizing the POTS interface you created in bullet #1. In addition, you should handle the logic of what happens when the user does answer. It is not clear what you mean by 'receiver', but if you plan to have a remote extension or similar, some extra work will be required.

As a side note, it might be easier to create/re-use a walkie-talkie kind of wireless communicator, accompanied by an Arduino, to signal or broadcast the names of the people called. This might not include reuse or interfacing with the current intercom device, but by thus I believe it will make development easier and faster.

Thanks for all the information and links. Can you please let me know how to use Arduino with walkies-talkie for the same functionality?

it depends on many factors; what kind of walkie talkie and if you interface it or build it yourself. There are many projects on the web. I suggest you take one as an example, study it, and open specific questions when you're stuck

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


text:
Programming bluetooth module JY-MCU v1.06
I have a popular bluetooth module JY-MCU version 1.06 (picture below). Before i insert it to my arduino project I want to configure the name, bound speed and the pass code using usb-to-serial link. But I am facing a problem where the device does not respond to commands. Please let me explain.
I send the module to programming mode by applying +5V on 'key'
Then I send commands using CoolTerm program:
AT+NAMEmyArduinoProject
> OKyour set name

Ok. setting the name works as expected. But that is the only thing that worked for me. Other commands give no response:
AT

AT+BAUD2

AT+VERSION

AT+VERSION?

Maybe you had this happen to you? I am I sending wrong commands or doing something wrong? Please help me to figure out how to control this module.

I've heard how sometimes you have to put it into "AT mode" by pulling up a pin to HIGH. It might be like the "KEY" pin (not entirely sure).

Just a comment on configuring these boards: there is no provision for resetting them to default- or factory-settings. They remember only their most recent settings. Either write down how you last left it or always use it the same way - the serial settings especially! The only alternative, if you've forgotten the last settings, is to run a program that tests combinations of baud and serial-framing until it can establish communication with the device and set it to your new preferences. Glad you got yours sorted out!

I believe that the active IV on this is also known as the HC-06.  You may also want to study relevant data sheet information on that device.

The board is actually called a Bluecore CSR Ext 4. Collioquially its known as an hc-05 bluetooth module. The jy name is tge breakout board it sits on

OK, I figured it out. It looks like CoolTerm was sending wrong line endings. Thus the only command that worked was name change as it interpreted the extra symbols as part of the name specification. Now I am using in built Arduino serial communication and it works like a charm!

The protocol is peculiar.
You are to send the command unterminated within one second.
For example the AT command comprises the two characters AT and nothing more, no line ending at all. And the command must be completed within one second.
So,
AT[cr][lf] will just be ignored.


text:
Arduino two Ethernet shields
Is it possible to connect two Ethernet shields to arduino? And if yes, how can I distinguish them in the code?

You need to move the SS pin for one of the shields (Arduino pin 10). That way you can select which shield you want to talk to.

I don't think you can do this because the Ethernet.begin statement isn't an instance of Ethernet so I don't think you can do this.

Technically it is possible. Maybe you will have to  write your own library. But... Why? Why do you need two ethernet shields? I'm pretty sure the main problem is another one... Please tell us what you really want to achieve, so smarter solutions can be suggested (see The XY Problem). I'm telling you this because even if you have two shields you won't be able to do much work with them...

The ENC28J60 Shields have a Chip-Select-Pin (CS) so you could select between the two shields with this.

I'm using the EN28j60 with the Ethercard library and I'm not sure if this could handle two Ethernet shields because you have to set the CS pin at init on the first call in the function, and can't change it at runtime.

As I know you can High or Low any pin at runtime.

As far as I know, the library doesn't have any provision to use multiple shields/modules because I tried to do it and it kept disconnecting.
Let me know if you had any success doing that.


text:
USB BUB II - Misconnection and no longer uploads
I accidentally misconnected a USB BUB II to a Arduino RBBB (atmega 328), and it no longer uploads code. Here are the symptoms, I think the BUB II is fried. I am using Ubuntu 14.10.

Code won't upload with error ser_recv(): programmer is not responding
The RBBB board will reset is I hit the button. Evidenced by the LED flashing in port 13
Prior code runs as expected
dmesg behaves normally upon USB connection
When I short the Rx and Tx terminals of the BUB II, I can send instant reply messages via the Serial Monitor

Does this sound like the USB BUB II is broken? Or is is possible that some component on the RBBB board is fried?

Well, I asked too soon. I tend to do this.
I had to switch the board configuration to Arduino Uno and it worked


text:
Programming Arduino
I'm new to electronics. Professionally I'm a software developer. I want to know whether it is possible to program Atmel AVR 8-bit and 32-bit Microcontrollers using Arduino IDE. If yes could any one guide me on the process or direct me to any site where I can learn about it.

You can Google AVR. There are tons of tutorials. Google is your friend.

Yes I do have winavr to program it but I would like to know whether Aurdino programming language can be used.

Understood. Just to be clear, there is no such thing as an Arduino programming language. You can program an Arduino with c or cpp with the Arduino library.

"Arduino" is not a programming language. It's C++ with an IDE that does most of the drudge work of dealing with hardware and libraries.

Downvoted because, well, it's a lousy question. You need more detail. This is not the kind of question I would expect from a software developer with professional experience.

Yes, it is possible. In fact, this is how the whole 'Arduino' concept works - programming 8/32 bit AVR microcontrollers with the Arduino IDE.

program Atmel AVR 8-bit and 32-bit Microcontrollers using Aurdino IDE

This has two parts actually:
1. Generate compiled HEX targeting AVR
Using the Arduino IDE you could utilize the Arduino libraries (aka working with assist utility functions like digitalWrite for example), which are built on top of the AVR tool-chain. The official Arduino IDE comes with pre-built support for several 8-bit/32-bit Atmel AVR micro-controllers, the full list of supported boards can be found on the Arduino official website or in this Wikipedia page.
You did not specify a specific MCU, therefor you should check if the MCU you would like to work with is in that list.
2. Uploading an Arduino sketch to a compatible AVR
Arduino IDE uses avrdude under the hood. avrdude is

an utility to download/upload/manipulate the ROM and EEPROM contents
  of AVR microcontrollers using the in-system programming technique

(From their website).
The best place to start is the official Arduino.cc website, in the 'Getting Started' section. If you haven't picked any specific Atmel AVR chip yet, consider that each has slightly different features, size, I/O pins etc. so make sure to research a bit before purchasing one (reference the table in the Wikipedia link above to compare between the different kinds).

http://arduino.cc/ is good place to start. It includes articles about how to get started, library references, and user forums. The Arduino IDE will certainly get you started, but as an experienced developer you'll most likely hit its limitations pretty quickly.
Later, or quite possibly sooner(!) you can use same toolset (compiler, loader, libraries) in several less limiting environments: Eclipse IDE, edit/make at the command line, and Atmel's AVR Studio. C and C++ are mainstream; I've seen references to the existence of (but never tried) AVR Forth and AVR python.
Though you'll see occasional references to an 'Arduino language' it's really nothing more than C++ with some attempt to be smart about detecting references to library packages and auto-inserting the relevant #includes.
You probably won't want to take advantage of such shortcuts, and keep to good programming practices, if you think you'll ever want to move up from the Arduino IDE.
I personally use Eclipse (supplementing with a few command line tools) and I'd recommend it once you've tried the Arduino IDE.

Just to complement the other responses. You can program some AVR chips using the Arduino IDE, but for it to work out-of-the-box just by using a USB cable it needs to be an Arduino or "Arduino compatible" board, mostly because these come with the Arduino Bootloader.
The bootloader is a small piece of software that runs at power-up and is responsible to load your program into the chip (as well as other configuration stuff, for more info read the previous link). If the AVR chip does not have the bootloader already flashed, then you will have to use a programmer (connected to its ISP pins) to burn it first.
So, it's not like you can just buy random AVR chips or development boards online and start using them. But taking in consideration the wide selection of official boards and "Arduino compatible" ones, you should be able to find something to fit your needs.

Although if you have a programmer there's no need to have a bootloader at all, since the IDE supports uploading the code via programmer.

Also, you can also buy bootloader-loaded chips, and you can program a chip with another Arduino or your homemade-duino.

Thanks  Ignacio Vazquez-Abrams just for clarification if I have Arduino programmer I can program my Atmel Avr MCU without a bootloader.


text:
SMlib State Machine Library not working as expected
I have the following setup and sketch.
The problem is that when I click the button it works sometimes, but other times it executes On Off straight after On as if it's executing twice.
This is after pressing the button only 7 times:
Off
On
Off
On
Off
On
Off
On
Off

I thought that was the whole point of a state machine? That it continues to execute the next state (not multiple times at random).
Very very confused with this one.

//http://www.arduino.cc/playground/uploads/Code/FSM.zip
#include <FiniteStateMachine.h>
//http://www.arduino.cc/playground/uploads/Code/Button.zip
#include <Button.h>
//http://www.arduino.cc/playground/uploads/Code/LED.zip
#include <LED.h>

const byte NUMBER_OF_STATES = 2; //how many states are we cycling through?

//initialize states
State On = State(ledOn);
State Off = State(ledOff);

FSM ledStateMachine = FSM(On);     //initialize state machine, start in state: On

Button button = Button(2, INPUT_PULLUP); //initialize the button (wire between pin 12 and ground)
LED led = LED(13);                 //initialize the LED
byte buttonPresses = 0;            //counter variable, hols number of button presses

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

//poor example, but then again; it's just an example
void loop(){
  if (button.uniquePress()){
    //increment buttonPresses and constrain it to [ 0, 1 ]
    buttonPresses = ++buttonPresses % NUMBER_OF_STATES;
    switch (buttonPresses){
      case 0: ledStateMachine.transitionTo(On); Serial.println("On"); break;
      case 1: ledStateMachine.transitionTo(Off); Serial.println("Off"); break;
    }
  }
  ledStateMachine.update();
}

//utility functions
void ledOn(){ led.on(); }
void ledOff(){ led.off(); }
//end utility functions

Maybe you need some sort of debouncing? There's a tutorial on the Arduino site that I think will sort your problem out.

It doesn't look like the state machine is a problem here. More likely it's a problem of the button bouncing, as you don't have any code or circuitry to guard against it.
A button is typically a very simple component which doesn't necessarily make/break connections cleanly. Sometimes it will have a brief intermittent connection, making it look like it's been pressed/released multiple times. This is referred to as bouncing.
There's lots of material online about debouncing, whether in hardware or software. The top answer here may help:

Why does my sketch report too many button presses?


text:
Can I use an ATmega328 alone without anything and what is the max voltage I can power the atmega328 with
Okay 2 questions. If I am to replace the Arduino with an ATmega328 programmed with a standard blink on pin 13, is this configuration correct, do I still need oscillators and whatnot?

Second question is, what is the max voltage I can power the ATmega328 with without frying it? I have seen conflicting answers of this on the net. Some have said 5V while some say 6V can someone clarify?

Always go to the official source: http://www.mouser.com/pdfdocs/Gravitech_ATMEGA328_datasheet.pdf  (page 18)

@Jasmine alright it says 1.8v - 5.5v. okay thats one down. Then is this a possible way to hook up an atmega328 in place of the arduino?

Check this question: http://electronics.stackexchange.com/questions/53713/what-is-the-minimal-set-of-parts-for-a-circut-with-this-avr-microcontroller

My advice would be to research a standard board like Arduino, and keep what you feel is necessary. For example, keep the voltage regulator, but remove the blink led.

You also need to connect the other GND (pin 22) and the AVCC (pin 20).

The datasheet describes the electrical and clock requirements of the chip, and AVR042 describes the external hardware configuration required. Decoupling, analog voltages, external crystal or oscillator if required.

If you take a look at the Standalone Arduino on the Arduino website, then this is what you require:

Note that there is one slight error in the guide, which I have highlighted here, Arduino Standalone - photo shows incorrect pin wired to MOSI.
There is a video on how to achieve, more or less, the same thing, 1-Day Project: Build Your Own Arduino Uno for $5.

You only need all that if you're trying to replicate an Uno. The chip itself is fine with very few external components, all supply-related.

@IgnacioVazquez-Abrams - Good point. I was going to update my answer later - with the minimal setup (the timing caps etc. in lieu of the xtal) - but time isn't on my side currently. ;-)

@IgnacioVazquez-Abrams - I think I'm going to delete this answer, as it is wrong and Nick's answer is the right one. Mine is just cluttering up the question :-)

I have a page describing How to make an Arduino-compatible minimal board. The minimal setup would be:

That excludes the circuitry for uploading your code.
By the way, in the image in the question you have an LED with no resistor. That will damage both the LED and the Atmega328. You need a current-limiting resistor.

do I still need oscillators

Not if you program the fuse to use the internal oscillator.

Some have said 5v while some say 6v can someone clarify?

The datasheet says 1.8 to 5.5 V operating range with an absolute maximum rating of 6 V.
This is what the datasheet says about absolute maximum ratings:

This is a stress rating only and functional operation of the device at these
  or other conditions beyond those indicated in the operational sections of this specification is not implied. Exposure to absolute maximum rating conditions for extended periods may affect device reliability.

Page 2 of the datasheet says:

Operating Voltage:
1.8 - 5.5V

That is poor positioning of the decoupling capacitors since there are large high-frequency loops. Also, the distance between the ground pins means that some of the peripherals on the chip will have a slightly different ground potential.

Ach, I knew I should have re-taken that photograph! I'll get onto it. The other photo currently posted seems to have the caps even further away though. :P -- I'm not sure what you mean by the distance between the ground pins. What would you do differently there?

I use a very short wire going directly over the chip to connect them.

I've redone the photo with the decoupling capacitors adjacent to the pins. I haven't put the short wire in, as I think that would just make the photo look cluttered. I'm not sure if the different ground potential for analog ground would make a lot of difference to the operation, perhaps the ADC readings would be affected slightly.

It's not "analog ground", it's ground for the peripherals that happen to be on that side of the die.

Oh, OK, I suppose that makes more sense.


text:
How to change input pin of FreqCounter Arduino Uno/Dumilanove library?
The following link to the library defines arduino pin 5 for input pin for signal.
https://www.pjrc.com/teensy/td_libs_FreqCount.html
But the problem is I'm using an 16x2 LCD display with the arduino pin 5. The display needs pin 5 to work. So the question can solved in two ways,to both of which I don't know the answer.
1. Change LCD pin number to other pin. (Tried it was a failure. I've probably done it wrong)
2. Change the input pin for the freqcount library.
Any idea how to get past this bottleneck?

how did you try to change the LCD pin to other pin? can you show a minimum of code to demonstrate?

I've used this to try changing pins. LiquidCrystal lcd(12, 11, 4,3 , 2, 1); in place of LiquidCrystal lcd(12, 11, 5,4 , 3, 2); This fails for some reason. Nothing appears on the screen.

The library makes use of the hardware peripheral Timer 1 which has its input on pin 5 of the Uno.
It can't be changed.  You have no choice in that.
You will have to move the LCD to another pin instead.

any idea how to do that?

Like you tried before, but don't use pins 0 or 1 - they are shared with Serial and sometimes that gets in the way - especially if you're also using Serial for communication with a PC at the same time.

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


text:
Simple Text input using 5 buttons
So I have to get this function done but I'm not so bright and got confused.
(excuse me! I'm total noob)
The function is basically inputing text using five buttons, directional buttons and an ok button. The up and down buttons will be used to cycle through letters (a-z), and the left and right buttons will be used to control which array to cycle letters.
The control will be:

up button (up): ASCII-1 (z, y, x...)
down button (dw): ASCII+1 (a, b, c...)
right button (ri): array[i] ~> i+1 (go to next character/array)
left button (le): array[i] ~> i-1 (go to previous character/array)
ok button (ok): confirm text and changes the limit to stop function looping

I can't get it work with this code I write.

void intext()
{
  int lim=16;
  lcd.setCursor(0,1);
  lcd.print(input);
  for(i=0; i<lim ; )
  {
    if(digitalRead(dw)==HIGH)
    {
      if(input[i]<'a')
        input[i]='z';
      if(input[i]>'z')
        input[i]='a';
      input[i]=input[i]+1;
      delay(1000);
    }
    if(digitalRead(up)==HIGH)
    {
      if(input[i]<'a')
        input[i]='z';
      if(input[i]>'z')
        input[i]='a';
      input[i]=input[i]-1;
      delay(1000);
    }
    if(digitalRead(ri)==HIGH)
    {
      delay(1000);
      i=i+1;
    }
    if(digitalRead(le)==HIGH)
    {
      delay(1000);
      i=i+1;
    }
    if(digitalRead(ok)==HIGH)
    {
      lim=i+1;
      delay(1000);
    }
  }
}

void loop()
{
  lcd.begin(16,2);
  lcd.setCursor(0,0);
  lcd.print("Type your text:");
  intext();
  lcd.setCursor(0,0);
  lcd.print("Success!!");
  lcd.setCursor(0,1);
  lcd.print(input);
}

The result I wanted it to be is like this:
first you got the "type your text:" on the first row and blank in the second row.
our cursor is in the first column of the second row, so we can cycle through the alphabet letters. if you press right you can edit the next column of second row. you can get to the previous column in second row by pressing left. you can input up to 15 characters.
after done typing pressing ok will stop the typing and you will see "Success!!" in the first row and typed text in the second row.
Please help. I'm stumped.
Thank you.

Could you clarify the current behavior (you just said it does not work but that does not give any leads where to investigate)? Also, it would be good to see the setup() code and the variables declaration. Finally, a description if your wiring would be nice too, in particular you did not mention if you use pullup or pulldown resistors.

Thank you and sorry for not making things clear, I'm really clueless about things. I'm not very keen either so I just kind of trying to rewrite codes from scratch or trying to change how things will work. I guess you can check the complete code here http://pastebin.com/knbXsen4 ;;
My design... I'm not too sure if this good or bad, but after I tested it, and it does need debouncing. Here's the picture  http://i.imgur.com/KHn3zzh.png  again, thank you for your points. I'll try to be more informative and clear next time.

Several issues in the code you posted:

Every change to the text you do inside the for loop, will not be reflected to the LCD until the for loop will end (when i<limit will no longer be a true statement). You might want to add an additional code, inside the for loop and outside any of its conditional statements, that will repeatedly set the cursor and print input to the LCD. Something similar to the code you have prior to the for loop:
void intext()
{
  ... // rest of the code until the for loop

  for (int i; i<limit; )
  {
    ... // all the conditions for up/down/left/right/ok

    lcd.setCursor(0,1);
    lcd.print(input);
  }
}

Another problem is that when the user clicks left, the counter should be decremented, not incremented, and you should check for left boundary:
if(digitalRead(le)==HIGH && i>0) // left boundary check added
{
   delay(1000);
   i=i-1; // and not i=i+1;

}

After clicking Ok, and since the for loop does not increment i, the condition in the for loop (i<limit) will stay true, and the loop will not end until the user will click Right once more. To mitigate this, change the following
if(digitalRead(ok)==HIGH)
{
  lim=i; // and not: lim=i+1;
  delay(1000);
}

Otherwise, the user will have to click Right for completion, to increment i once more.

jfpoilpret comment about pull up/down is very important. Make sure you use pull up/pull down resistors in order to prevent input debounce (more details inside this link).

You're my light. Thank you.
Sorry for not giving a quality comment. I'm just... in awe..

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


text:
Why do you need a second resistor when using a photoresistor/LDR?
A photoresistor is already a resistor and will limit the voltage in the circuit. Why can't this be connected to a pin and measured? Why is a second resistor needed to connect the photoresistor to ground?

why we use resister in ldr circuit

The simple answer is that voltage is very easy for the Arduino to measure, while resistance is not, and most sensors such as Photoresistor (LDR), flex sensor, thermistors and more - are actually a variable resistors.
The main reason it's hard to measure resistance changes is that the Arduino (and most IC) contain a tiny system called Analog to Digital Converter (ADC). This system translates changes in analog voltage to a series of 1's and 0's that can be in turn converted to an Integer for example.
The ADC is designed to read voltage changes, and if we want to use the Arduino's analogRead (which utilizes the ADC) to get the Photoresistor readings for example, we will need a way to convert the changes in resistance to changes in voltage - and a voltage divider is the easiest way to do it.
It is true that the sensor is already a resistor, and as such it should change the voltage across it. But you would have trouble measuring the voltage changes, since there is no reference point except for Vcc (5V) and Ground:

In contrary, when using a voltage divider, you have a well defined reference point to measure the voltage changes:

This isn't strictly an Arduino question, but I appreciate that things like photo-resistors are common early projects for Arduino users.
Resistors (and other components) don't really limit the voltage in the circuit as such. Rather, each component in a series circuit gets a proportion of the total voltage. That proportion is determined by its resistance.
If you only have one component, then the entire voltage is dropped across it no matter what resistance it has. Changing the resistance in that situation would only affect the amount of current flowing through it.
You need the second resistor as a fixed reference point. You know how much voltage it will get if both resistances are equal, and that the relationship between voltage and resistance is (hypothetically) linear. You can therefore use that to figure out what resistance the other component has, e.g. the photo-resistor.
As a side note, the second resistor can also play an important role for safety. Without it, you could potentially end up with a short-circuit if the other component's resistance goes too low.

"would only affect the amount of current" - I think this is incorrect, like the case where you use a resistor next to a LED to drop the voltage. Also, A2D are high impedance, and low resistance shouldn't cause short-circuit.

@Omer "If you only have one component...". A resistor and LED together are two components. :) You're right that a short-circuit isn't an issue for a typical A2D, but that's not the only situation where you might want to use a photo-resistor or similar.

Right, missed that :)

Accurate measurement of resistance requires a precise current source (http://www.digikey.com/product-search/en/integrated-circuits-ics/pmic-current-regulation-management/2556448?k=current%20source).
Ohm's law, V=IR or  R=V/I states that for linear components, the value of resistance in the circuit can be estimated by the ratio of the applied voltage divided by the current.  With a simple voltage divider, as the resistance of the sensor changes so does the current in the circuit.  So measuring the voltage at the junction does not necessarily provide an accurate indication of the current in the circuit.  Both the imposed voltage and current should be controlled to obtain accurate measurements.

also another big reason for it is if you have just in series, a power source, an LDR and say a bulb, then the bulb may come on as soon as the LDR resistance gets low enough, then it will get brighter as the resistance keeps decreasing.
If configured with more resistors in a potential divider with a transistor and the bulb at the collector side, then you can vary the resistors to define the exact amount of light that will allow approx 1.6V (?)(whatever voltage turns the base into a conductor anyway), and therefore the light at which the bulb will suddenly turn on with a constant power supply direct from the power source through a fixed resistor if needed.
So in series an LDR will vary the current with light around the circuit, in a divider and transistor it functions as a light dependant switch

Unlike other electric components, a photoresistor(or light-dependent resistor,LDR,or photocell) is a variable resistor. This means its resistance can depend according to light intensity.

I will go first with half of the circuit diagram to understand clearly.
The resistance of a photoresistor decreases with increasing light intensity.
Strong Light —> LDR resistance(decreases to 0ohms) So the 10k(ohm) resistor sees closer to 5V.
The resistance of a photoresistor increases with decreasing light intensity.
Dim Light —>LDR resistance(increases to infinity).
So, the 10k(ohm) resistor only gets a little voltage.
Here is the full circuit diagram that you want to ask why second resistor is needed.

The key point is Arduino board also has Vcc(5V) and ground. So, there is no current if the potential difference is zero. Therefore, firstly, Vcc(5V) will flow through the photoresistor and go to the 10k(ohm) resistor.
Then, since there is a parallel circuit, arduino will get the same voltage as the 10k(ohm) resistor. So this LDR resistor does the function of a pull-up resistor which draws the current to VCC.

I THINK NONE OF THE ABOVE ANSWERS ARE CLEARLY DEFINING THE SOLUTION. I WILL ANSWER WITH RESPECT TO THE WORKINGS OF AN LDR CIRCUIT  WITH A LIGHT BULB THAT SWITCHES ON IN THE DARK AND OFF IN LIGHT.
LETS ASSUME THAT WE HAVE AN LDR ONLY CONNECTED IN SERIES TO A LIGHT BULB. THE LDR IS ALREADY ACTING AS A VARIABLE RESISTOR AND HENCE WILL ALLOW CURRENT TO FLOW IN THE PRESENCE OF LIGHT, (LIGHT INTENSITY BEING DEPENDANT ON THE CURRENT RESISTANCE) AND WILL LIMIT THE CURRENT WHEN IT IS DARK. THIS MEANS THAT THE BULB LIGHTS UP IN LIGHT AND IS OFF WHEN IT IS DARK. THERE IS NO PRACTICAL USE FOR THIS. I WANT THE BULB TO LIGHT IN THE DARK AND SWITCH OFF IN THE PRESENCE OF LIGHT.
SO WHAT I DO IS ADD A RESISTOR IN SERIES TO THE LDR. THIS RESISTOR HAS A FIXED RESISTANCE MUCH LOWER THAN THE LDR AT ITS HIGHEST RESISTANCE BUT MUCH HIGHER THAN THE LDR AT ITS LOWEST RESISTANCE. THE BULB ELECTRIC PATH IS CONNECTED BETWEEN THE LDR AND THE RESISTOR. PLEASE NOTE THAT THE RESISTOR IS PLACED ABOVE THE LDR.
NOW LOOK AT IT IN TERMS OF CURRENT FLOW.
WHEN THERE IS LIGHT, THE LDR RESISTANCE IS LESSER THAN THE RESISTOR. HENCE THE CURRENT FLOWS FROM THE BATTERY TO THE RESISTOR AND A SIGNIFICANT PORTION OF THAT CURRENT CONTINUES TO FLOW IN SERIES THROUGH THE LDR AND BACK TOWARDS THE BATTERY. THE REMAINDER OF CURRENT IS CARRIED OVER TO THE BULB ELECTRIC PATH WHICH IS NOT SUFFICIENT TO LIGHT THE BULB. HENCE THE BULB STAYS OFF IN THE LIGHT.
WHEN ITS DARK, THE LDR RESISTANCE IS HIGHER THAN THE RESISTOR. HENCE THE CURRENT FLOWS FROM THE BATTERY TO THE RESISTOR AND INSTEAD OF CONTINUING TO THE LDR WHICH IS CONNECTED IN SERIES, IT TAKES THE PATH OF LEAST RESISTANCE TOWARDS THE BULB. THE LDR RESISTANCE HAS EFFECTIVELY BLOCKED THE CURRENT FROM FLOWING THROUGH IT AND DIRECTED IT TOWARD THE BULB. HENCE THE BULB LIGHTS UP IN THE DARK.
IN TERMS OF PRACTICAL USAGE THIS IS MOST IMPORTANT CONCEPT. ALL OTHER REASONS FOR USING A SECOND RESISTOR WITH AN LDR ARE SECONDARY.

Why are you shouting?

This is not a practical use of an LDR and a (light) bulb. Using an LDR to effectively short out the light bulb in conditions of higher ambient light is extremely inefficient. In the context of Arduino projects, it is important to be able to derive a precise measure, converted relative to a voltage, of the light falling on the LDR.

This "answer" misses the point of the question and appears to have been written by a chat bot.


text:
7 Key Educational Piano with Capacitive Sensor
I am working on a project for grade 10 computer science.  I am supposed to make a piano that has 7 keys using a capacitive sensor, and the piano is supposed to teach you songs like Twinkle Twinkle Little Star by illuminating the LED corresponding with that key and then playing that tone on the speaker.  There is also a "random scales" part where you are timed and have to press the keys as fast as you can as they light up.  Unfortunately, I have come into a few problems.

I ran out of outputs and have to use a shift register. I have no idea on how to control each of the outputs.
When the game starts I want there to be 2 options a song and a random scales using randomSeed however I have NOT found a way for them to pick which option. I think I can do user input by typing or by them just pressing a key but I am not sure.
I am pretty new on Arduino so anything helps.

Finally I am using the Arduino Uno and that is why I am short pins because I have 1 gnd 1 speaker and the rest key inputs.

Are you sure you've run out of pins? Did you know you can use the analog pins as digital IO as well?

Thanks I didn't know about the analog, but there are only 6 analog pins and I need 7. Could I use one digital with 6 analog

Unfortunately you can't use digital pins as analog. If you need more analog inputs you'll probably need an external ADC (a shift register won't work for that).

I count 7 sense pins, 7 led pins, and one speaker pin. That is 15 digital pins. The uno has 18 pins available (don't use 0 and 1, as they are used for serial). Analog pins can be used as a regular digital pin. Your setup doesn't need the analogRead capability of the analog pins.

Thanks I did end up using a shiftregister I had got theL LED's corresponding w/ the keys fo

Thanks I did end up using the shift register and the have the LED's corresponding w/ the keys to show the user where to press. I need to find a way to see if the participant actually pressed the right keys and to hopefully give them a score at the end.


text:
What is the best vehicle platform to begin with (e.g. tracked, four-wheel drive)
Despite many articles on the topic of vehicle platforms, none of them seem to recommend the best one to start with. Later on I am sure I will seek an exact kind of chassis for autonomous vehicle construction, but now I am looking to learn the basics of this area of the Arduino world. If you could give me a simple recommendation for the general category of vehicle platform to use it would be much appreciated. I will be using an ultrasonic distance sensor coupled with a servo motor to detect obstacles, so it is a very simple project. Thank you so much.

SparkFun's Magician Chassis is a very simple, very flexible chassis for starting out. Also comes as part of the RedBot Kit.


text:
coding standards for bigger projects
I'm starting a decently sized project around arduino/ATMELavr, and I came to wonder if there are any commonly accepted C/C++ coding standards or style guidelines specifically aimed at embedded C++/arduino.
I've worked mostly with python recently, and came to love the PEP8 guidelines, and the associated pep tool (which checks syntax consistency with the style guide).
Similarly, I've used jslint and similar tools for javascript, as I find they help keeping your code base homogeneous, and avoid wasting time and commits on silly typos, and arguing over where the braces should go.
Any similar tools for C++ or more specifically arduino C++?

There is no such thing as "Arduino C++"; the magic is in the IDE, not the language. Also, you may want to try Programmers.SE for a style guide.

In my experience (15 years in industry, 30 total), this does not matter. What matters is having good developers who understand code written in ANY valid style. I currently work at a large bank, and there's 2 different bracket styles being used in our code, and nobody cares. Good developers don't care about this. We care a lot more about the code being valid, error-free, and efficient. If you do that, I don't care where your brackets are.
Yes, there are style guides for C++ but you don't need to use them. This is a good one though...
http://google-styleguide.googlecode.com/svn/trunk/cppguide.html
I am not aware of any style tools that integrate into Arduino IDE. There are some style tools that integrate into Eclipse though - and if this is important to you and your team, I strongly suggest using Eclipse for development. The Arduino IDE isn't really for large projects.
http://astyleclipse.sourceforge.net/ - but Eclipse doesn't really need this, it has a pretty good built-in formatter.

I don't intend to use the arduino IDE, it is pretty useless indeed beyond quickly testing some simple code. But I'm not a big fan of eclipse either, which I find clunky. The plugin you mention is built on top of http://astyle.sourceforge.net. There may be a way to use it as a validator rather than formatter.

Actually the Arduino IDE uses AStyle. In folder IDE/lib there's file formatter.conf file that you can edit if the default style doesn't suffice or fit

@Jasmine the google coding style is pretty much what I was looking for. http://google-styleguide.googlecode.com/svn/trunk/cpplint/ has the sort of tool I was looking for. Thanks for putting me on the right path!

Just as long as you remember that attempting to enforce a style will hurt you a lot more than it will help you. I hope I made that point clear. People with less experience will debate that, because they haven't witnessed the damage it can cause.


text:
What should be the delay to be given for reading accelerometer
I have five accelrometer sensors (MMA 7361) connected to the analog channels of Arduino Duemilanove. I am using the following code to read the data. (I am reading from only one axis from each sensor.)
#include <avr/io.h>
#include <avr/wdt.h>

int sensorValue = 0; // value read from the pot

void setup()
{
    Serial.begin(9600); // initialize serial communications at 9600 bps:
}

void loop()
{
    // read the analog values:

    int i=1;

    Serial.print("ACS#");

    for(i=0;i<5;i++)
    {

        sensorValue = analogRead(i);
        Serial.print(sensorValue);
        Serial.print("#");

        delay(10);
    }

    Serial.println("");

}

I am using a delay of 10 after reading each sensor. What should the value of the delay I should be using after reading one sensor to get the correct values from the sensors?

Why do you need any delay?

No delay is needed. Note however that the serial communication might not be able to keep up. If that happens your Serial.print calls will block/delay until the TX-buffer is no longer full. No big deal, but might be useful to know.

What are you trying to do with the data? This will help us give you an answer about sample rates

A delay is not needed.
What can be more beneficial, though, is making a dummy reading between each real reading.  This gives the ADC more of a chance to settle on the right reading without the Sample and Hold capacitor being influenced by the previous reading.
The simplest way is just to duplicate your analogRead line so it's done twice.

what is the time required for the ADC to settle on the right reading?

You'll find that kind of information in the datasheet. Cross-reference that with the analogRead() code to see what the current settings are.

@ukg You don't need to wait for the ADC to settle for any of the readings, each pin uses a different ADC, and they are continuously tracking the input.


text:
5V FTDI cable for Arduimu V3
I just recently bought an Arduimu v3. Rather annoyingly they did not supply an FTDI cable. I'm going for an FTDI cable where the I/O pins are configured to operate at 5v. I assume this is the right but I don't want to fry this board. Is this cable OK?

The board is a 5v one, so a 5v FTDI would be fine.

A 5V cable would be fine, or for about the same price, I would recommend an Adafruit FTDI Friend which is configurable between 5V and 3.3V.

Yes, as long as the board is 5V


text:
Several SIM with Arduino GSM/GPRS shield
For some purpose we need to communicate with Arduino using more that one SIM card, but still like to use an only GSM shield.
So, the idea is to use several SIM holders, to commutate each of six SIM wires to the sim we currently use. But it is still the question
1) How we should handle the gsm module itself? Is it okay for it if the SIM wire will be commutated to another SIM when it is in the middle of something? May be we should power off the module before, but it unclear how to do it programmatically when it is installed on the top of Arduina Mega 2560
2) should we commutate all six wires, or may be there are few signal ones and another shouldn't be never commutated?
3) what is the best way to do this commutation? Relays/transistor switches and so on?

Hi Ilya, have you finally implemented it? Could you please share the solution? Thanks

Hi, unfortunately no> I haven't implemented it :(

You should reset the shield, and keep reset, while switch sims. The reset is on pin 7.
If you look at the schematic, you can see there are only 3 lines, plus a GND and VDD. The GND and VDD you can probably share between the different sims. The SIM_RST, SIM_SCK and SIM_DATA need to be switched.
I think you should use a MUX for that, but that is not my area of expertise. Note that at least the DATA line is bi-directional.


text:
Help to understand multiple PWM working together
I'm very new to arduino related stuff so this question might be really easy to answer.
I don't understand how multiple PWM outputs are supposed to work. Look at the pic.

In the first(1) case we are using short signal width which would be close to motor staying still. In this case, as can be seen, short pulses follow each other, so does the code.
motor1.writeMicroseconds(shortWidth);
motor2.writeMicroseconds(shortWidth);
motor3.writeMicroseconds(shortWidth);
motor4.writeMicroseconds(shortWidth);

when motor4 ended it's output, motor1 starts it's pulse again causing non-problem consequent pulses.
In the second(2) case pulse is wider which corresponds to setting motor speed close to maximum. After motor1 finishes generating width, it's time for motor2 to generate one. But when it does, motor1's period comes to end and it has to start generate width again, but arduino is busy generating pulse of motor2.
How does PWMs work in this case?

are you trying to understand how the servo library manages multiple ppm/pwm signals at once? Those writeMicroseconds calls don't directly relate to any change in the output state of a pin. They just reconfigure the servo lib's signal generator that uses interrupts to change the pin when a certain amount of time has passed.

Thanks, that actually clears some things up. Still it's interesting to dig a little deeper and to know how same timer manages to make a pwm signal at once.

The timer interrupts routine get called every X microseconds. This routine increments an counter. Loops through all servos and sees if the PWM value for that servo is greater of less than the counter value. If less, write a HIGH to the pin associated with that servo, otherwise write a LOW. The actual code is a bit more difficult, but that is the gist of it.


text:
Cannot program Mega2560 using Atmel Studio 6.2 and avrdude
So I will admit that I am a noob to Arduino. I have some experience programming microcontrollers, and that was back in the day (about 4 years ago - such as the Freescale 68HC12) so up until this point I thought I was experienced enough to get this Arduino Mega2560 rocking with AVR C using Atmel Studio and avrdude by lunch...
Wrong.
I believe I'm getting held up at what's possible...
What I want to accomplish: Write and compile a program in AVR C within Atmel studio. Use the hex file that was built and download that to the Mega. (Keep in mind I was planning on using USB and Arduino as my programmer between PC and ATMega2560 as per this gentleman's example... https://balau82.wordpress.com/2011/03/29/programming-arduino-uno-in-pure-c/ -- however, I was not using his code and he was compiling using avr-gcc...)
Question: Is this possible?
Using avrdude when attempting to write the file I get this message... (and my blinking LED goes dark for a few seconds before returning to normal operation)

When I searched the internet for this issue it was never related to avrdude, but rather a communications issue. I've verified my bootloader is still ok (uploaded other sketches with no issues).
It's certain that I am missing something minor, but this is my first day using Arduino so go easy on me!
Thanks

try -c wiring instead of -c arduino. Thats what the IDE uses when uploading to a mega.

Unfortunately, I tried that and I get - avrdude: Can't find programmer id "wiring"

Ok so I've got it to the point of actually uploading to the Mega... and that happened using this line - avrdude -F -V -c wiring -p m2560 -P COM3 -b 115200 -D -U flash:w:tmp\BlinkLED.hex:i but unfortunately I'm getting no blinking! But I think that it's a code/ports pin thing. Thanks for the help guys!


text:
Weird Arduino timer behaviour
I am trying to output something every one second with the following code.
volatile uint64_t timerCounts = 0;
double timenow,pretime;
void setup()
  {
     Serial.begin(19600);
     noInterrupts();
     TCCR2A = TCCR2B = 0;
     TCNT2 = 0;
     OCR2A = 124; //Zero Relative 125
     TCCR2B = B00001101;  //prescaler = 1024
     TIMSK2 |= (1 << OCIE1A);
     interrupts();

     Serial.print("Begin... \n");
  }

  //**********************************************************************
  //  Timer2 Interrupt Service is invoked by hardware Timer 2 every 0.008s
  //  16Mhz / 125 / 1024 = 125 Hz    0.008s

  ISR(TIMER2_COMPA_vect)
  {
     timerCounts++;
     if (timerCounts == 125){
        Serial.print("1s");
        timerCounts = 0;
     }
  }  // end of TIMER2_COMPA_vect

  void loop()
  {

  }

In the above code, I have set the OCR2A(output compare register) to 124``, which is well below 256(2^8). A user defined counter is also used.
However, when I execute the programme, the interval between consecutive outputs is less than 1 second.
When I change it to timer 1, the interval becomes roughly 1 second.
When I change it to timer 0, the interval becomes longer than 1 second.
Anyone knows why?
Thanks.

OCR2A doesn't do anything because the timer is in 'normal' mode. In normal mode the timer will just count to 256, not 125. Which would mean the you get a serial.print every 2.05s.
You need to use CTC mode. Do this by setting the WGM21 bit to 1.
TCCR2A = _BV(WGM21);


text:
Is there any way that the values here be converted to another variable and not string?
int val1 =(mfrc522.uid.uidByte[0]);
int val2 =(mfrc522.uid.uidByte[1]);
int val3 =(mfrc522.uid.uidByte[2]);
int val4 =(mfrc522.uid.uidByte[3]);

String valA=String(val1);
String valB=String(val2);
String valC=String(val3);
String valD=String(val4);
uID=valA+valB+valC+valD;

The function above with mfrc522.uid.uidByte[x] is from the MFRC522.h Library by Miguel Balboa and it is initialized as byte there. But when I initialize the val1 to val4 as byte, the desired number doesn't appear. I don't intend to print the uID to serial (as someone may suggest that to readily print to serial as it converts it automatically to some ASCII strings), but instead in the client.print() of the Ethernet library along with other codes. I want to save it into another "greater" variable in terms of speed and memory allocation. The Arduino community warns about the use of String as it uses additional decoding which is not needed as well as may crash Arduino and make Arduino run out of memory. And somehow, I experience some lagging or hanging in the serial, which I thought maybe due to the use of Strings variable. Please help me. I've read some sprintf() concatenations and free() but not well documented, I'm quite confused on their explanations. :)

It sounds like you want to print the UID to serial. Have you tried using "mfrc522.PICC_DumpToSerial(mfrc522.uid);" ?

sprintf() is a nicer way to do that (imo), however, there's nothing wrong with what you've done-- if you don't have a ton more code, I'd continue to use it.
It's simple and that's a lot more important that speed most of the time. Also, the likely memory usage isn't enough to worry about.
In my experience, once I got past 1500 bytes SRAM (dynamic) memory usage, I ran into trouble. But my projects have a ton of code. I've read through the String class code and it's totally reasonable-- you're not likely to experience lag there.
My bet is that the lag is due to the timeout period, try making it smaller.

The UidByte[] is a 10 character array, loaded with the tag ID (this is an RFID reader) by the library.
Your code is attempting to put a character value into integer variables.
What you mean to do (I think) is to read the string as a number - this would be val=atoi(mfrc522.uid.uidByte) which relies on there being only numeric data in the ID string - or at least, will only read the leading numbers (if any). Also, there are 10 characters in the string - if you want to limit this to 4 you will need slightly more code.
If you have a tag on which you set the ID then this is usable, for your tags at least; but you can't rely on numeric uid's being universal.
If your intent is, as you say, to include it in a longer string, then the overhead of atoi is completely unnecessary and you should just handle it as a string. I think you have misunderstood the warnings about strings, there isn't a problem just handling short chunks of fixed-length data as strings, and I think you are inadvertently causing trouble by extra conversions.

The poster's concerns are based in real issues with dynamic memory allocation on small systems, and while they may not occur here is what could hopefully turn out to be a reuse-in-place allocation case, it is also not necessary to allocate a bunch of dynamic Strings to accomplish this goal at all.  If the size of the intended result is known or reasonably bounded, byte/character values can be directly written to appropriate positions in a C string.


text:
Struggling with SD card read on Arduino
I'm attempting to read data from my SD card, but I have strange behavior and can't figure out why this is happening.
I'm using CardInfo from the Arduino example and am trying to read the data from my SD card.
I'm faced with two different problems, but maybe they can be related:
1:  If I format my SD card from my Mac (FAT32), if my card is still empty, the program can read my card and output the right information. But if I add data from my Mac to the SD Card, card.init never initialise, and my data are never read (because of the hidden files). If I remove those hidden files, but let only the expected files be, the program never find them, like if my card was still empty. I don't know how to handle this.
2: From my Arduino, if I feed the card from the 3.3 V output, I get the

Card type: SD2 Could not find FAT16/FAT32 partition. Make sure you've
  formatted the card

It only works on 5 V (but the card type becomes SDHC). So I've tried to feed my card with another 3.3 V/5 V supply (my Arduino is grounded to this supply as well), but this is only working on 5 V. On 3.3 V my card isn't detected. My wires to the SD card are about 15 inch. I don't know if it can affect it drastically, but this is the only 'weird' thing about this circuit. By the way I naively think my 3.3 V supply should handle that.
Here are my materials:
- Arduino Duemilanove

For the SPI wiring I'm using pin 10 for SS.
Using the Cardinfo from the Arduino library.

And SD cars is powered by 3.3v, but also the I/O is 3.3v. You'd need a logic level converter to talk to it. Giving it 5v signals might screw up the SD card and result in wrong behavior. Not sure if that's the case here though. I haven't worked with SD cards.

I recommend you get a MicroSD card breakout board from that link, or something similar. That's around $US 15.

That includes the logic level converters. That particular board is for the **micro* SD card, but similar converters could no doubt be found for an SD card. Or use that one with a micro-SD card and just get an SD converter for when you plug it into the Mac.
I personally have used the SDfat library without any problems. However since he started rewriting it, I did have some issues. I have a backup of an earlier version which might be useful if the live library doesn't work for you.
You might be best off not formatting the card, but leave it as factory formatted. That will probably be compatible with the Mac, and also the SDfat library.

First of all, use 3.3 V. You need a logic-level converter.
Then you have to understand SPI is not the main protocol used by SD cards, and that Arduino should use SDSC to be sure, as some libraries are SDSC only.
Then you may have a hardware problem (from FAT32/SDHC library for Wave and other shields):

SDHC cards have a 3.3 V bus so most Adruino shields, like the Wave Shield, use a resistor voltage divider to shift bus levels from 5 V to 3.3 V. These voltage dividers can not meet the 10 ns rise time for most SDHC cards."

Also using an external power source may solve your trouble.

Mac OS X will default to using the GPT partition table to format the card, even in FAT32. This does not work with the standard Arduino library for SD cards I've found. You must use MBR.


text:
Arduino CC3000 websocket client
I am working for arduino websocket client with CC3000 wifi board from adafruit.
I have usde this websocket example as a reference and modified to work with cc3000 wifi board.
I am not able to connect to echo.websocket.org.
My code shows client is not connected and unavailable to communicate after sending the upgrade headers.
Here is the serial monitor response for the code:
echo.websocket.org -> Errno: 1
174.129.224.73-------------------------------------
Client connected
Sending websocket upgrade headers
Analyzing response headers
client not connected
client not available

here is the Arduino sckech:
#include <Adafruit_CC3000.h>
#include <ccspi.h>
#include <SPI.h>
#include <string.h>
#include <WebSocketClient.h>
#include "utility/debug.h"

// These are the interrupt and control pins
#define ADAFRUIT_CC3000_IRQ   3  // MUST be an interrupt pin!
// These can be any two pins
#define ADAFRUIT_CC3000_VBAT  5
#define ADAFRUIT_CC3000_CS    10
// Use hardware SPI for the remaining pins
// On an UNO, SCK = 13, MISO = 12, and MOSI = 11
Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS, ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT,
SPI_CLOCK_DIVIDER); // you can change this clock speed

#define WLAN_SSID       "UNSTOPPABLE"           // cannot be longer than 32 characters!
#define WLAN_PASS       "8878333344"
// Security can be WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA or WLAN_SEC_WPA2
#define WLAN_SECURITY   WLAN_SEC_WPA2

#define IDLE_TIMEOUT_MS  3000      // Amount of time to wait (in milliseconds) with no data
// received before closing the connection.  If you know the server
// you're accessing is quick to respond, you can reduce this value.

// What page to grab!
#define WEBSITE      "echo.websocket.org"
//#define WEBPAGE      "/testwifi/index.html"

// Here we define a maximum framelength to 64 bytes. Default is 256.
#define MAX_FRAME_LENGTH 64

// Define how many callback functions you have. Default is 1.
#define CALLBACK_FUNCTIONS 1

Adafruit_CC3000_Client www;
WebSocketClient webSocketClient;
/**************************************************************************/
/*!
 @brief  Sets up the HW and the CC3000 module (called automatically
 on startup)
 */
/**************************************************************************/

uint32_t ip;

void setup(void)
{
  Serial.begin(115200);
  Serial.println(F("Hello, CC3000!\n"));

  Serial.print("Free RAM: ");
  Serial.println(getFreeRam(), DEC);

  /* Initialise the module */
  Serial.println(F("\nInitializing..."));
  if (!cc3000.begin())
  {
    Serial.println(F("Couldn't begin()! Check your wiring?"));
    while(1);
  }

  // Optional SSID scan
  // listSSIDResults();

  Serial.print(F("\nAttempting to connect to "));
  Serial.println(WLAN_SSID);
  if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
    Serial.println(F("Failed!"));
    while(1);
  }

  Serial.println(F("Connected!"));

  /* Wait for DHCP to complete */
  Serial.println(F("Request DHCP"));
  while (!cc3000.checkDHCP())
  {
    delay(100); // ToDo: Insert a DHCP timeout!
  }

  /* Display the IP address DNS, Gateway, etc. */
  while (! displayConnectionDetails()) {
    delay(1000);
  }

  ip = 0;
  // Try looking up the website's IP address
  Serial.print(WEBSITE);
  Serial.print(F(" -> "));
  while (ip == 0) {
    if (! cc3000.getHostByName(WEBSITE, &ip)) {
      Serial.println(F("Couldn't resolve!"));
    }
    delay(500);
  }

  cc3000.printIPdotsRev(ip);

  // Optional: Do a ping test on the website
  /*
  Serial.print(F("\n\rPinging ")); cc3000.printIPdotsRev(ip); Serial.print("...");
   replies = cc3000.ping(ip, 5);
   Serial.print(replies); Serial.println(F(" replies"));
   */

  /* Try connecting to the website.
   Note: HTTP/1.1 protocol is used to keep the server from closing the connection before all data is read.
   */
  www = cc3000.connectTCP(ip, 80);
  if (www.connected()) {
    /*    www.fastrprint(F("GET "));
     www.fastrprint(WEBPAGE);
     www.fastrprint(F(" HTTP/1.1\r\n"));
     www.fastrprint(F("Host: ")); www.fastrprint(WEBSITE); www.fastrprint(F("\r\n"));
     www.fastrprint(F("\r\n"));
     www.println();*/
  }
  else {
    Serial.println(F("Connection failed"));
    return;
  }

  Serial.println(F("-------------------------------------"));

  /* Read data until either the connection is closed, or the idle timeout is reached. */
  /*  unsigned long lastRead = millis();
   while (www.connected() && (millis() - lastRead < IDLE_TIMEOUT_MS)) {
   while (www.available()) {
   char c = www.read();
   Serial.print(c);
   lastRead = millis();
   }
   }
   www.close();
   Serial.println(F("-------------------------------------"));*/

  /* You need to make sure to clean up after yourself or the CC3000 can freak out */
  /* the next time your try to connect ... */
  /*  Serial.println(F("\n\nDisconnecting"));
   cc3000.disconnect();*/
  // Handshake with the server
  webSocketClient.path = "/";
  webSocketClient.host = WEBSITE;

  if (webSocketClient.handshake(www)) {
    Serial.println("Handshake successful");
  }
  else {
    Serial.println("Handshake failed.");
    while(1) {
      // Hang on failure
    }
  }
}

void loop(void)
{
  String data;
  if (www.connected()) {

    /*   data = webSocketClient.getData();

     if (data.length() > 0) {
     Serial.print("Received data: ");
     Serial.println(data);
     }*/

    // capture the value of analog 1, send it along
    pinMode(1, INPUT);
    data = String(analogRead(1));

    webSocketClient.sendData(data);

  }
  else {

    Serial.println("Client disconnected.");
    while (1) {
      // Hang on disconnect.
    }
  }

  // wait to fully let the client disconnect
  delay(3000);
}

If anybody can guide me where I am wrong then it would be great help.I have taken reference code from brandenhall/Arduino-Websocket

Can you please add a wireshark sniff of what is going on?

Thanks for reply I am not getting what to do with wireshark. In my case my client code is not communicating with echo server. As I have put debug print, it got disconnected from the client after sending upgrade header.

Then print back the response from the server. And also what you are sending. (That is what wireshark do)

here the problem is i am not recieving anything from server. My client disconnected from the server after sending the Upgrade headers. that's why in wireshark i am not getting anything from server I think so.

Then post what YOU are sending!

here the problem is i am not receiving anything from server. My client disconnected from the server after sending the Upgrade headers. that's why in wire-shark i am not getting anything from server I think so.
here is code which do handshake with server.The problem is i am not receiving anything from server. My client disconnected from the server after sending the Upgrade headers. that's why in wire shark i am not getting anything from server I think so.
here is code which do handshake with server:

bool WebSocketClient::analyzeRequest() {
    String temp;
    int bite;
    bool foundupgrade = false;
    unsigned long intkey[2];
    String serverKey;
    char keyStart[17];
    char b64Key[25];
    String key = "------------------------";
    randomSeed(analogRead(0));
    for (int i=0; i<16; ++i) {
        keyStart[i] = (char)random(1, 256);
    }
    base64_encode(b64Key, keyStart, 16);
    for (int i=0; i<24; ++i) {
        key[i] = b64Key[i];
    }
    Serial.println(F("Sending websocket upgrade headers"));
    socket_client->print(F("GET "));
    socket_client->print(path);
    socket_client->print(F(" HTTP/1.1\r\n"));
    socket_client->print(F("Upgrade: websocket\r\n"));
    socket_client->print(F("Connection: Upgrade\r\n"));
    socket_client->print(F("Host: "));
    socket_client->print(host);
    socket_client->print(CRLF);
    socket_client->print(F("Sec-WebSocket-Key: "));
    socket_client->print(key);
    socket_client->print(CRLF);
    socket_client->print(F("Sec-WebSocket-Protocol: "));
    socket_client->print(protocol);
    socket_client->print(CRLF);
    socket_client->print(F("Sec-WebSocket-Version: 13\r\n"));
    socket_client->print(CRLF);
    Serial.println(F("Analyzing response headers"));
    //here it got disconnected
    while (socket_client->connected() && !socket_client->available()) {
        delay(100);
        Serial.println("Waiting...");
    }
    // TODO: More robust string extraction
    while ((bite = socket_client->read()) != -1)
    {
        temp += (char)bite;
        if ((char)bite == '\n')
    {
     #ifdef DEBUGGING
            Serial.print("Got Header: " + temp);
     #endif
            if (!foundupgrade && temp.startsWith("Upgrade: websocket"))
            {
                foundupgrade = true;
            }
            else if (temp.startsWith("Sec-WebSocket-Accept: "))
            {
                serverKey = temp.substring(22,temp.length() - 2); // Don't save last CR+LF
            }
              temp = "";
            }
if (!socket_client->available()) {
          delay(20);
        }
    }
key += "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
    uint8_t *hash;
    char result[21];
    char b64Result[30];
    Sha1.init();
    Sha1.print(key);
    hash = Sha1.result();
    for (int i=0; i<20; ++i) {
        result[i] = (char)hash[i];
    }
    result[20] = '\0';
    base64_encode(b64Result, result, 20);
    // if the keys match, good to go
    return serverKey.equals(String(b64Result));
}

authors: 摩登5娱乐代理--平台总代


text:
How to make arduino show cpu usage with 10 leds?
So i want to make arduino show my computer cpu usage with leds, for example if 10% then 1 led will light, if 50% then 5 leds, if 80% then 8 leds...

How you would do that depends completely on what OS you're using.

There's three basic steps you need to cover:

Get the CPU usage of your computer
Communicate that to the Arduino
Have the Arduino respond to the data

We can't really help you with step 1.  That's outside our remit.   You should head over to StackOverflow for that. How you would do it depends on your host OS since each one has its own way of reporting it.
For step 2 you would need to write software for your computer, incorporating what you have learned from step 1.  Once you have the correct data you need to send it over to the Arduino through its serial connection. You'd need to come up with a good way of doing that, but probably just sending the usage percentage as plain ASCII text separated by new-lines is probably simplest.
Step 3 would entail reading in the data you sent in step 2, deciding what the numbers you have got mean, and then turning on the relevant LEDs.
Another option, which might simplify things a little, might be to use something like Firmata, where your PC sends the instructions to turn the LEDs on and off, and the Arduino just becomes a kind of dumb interface that doesn't do much on its own.


text:
Why client.stop causes some significant delay to do another task in a loop?
void setup() {
    Serial.begin(9600);        // Initialize serial communications with the PC

    // disable SD SPI
    pinMode(4, OUTPUT);
    digitalWrite(4, HIGH);

    // disable w5100 SPI
    pinMode(10, OUTPUT);
    digitalWrite(10, HIGH);

    SPI.begin();                // Init SPI bus
    mfrc522.PCD_Init();        // Init MFRC522 card
    //Serial.println("Scan a MIFARE Classic PICC to demonstrate Value Blocks.");

    Ethernet.begin(mac, ip); //we used a STATIC address to start ETHERNET

    // print your local IP address:
    Serial.print("My IP address: ");
    for (byte thisByte = 0; thisByte < 4; thisByte++) {
        // print the value of each byte of the IP address:
        Serial.print(Ethernet.localIP()[thisByte], DEC);
        Serial.print(".");
    }
    // give the Ethernet shield a second to initialize:
    delay(1000);
    Serial.println("connecting...");
}

void loop() {

    // Prepare key - all keys are set to FFFFFFFFFFFFh at chip delivery from the factory.
    MFRC522::MIFARE_Key key;
            key.keyByte[0] = 0xFF;
            key.keyByte[1] = 0xFF;
            key.keyByte[2] = 0xFF;
            key.keyByte[3] = 0xFF;
            key.keyByte[4] = 0xFF;
            key.keyByte[5] = 0xFF;

    // Look for new cards
    if ( ! mfrc522.PICC_IsNewCardPresent()) {
        return;
    }

    // Select one of the cards
    if ( ! mfrc522.PICC_ReadCardSerial()) {
        return;
    }
    // Now a card is selected. The UID and SAK is in mfrc522.uid.

    // Dump UID
    //Serial.print("Card UID:");
    //Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : "");

    // In this sample we use the second sector (ie block 4-7). the first sector is = 0
    // scegliere settore di lettura da 0 = primo settore
    byte sector         = 0;
    // block sector 0-3(sector0) 4-7(sector1) 8-11(sector2)
    // blocchi di scrittura da 0-3(sector0) 4-7(sector1) 8-11(sector2)
    byte valueBlockA    = 0;
    byte valueBlockB    = 1;
    byte valueBlockC    = 2;
    byte trailerBlock   = 3;
    byte status;
    // Authenticate using key A.
    // avvio l'autentificazione A
    //Serial.println("Authenticating using key A...");
    status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, trailerBlock, &key, &(mfrc522.uid));
    if (status != MFRC522::STATUS_OK)
    {
        Serial.print("PCD_Authenticate() failed: ");
        Serial.println(mfrc522.GetStatusCodeName(status));
        return;
    }

   //No KEY B Authentication
   int val1 =(mfrc522.uid.uidByte[0]);
   int val2 =(mfrc522.uid.uidByte[1]);
   int val3 =(mfrc522.uid.uidByte[2]);
   int val4 =(mfrc522.uid.uidByte[3]);

   String valA=String(val1);
   String valB=String(val2);
   String valC=String(val3);
   String valD=String(val4);

   uID=valA+valB+valC+valD;
   Serial.print(uID);
   Serial.println();
   counter=counter+1;
   Serial.print(counter);
   //}
   Serial.println();

   // Halt PICC
   mfrc522.PICC_HaltA();

   // Stop encryption on PCD
   mfrc522.PCD_StopCrypto1();

   if (counter>first)
   {//delay ifs
       // enable w5100 SPI
       if (client.connect(server, 80)) { //start of IF
           Serial.println("connected");
           client.print("GET /accessdenyrfid.php?rfid="); //dont make these println
           client.print(uID);   //dont make these println
           client.print("&&");
           client.print("ip=mech1");

            //client.print( ip );
            //client.print("&&");
            //client.print("ipkey=");
            //client.print( ipkey );

            client.println(" HTTP/1.1");   //println
            client.println("Host: ");    //println
            client.print(server);//don't make println
            client.println("Connection: close");  //println
            client.println();   //terminates the query
            Serial.print("SENT");
            Serial.println();
            first++;
            Serial.print(first);
            Serial.println();
            // add this
            while(client.connected()) {
                while(client.available()) {
                    char ch = client.read();
                    Serial.write(ch);
                }
            }

           client.stop();
           client.flush();

       } //end OF IF
    }//delay ifs
}

The code above works perfectly with another php. that either saves or denies a card into a database. The arduino sends and receives data back and forth from and to php in less than a second. But the problem is that whenever the function client.stop is called. It takes approx. 8 seconds before another data is sent in the loop function. I need the loop to continue with just 2 second interval, which is enough or even faster. I don't think that the mysql query in the php is the one that makes it longer cause all the queries are made before the delay starts. (The server has already sent it's response, before the delay starts, which i think is in the client.stop.) Please help me on other alternatives on stopping the client or any way I can do this faster. Thanks, I'm really in trouble right now. I'm using Arduino UNO. Data sent back and forth are just a couple of letters and numbers.

Could you post the full code? There's a bit missing...

I would bet the problem relies on
if (counter>first)

As seems like you never reset counter, there might be weird things going on

Can you please edit your answer to explain why this causes the code in question and how it should be fixed? Thanks!

@AnnonomusPenguin Edited

I can't even see where counter is declared, nor first.


text:
Arduino Uno with SD, Cardinfo sketch how to list only visible files
There are two files (that can be seen on my computer) on my sd card, 6.bmp and example.txt (the latter written from my arduino). I have them connected to my arduino via LCSTUDIO breakout board (which surprisingly caused me no trouble at all).
When I run the example "cardinfo" sketch, the files it lists includes those two files along with tons of others, which I assume are just invisible from a personal computer.
How would I list only the files that can be seen from my computer (i.e. aren't inside any directory, but are just plain in the SD card)?
Using arduino UNO

Simple Answer: Don't think you can
Long Answer: Dont think you can, because, unlike an OS like windows, mac, linux, etc. The arduino just tales all the files. You could save those two files and format it as FAT16 though, then add the 2 files back on the sd and there you go.

Ok, I'm gonna go ahead and accept this,

Probably the best answer I can get for something thats apparently impossible,


text:
Arduino Leonardo on Win 8.1 COM port disappeared
I've been using an Arduino Leonardo on my Windows machine for a few days now without too much trouble but today the COM port disappeared. I've been able to successfully send sketches to the arduino and execute them so everything was working until recently. When I look in Device manager on the control panel there is no com port listed for the arduino. If I reset the device then a com port shows up briefly with "Arduino Leonardo BootLoader" but after a few seconds that disappears. I've tried USB2.0 and USB 3.0 ports on my PC and a different cable but to no avail. I don't have anything listed under "Other Devices" and I'm out of ideas for what could be the trouble.
I'm trying to get it recognised now as just the leonardo with nothing connected to any pin. Any ideas of what to try?

Strange, it's resolved itself/I resolved it. I don't know whether what I did was actually responsible for solving this but I'm back in business:
* I reset the board so that the bootloader appeared as a com port
* I set the arduino IDE to use the port that appeared for the bootloader
* I uploaded a simple sketch and pressed reset during the "upload phase" so that the port appeared during the upload
* the upload completed successfully and the arduino was back in the com port list
I'd still be interested to understand what I did that caused the problem in the first place but I suppose something was corrupted on the board?

Probably you had a sketck witch was messing with serial, like you forgot Serial.begin() or the while needed by it, also this reset is needed on the uno when write too much on serial.

You could be right. I have a button press to trigger some actions and I'd been monitoring the button status using a serial write. It could be I was hammering that method call or had messed something up around the serial comms.

Do note that on some example sketches the setup of the "Serial." function requires that there is special check for the serial port to be recognized/enabled (for the Leonardo only).  Have you actually run a serial sketch to see if the com port comes back?
Did you load any other software or run virus checks that might have interfered with the special USB/Com driver?
You might try unloading and reloading the special driver used with the USB.  Be sure to use the one specifically for Win8.

My suspicion is that the board is dead - I've tried to install to a Win 7 laptop which also doesn't recognise it except during the bootloader sequence. I can't load any sketch onto the board to test with since the board doesn't showup with a com port. so the IDE doesn't have anything to connect to.


text:
The Arduino robot tutorials describe a cord comming with the official robot, now I'm confused
I recently got the Arduino Robot and have been looking at the examples for the RobotLibrary. As I looked, I found something quite confusing (for me at least), a few of them describe connecting a sensor (like an IR sensor or Ultrasonic sensor) to a port with a cable that was provided with the robot. But I never received a cable. Which got me to question, what type of cable is this, because it is not the same cable you would use on an UNO, at least not according to the pictures. So does anyone know what type of cables these are and/or where I can get them? Thanks :smiley-mr-green:
Here are the pictures btw:

And the next one:

Usually, Arduino gives you the minimal board and sends you on your way. Reading over the instructions, I think they mean a cable that would have come with the IR sensor. That three-tone cord you see in the pictures are actually just three wires. You connect them as described if they came with the sensors. More likely, if they did not, you can use your own wires to connect these. Just be sure that you understand which is the ground (GND), power (+5V or some other +V), and signal. Usually, ground is denoted by the darkest color: black or brown; power is usually red, and signals can be any light color. USUALLY (READ about your device before you plug it in) ground and power are side-by-side for IR sensors, and signal is on the outside. Take a few minutes to Google up your device before plugging it in if you don't have documentation.
Good Luck!


text:
RGB fade program
I'm working on a function to fade RGB LEDs smoothly from one color to the next, so I thought I'd use a for loop  to increment each RGB value according with the set value. I've made the for loop as following:
for (redFadeCurrent, greenFadeCurrent, blueFadeCurrent;
   ((redFadeCurrent != redFadeTarget)&&
   (greenFadeCurrent != greenFadeTarget)&&
   (blueFadeCurrent != blueFadeTarget));
   redFadeCurrent = redFadeCurrent + redStep,
   greenFadeCurrent = greenFadeCurrent + greenStep,
   blueFadeCurrent = blueFadeCurrent + blueStep) {

    analogWrite(ledRedPin, redFadeCurrent);
    analogWrite(ledGreenPin, greenFadeCurrent);
    analogWrite(ledBluePin, blueFadeCurrent);
    Serial.print("Red: ");
    Serial.print(redFadeCurrent);
    Serial.print(" Green: ");
    Serial.print(greenFadeCurrent);
    Serial.print(" Blue: ");
    Serial.println(blueFadeCurrent);
    delay(3000);

    if (redFadeCurrent>redFadeTarget) {
        redStep = -1;
    }
    else if (redFadeCurrent<redFadeTarget) {
        redStep = +1;
    }
    else {
        redStep = 0;
    }

    if (greenFadeCurrent>greenFadeTarget) {
        greenStep = -1;
    }
    else if (greenFadeCurrent<greenFadeTarget) {
        greenStep = +1;
    }
    else {
        greenStep = 0;
    }

    if (blueFadeCurrent>blueFadeTarget) {
        blueStep = -1;
    }
    else if (blueFadeCurrent<blueFadeTarget) {
        blueStep = +1;
    }
    else {
        blueStep = 0;
    }

Problem is, when one of the values hit the target the code leaves the for loop.
I'm guessing the condition ((redFadeCurrent != redFadeTarget)&&(greenFadeCurrent != greenFadeTarget)&&(blueFadeCurrent != blueFadeTarget)) does not work.
Is there any way to work around this?
Thanks is advance.

Your code sample is incomplete the end of the loop is missing }.

You are correct, the problem is the condition inside the for statement.
Let's examine what happens when the red LED hits its fading target, which is, say, 100 (for the sake of the example, I will fabricate the other values):
for (...; (100 != 100) && (90 != 100) && (80 != 100) ; ... )

(100 != 100) -> FALSE
(90 != 100) -> TRUE
(80 != 100) -> TRUE

FALSE && TRUE && TRUE -> FALSE
The condition inside the for evaluates to FALSE, therefor the loop will exit.
If you want the loop to continue as long as there is at least one LED which hasn't hit the fading target, you should change the AND to OR:
((redFadeCurrent != redFadeTarget) || (greenFadeCurrent != greenFadeTarget) ||
   (blueFadeCurrent != blueFadeTarget))

Let's examine what happens now with the same values:
for (...; (100!=100) || (90 != 100) || (80 != 100) ; ...)

(100 != 100) -> FALSE
(90 != 100) -> TRUE
(80 != 100) -> TRUE

FALSE || TRUE || TRUE -> TRUE ==> The loop will continue.
And what will happen when all the colors hit the fading targets?
for (...; (100!=100) || (100 != 100) || (100 != 100) ; ...)

(100 != 100) -> FALSE
(100 != 100) -> FALSE
(100 != 100) -> FALSE

FALSE || FALSE || FALSE -> FALSE ==> The loop will stop since the condition will not evaluate to TRUE.

...That's kind of embarrassing!
Gotta do some exercises on my logic. :p
Thank you very much!


text:
Do addressable RGB's need to be programmed differently from normal RGB's?
I bought these rgb's from Sparkfun, however I have no idea how to hook them up or how to program them. Obviously the data sheet was somewhat helpful, however I have no idea how the IC's in the LED's work themselves or how to control them separately, or even how to string them together. My best guess is currently going for what the led's appear as in the example picture by connecting the first and last pins and putting the respective Vcc and ground pins to Vcc and ground.
Is there any good examples for hooking these up and coding them, or a basic understandable explanation for how they work?
Thanks, I can't find a great resource yet.

These are much different than "normal" RGB LED: they use the WS2812 chip, which is the same as the chip used in famous Adafruit "neopixels" strips, rings...
Wiring is simple. For all LEDs:

GND to 0V
VDD to 5V

For the first LED (connected to Arduino):

DIN to any Arduino logical output pin
DOUT to the 2nd LED you want to address (on its DIN pin)

For all but the first LED:

DIN to the previous LED DOUT
DOUT to the next LED DIN (or left floating for the last LED)

Programming neopixel is quite hard because timing of sent commands must be very precise.
I highly suggest to use Adafruit libraries for that.

Wiring is not the same. RGB addressable LEDs will need 12V, they draw some "extra" power over what the LED would draw by itself. See this: https://www.youtube.com/watch?v=h_GXhJeCDD0

I don't see anywhere in the datasheet mentioned the need for 12V: datasheet says 4.5V~6V. Personally, I have used neopixels rings with 5V without any issue.

The WS2812 itself can run on lower voltage, but the LEDs won't. EDIT: oh, you're right - that one from Sparkfun is special.

@Jasmine that's why it is always important to refer to the datasheet when you have it, that must be THE reference. No hard feelings though, your work on neopixels is interesting, thanks for sharing.

Does neopixel use either I2C or SPI? Or is it something else entirely? We're just learning about communication interfaces in my current classes.

No they use their own protocol.

It just uses "clocked" serial data. I didn't check the link at first, I just assumed he was using the same RGB strips everyone uses. Those individual ones are a major pain :)


text:
Why are LED 0 and 1 on as well?
I was just playing around a bit and ran into a strange problem. LED 3, 5, 6, 9 and 10 are on, as intended. For some reason LED 0 and 1 are on as well. Can someone explain why this is happening?
int ledPins[] = {3, 5, 6, 9, 10};
int pinCount = sizeof(ledPins);

void setup(){
  for (int i = 0; i < pinCount; i++){
    pinMode(ledPins[i], OUTPUT);
  }
}

void loop(){
   for (int i = 0; i < pinCount; i++){
     digitalWrite(ledPins[i], 1);
   }
}

What kind of Arduino are you using? Uno?

Yes, it is an Arduino Uno.

Can you show the wiring?

Sorry, that would be quite difficult at this very moment. Though, I tested with some different code, like very specific numbers, such as
digitalWrite(5, 1);

for example, then it only turns LED 5 on, and none of the others. It must be code related, I guess.

The behaviour of your program is undefined because you're reading past the end of your array.
In C/C++, the sizeof operator always gives you the size of something in bytes. It doesn't directly tell you the number of items in an array. Since int is usually 2 bytes for Arduino programming, the pinCount variable is actually being initialised to 10 (5 items x 2 bytes each).
The result is that each for loop is actually doing 10 iterations. The first 5 iterations are OK, reading correctly from the ledPins array. However, the rest of the iterations are reading whatever data happens to be in memory after that. This means it could be trying to initialise and switch on any pin, potentially including 0 and 1.
I can't guarantee that this is the source of the problem, but it's certainly very important to fix.
The solution is quite easy though. Divide the total size of the array by the size of a single element:
int pinCount = sizeof(ledPins) / sizeof(int);

Thanks for the help! That's some very important information right there. It doesn't completely solve the problem, but that's okay. I'm getting closer and learning more, that's what counts!

Actually with the 2 answers combined, the problem is pretty much gone. Thanks for the help everyone. I just had to initialize 0 and 1 as well, other than that it's fixed with this answer!

Alternatively use byte instead of int. So byte ledPins[] = {3, 5, 6, 9, 10};

Sweet! Thanks for the help, I will remember this!

Better, define a macro to do the calculation, e.g. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0])) and then use int pinCount = ARRAY_SIZE(ledPins); or just skip the pinPount variable all together and use the macro directly. See also this answer.

You haven't initialised the other pins at all; or included your circuit, but clearly you have LEDs on more pins than those defined (5 defined, 7 on).
The other LEDs are, therefore, in an undefined state - and may well be attached to pins set 'on' by default in your circuit. You probably need to either move 0/1 off the serial interface or explicitly set them 'off'.

That's very true, I thought I had to initialize them for them to become active in the first place. I do indeed have more than 5 LEDs on the breadboard, but was only going to use 5 of them.


text:
Decoding a RS232 message in Arduino
I have an Arduino Mega with an MaxBotix (MB7066) sonar attached, the sonar has the ability to send serial data with it's reading. It uses a asynchronous RS232 format, except the voltages are 0-Vcc. The output should be a capital "R" (ASCII), followed by four digits(ASCII) and a carriage return (ASCII 13). The baud rate is 9600, 8 bits, no parity with one stop bit.
What I get from the device is as follows: (sonarSerial.read() while sonarSerial.available())
43
192
6
6
179
89
30
0

What do I have to get to the information? Or is my sensor just retuning garbage?
Please see the code below:
#include <SoftwareSerial.h>

#define pin1 3
#define pin2 5 //pwm
#define pin3 6 //analog
#define pin4 10 //RX for sonar, TX for arduino
#define pin5 11 //TX for sonar, RX for arduino

SoftwareSerial sonarPort(pin5,pin4);

void setup(){
   Serial.begin (9600);
   pinMode(pin1, OUTPUT);

   pinMode(pin4, OUTPUT);
   pinMode(pin5, INPUT);
   sonarPort.begin(9600);
}

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

  digitalWrite(pin4, LOW);
  digitalWrite(pin4, HIGH);
  delayMicroseconds(20);
  digitalWrite(pin4, LOW);

  long pulse = pulseIn(pin2, HIGH)/58;
  Serial.print("PM Result: ");
  Serial.println(pulse);

  String buffer = "";
  sonarPort.listen();
  while(sonarPort.available() > 0){
      int inByte = sonarPort.read();
      buffer += inByte; buffer += " ";
      if(!sonarPort.available()){
          Serial.print("Serial result: ");
          Serial.println(buffer);
      }
  }
  delay(500);
}

Please provide specific model of the sensor you are using.

I contacted MaxBotix with the problem and for my surprise their technical support is really great:

The Arduino is set up to natively read TTL serial data.The MB7066 outputs its serial data in the RS232 format. Do not worry; this problem can easily be fixed. You can use an inverter such as the MAX232. You can also follow the following tutorial to make your own https://github.com/simonmonk/raspirobotboard/wiki/Rangefinder-Adapter.
Another option would be to test using this code section SoftwareSerial
  sonarSerial(rxPin, txPin, true); //define serial port for recieving
  data, output from maxSonar is inverted requiring true to be set.

In the bitstream of your ASCII data the pattern for "R" (01010010b) does never occur.
So obviously something is wrong in your system and/or setup.
Have you already considered the information given here http://www.maxbotix.com/articles/034.htm?
I would connect the sensor to a PC to check whether it's working correctly using a standard terminal software.

I don't have the cable yet so no, I have not checked, will later post my code to remove the possibility of a bad setup.