text:
What is Serial.begin(9600)?
I know that this is to initialize something:
Serial.begin(9600);

But I want to know what it really means?

The documentation has a good description of it. http://arduino.cc/en/Serial/begin

Serial.begin(9600) doesn't actually print anything. For that you'd want to use Serial.print("Hello world!") to print the text "Hello world!" to the serial console. Rather it initializes the serial connection at 9600 bits per second.
Both sides of the serial connection (i.e. the Arduino and your computer) need to be set to use the same speed serial connection in order to get any sort of intelligible data. If there's a mismatch between what the two systems think the speed is then the data will be garbled.
9600 bits per second is the default for the Arduino, and is perfectly adequate for the majority of users, but you could change it to other speeds: Serial.begin(57600) would set the Arduino to transmit at 57600 bits per second. You'd need to set whatever software you're using on your computer (like the Arduino IDE's serial monitor) to the same speed in order to see the data being sent.

Baud and BPS are two different things... can't find the link I was looking for now.

what if I put "Serial.begin(0);" or "Serial.begin(4000);". I mean I want to know what is the difference between the numbers?

Serial.begin is used to set the speed of communication, in bits per second. One byte is equal to 8 bits, but serial connections send a start and stop bit to identify the start and end to a particular byte to the receiving system. Thus, 10 bits are needed to send one character.
Using Serial.begin(0) tells the Arduino that it should communicate with serial at 0 bits per second. As you might expect, this means that the Arduino will never send any data at all.
Serial.begin(4000) will cause the Arduino to send data at 4000 bits per second. This is non-standard, but otherwise fine.

In short: changing the number changes the speed. Making the number smaller (e.g. Serial.begin(300)) has the Arduino send data more slowly. Increasing it, say to 57600 will send data faster. Both the sending system and the receiving system need to agree on what speed to use: your computer's serial program, like the Arduino Serial Monitor window, will let you set the speed at which your computer will receive data but you can only select from the common speeds: 300, 1200, 2400, 4800, 9600, 19200, 38400, 57600 and 11520 bit/sec. You can't enter other speeds, like 4000. 9600 is usually good.

Baud and BPS are two different things... can't find the link I was looking for now. - Here's one explanation: Appendix C: "baud" vs. "bps"

A picture is worth 1000 words, so they say, (1024 words if you work with computers) so I'll post some pictures ...
I set up my Uno to send "Fab" at 9600 baud and captured the results on a logic analyzer.

The parts shaded in red are the "idle" period between bytes.
From the above graphic note that the Tx (transmit) data line is normally high (1) until it drops low to indicate the start of a character (byte). This is the start bit. Then the 8 data bits (indicated by white dots) appear at the baud rate (9600 samples per second). After that the line is brought high again. This is the stop bit (the red part). Then we see the start bit for the next character, and so on. The "stop" portion can be indefinitely long, however it has to be at least one bit length.

More detail for the first character (the letter "F" or 0x46 or 0b01000110) can be seen here:

A - no data (Tx is high)
B - The "start bit". The line is taken low to tell the receiver that a character (byte) is commencing to be sent. The receiver waits for one and a half clock times before sampling the line.
C - First character arrives (the letter "F" or 0x46 or 0b01000110). There is no clock bit as such, the incoming data is simply sampled at the baud (transmission) rate. In contrast to SPI communication the data arrives least-significant bit first (in case you are not sending 8 bits per byte). Thus we see 01100010 (rather than 01000110).
D - The stop bit. This is always high, to ensure that we can distinguish between the end of this byte, and the start of the next one. Since the start bit is a zero, and the stop bit is a one, there is always a clear transition from one byte to the next.
E - The start bit for the next character.

You can see from the logic analyzer capture that T1 - T2 is 0.1041667 ms, and as it happens that is 1/9600:
1 / 9600 = 0.00010416666 seconds

Thus the rate of 9600 gives you the number of bits per second and the inverse is the time interval between bits.

Other considerations

Serial comms is not self-clocked (unlike SPI or I2C, and others) hence both sender and receiver have to agree on a clock rate.
The clock rate is not exact on the Arduino, because the hardware has to divide the system clock down to get a serial clock, and the division is not always exact. There is almost always an error, the amount is given in the datasheet (figures quoted for a 16 MHz system clock, such as on the Uno):

You can vary the number of data bits, you don't have to send 8 of them, in fact you can send 5 to 9 bits.
There can optionally be a parity bit sent after the data bits.

If you specify "odd" parity, the parity bit is set in such a way that the total number of 1-bits is odd.
If you specify "even" parity, the parity bit is set in such a way that the total number of 1-bits is even.
If you specify no parity, the parity bit is omitted.

This can help the receiver detect if the data arrived correctly or not.
The parity bit is sent before the stop bit.
In the case of 9 data bits (as used in the SeaTalk protocol) the parity bit is re-purposed as a 9th data bit. Therefore you can't have both 9 data bits and a parity bit.
You can also have two stop bits. This basically just lengthens the time between bytes. In the "olden days" this was so that slow electromechanical equipment could process the previous byte (eg. to print it).

Possible corruption
If you start listening to serial data in the middle of a stream, it is quite possible that a 0-bit in the middle of the stream will be interpreted as a start bit, and then the receiver will interpret everything after that incorrectly.
The only real way to recover from this is to have a large enough gap, from time to time, (eg. 10 bits long) that this cannot happen.

Inverted logic
The bits shown here (logic-level) are not inverted. That is, a 1-bit is HIGH and a 0-bit is LOW. If you have RS232 equipment that will probably be sending something like -12 V for a 1-bit, and +12 V for a 0-bit. This is inverted because a one is less than a zero, voltage-wise.
If you have such devices you need to do voltage conversion and logic inversion. Chips like the MAX232 will do both for you. They can also provide the -12 V needed to drive such equipment by generating it internally with the help of a few user-supplied capacitors.

Speed rule-of-thumb
Since, with one start bit, 8 data bits, and one stop bit we have a total of 10 bits, as a quick rule of thumb, you can calculate the number of bytes you can transmit in a second by dividing the bit rate by 10.
Eg. At 9600 BPS you can send 960 bytes per second.

Code to reproduce:
void setup()
  {
  Serial.begin(9600);
  Serial.print("Fab");
  }

void loop ()
  {
  }

;TLDR; It initializes the serial communication port and sets the baud rate. The device you're communicating with (or Arduino IDE Serial Monitor) have to be set to a matching baud rate. Once you've initialized the port you can begin sending or receiving characters. Arduino Serial Reference

Not to diminish or disrespect @Nick-Gammon's excellent coverage of this topic.

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


text:
can i give a vcc to 14v?
What is maximum voltage PWM pins can give?
can i give a vcc to 14v?

FYI, PWM doesn't vary voltage at all except going to Vcc and Gnd. It's never in between.

Since PWM pins are digital outputs, the maximum output voltage is VCC.

Or a little less, depending on load.  In effect, the PWM maximum at 100% duty cycle is VOH or the high-state logic output voltage, and the data sheet will characterize what that is in relation to Vcc.

The datasheet itself does not specify a maximum in the tables, but in the charts it gives a maximum of Vcc.

There's a difference between "Maximum that could be seen" (which arguably is more like Vcc+.6v) and "Voltage that will be seen at Maximum duty cycle" - the latter is the same as the voltage of a "1", and that is not necessarily Vcc but rather depends on the load, in a way that the data sheet should at least roughly characterize (ie, voltage at a given source current, effective Rdson, etc).

On a typical Arduino board, PWM pins will theoretically only ever operate at ground (+0v) or Vcc (typically +5v). PWM is a square wave, which means it alternates rapidly between those two values, aka LOW and HIGH.
With that said, if you run it with a 50% duty cycle, then the average voltage over several cycles will work out as 50% of Vcc (i.e. typically 2.5v). The same applies to other percentages. It's important to note that it's not equivalent to a 'true' analog signal though, and shouldn't be used as such.
As a side note, there are some modified Arduino clones which have a voltage selection switch. These typically let the pins operate at either 3.3v or 5v, and should affect PWM (as far as I know).

+5V
I understand for higher power people driving motors trigger a MOSFET transister which normally can go to 30 volts but this unit here appears to be able to switch 100 volts: https://www.banggood.com/100V-9_4A-FR120N-Isolated-MOSFET-MOS-Tube-FET-Relay-Module-For-Arduino-p-1396252.html this unit is likely to be able handle up to 50 Khz switching frequency (based on the regular MOSFET switching speed). Anything higher you'd need GaN (Gallium Nitride) transisters as used in Class D audio amps. Anyhow 100 volts and 9.4 amps would be 940 watts of DC, or maybe 664 watts of RMS sine wave (ball park), probably I would not trust more than 300 watts through that thing mind.

source: Stack Exchange

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

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

sort: votes


text:
Use command line to upload hex code to teensy.ex
I need a command line implementation for uploading code to Teensy-LC through Windows 8.1 operating system
I know Paul has not released support for command line for Teensy-LC yet but i would like to know if any work has been done by anybody else in this regard.
I asked this and this. But all these solutions include

sending the hex file to the user.
Asking him to open Teensy.exe
Asking him to upload the hex file into Teensy.ex
Asking him to run teensy_reboot.exe

So is it possible to create an installer of a sort for this purpose which eliminates the user performing all these operations separately and a guided installer simply with Next->Next which does the entire job.
But I suppose that since Command Line installer is not available for windows I don't know if this is possible for impossible.
So if there is any way I can achieve an installer UI for Teensy-LC bootloader that would be perfect
Other viable option
If not that is it possible to make the entire process happen with the person not having direct access to the hex file.
Like sending a packaged installer or something
I am not sure how this would happen but if there is any possible way please help me out

You might be able to run the teensy.exe in the background, and press the right button using code

But this is a third party application I don't have access to. Secondly the question that you pointed me to does not have an answer yet. So even that person was not able to press button of a third party application in background. is there any other way?

Most applications use the windows api to create buttons. E.g. screenreaders are able to access this information, and read out button info, and also "click" on it.

This is starting to drift off topic for this site, but the best solution for making an automated programming utility for the Teensy on Windows, short of writing one yourself, would be to use some kind of UI automation framework to automate the process described in my earlier answer. My favorite one that I have used in the past is AutoIt. It has tools to inspect applications so that you can programmatically click buttons and fill out fields. There are even ways of having it run programs without them being visible to the user. There are plenty of tutorials on the web on how to use AutoIt so I would suggest googling for that. If you have further questions on how to do that, they would be more appropriate on a site other than Arduino.SE.

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


text:
What is the difference between file.print() and file.write()
From here I think I understand the difference between Serial.write and Serial.print, but is it the same when writing to a file in a SD card for example. Does it mean that File.write saves bytes in the file instead of text?

The File class inherits from the Stream class, which in turn inherits from the Print class.
The Serial class inherits from the Stream class, which in turn inherits from the Print class.
print() and write() are defined by the Print class.
So yes, File.print() and Serial.print() are the same, as are File.write() and Serial.Write().


text:
How can I enable the security bit of a teensy board?
I want to prevent someone from connecting an arduino device to a computer and downloading the code (yes, the hex-dump code) because I want to embed a wifi password inside a device that should be kept secret
With that said, I stumbled upon this answer that mentions a security bit
I would like to ask for more details regarding it - i.e. how can I use it, enable it, what are it's limitations, etc. (Preferably for a Teensy v3.2 board, but if it's standard/generic, I would accept such an answer as well).

It is neither standard nor generic.

@IgnacioVazquez-Abrams then id like a Teensy v3.2 solution if possible

Given that the controllers in question don't have on-chip wifi, it is likely that the wifi credentials are going to be sent in the clear across some sort of standard serial interface to the wifi engine, and can be sniffed in flight.  So read-locking the MCU won't actually achieve your goal.

@ChrisStratton you would be correct, I do intend to eventually make this on my own PCB though and thus sniffing them from the serial interface would be difficult if not impossible without de-soldering the chip(s) - although I think at that point I may as well go with storing them on an embedded SD card or similar as well (yes, one could still write a program to read it from the SD card, after downloading the current code to see where to look on the SD card, and then publish it via the wifi somehow, but that is becoming a complicated procedure).

Unless you are using all BGA chips and routing only on internal layers, it doesn't really follow that a custom PCB prevents sniffing.  Those Cypress FX2 logic analyzers are cheap, powerful, and frequently employed for this type of purpose (for example, reversing propriety 2.4 GHz RC toy protocols to allow using a transmitter with better sticks)

@ChrisStratton I was thinking of potting (i.e. covering in epoxy) the sensitive area between the processor/storage/wifi, but leaving the USB and some other stuff exposed - should make it difficult if not impossible to use any sort of logic analyzer on that area of the PCB without destroying the PCB physically

The Teensy 3.2 board is based on MK20DX256. The processor core is an ARM and not AVR. The best way to learn about security on the MK20DX256 is to read the documentation.

Chapter 8 Security
  8.1 Introduction
  This device implements security based on the mode selected from the flash module. The following sections provide an overview of flash security and details the effects of security on non-flash modules.
8.2 Flash Security
  The flash module provides security information to the MCU based on the state held by the FSEC[SEC] bits. The MCU, in turn, confirms the security request and limits access to flash resources. During reset, the flash module initializes the FSEC register using data read from the security byte of the flash configuration field.
NOTE The security features apply only to external accesses: debug and
  EzPort. CPU accesses to the flash are not affected by the status
  of FSEC. In the unsecured state all flash commands are available to the programming interfaces (JTAG and EzPort), as well as user code execution of Flash Controller commands. When the flash is secured (FSEC[SEC] = 00, 01, or 11), programmer interfaces are only allowed to launch mass erase operations and have no access to memory locations.
Further information regarding the flash security options and enabling/disabling flash security is available in the Flash Memory Module.

The next step is to search for an open-source project that uses the FSEC setting. And by chance the mbed does. Here is link to how it is done in the mbed CMSIS Cortex-M4 Core Device Startup File for the MK20DX256. There should be the same setting in the Teensy Arduino core. Locating that is left to the reader.
Cheers!

It is possible for the AtMega processors - like the Teensy 2.0 (see https://www.pjrc.com/teensy/ ).
Steps:

Work out your exact code. It will be a pain to update it once this is done, so thing carefully.
Upload the code using ICSP (file->upload using programmer). TEST IT HERE!
Work out the fuse you need to set. The important one is "RSTDISBL" - this disables the reset pin (makes it behave just like a regular pin).  Use the page at http://www.engbedded.com/fusecalc/ to calculate your fuse settings.
DOUBLE CHECK IT!
Use an ICSP to set the fuse. You will need to work out the 6 pins to connect the ICSP to, since there is no standard ICSP header.

If you did everything right, and the reset pin no longer works - this will protect the code from download!
If anything went wrong (e.g. you set the wrong fuse values - I've been there), or if you want to change the code, you will run into problems. In theory, you can use a high-voltage programmer - like http://www.societyofrobots.com/member_tutorials/node/239 - to reset everything to factory, but that takes 20 volts, and there's a high chance one of the other components on the Teensy board will be damaged.
Note that, if you do use the High-voltage programmer, the chip's memory will be wiped, so this can't be used to recover your code.

Any thoughts for the arm versions?

It's only 12V (on the pin), and it's not difficult to build a HV programmer.

This is not only targeting the wrong chip (the Teensy 3.x are NOT ATmegas), it is bad advice - the goal is to prevent readback which is a distinct goal from blocking the (re)programming pins.

The reprogramming pins are enough to read back the data. It's not difficult to build an HV, but that doesn't get you the data, only lets you wipe it. I missed the bit where it said v3.2, and I believe the "security bit" mentioned in the link in the question is the method I described.

You are overlooking the difference between disabling the pins vs disabling readback.  Typically, when you lock a chip you can still reprogram it via the most convenient method (if you are willing to erase it), but what you cannot do is read back the existing memory.

While this does not answer your question, I believe it may help you with an alternative approach, which won't hide it completely, but will make it a lot harder to figure out.
Rather than keeping the password in plain text (which will be easy to spot in a hex dump), you can hide it somewhat. For example, exclusive-or each byte of the password with a randomly chosen number, put the result in your code; then, when you want to log in to the wifi, exlusive-or it with the same numbers (which must also be on your code).
Note that all the information required MUST be on the Teensy, so it is not impossible to reverse engineer; however, it will be hidden from casual inspection.
Note that, although more complex obfustication is possible (using any off-the-shelf encryption), since both the code and any keys will be available to an attacker, it is a token gesture only.
The Teensy v3 has JTAG, which means a running Teensy can be inspected, single-stepped, all memory and pin states can be viewed & modified. Once someone has your device, it's pretty much a lost cause against a determined attacker.

The Teensy (or at least the primary MCU used on it) can of course be read-secured which should make the jtag access irrelevant; what you miss is that the credentials can still be sniffed in-flight to the wifi engine.

@ChrisStratton, since you seem to know the answer to this question, could you post it as an answer (with the caveat that it won't work in this case)? That way, if someone else finds this question and wants it for a different purpose, they don't have to ask a new question?


text:
Tone inside interrupt
I am trying to play a tone with a buzzer connected on an arduino nano pin. I have also connected a reed switch with INPUT_PULLUP on INT0 and a led. The program loops continuously (it's an environmental monitor and alarm personal project) until the reed switch is set on HIGH where a function is called and the buzzer should play an one-second high pitch tone.
void doorStateChange() {
  static unsigned long last_interrupt_time = 0;
  unsigned long interrupt_time = millis();
  if (interrupt_time - last_interrupt_time > 1000)
  {
    led_B_state   = !led_B_state;
    digitalWrite(buzzPin, HIGH);
    digitalWrite(led_A_Pin, HIGH);

    if (millis() - interrupt_time <= 1000 ){
        digitalWrite(buzzPin, LOW);
        digitalWrite(led_A_Pin, LOW);
    }

  }
  last_interrupt_time = interrupt_time;
}

The interrupt is called, the Led lights up but I can't make the buzzer sound right. I 've tried with tone(buzzPin, 5000, 1000); but seems that the delay does not work - The sound is heard but after the 1000ms it continuous to work in a different tone (strange?).
The only way I could make it work is with buzzPin_state = ! buzzPin_state; where the buzzer beeps as long as the reed switch is HIGH.
I also need to say that attachInterrupt(0, doorStateChange, CHANGE);.
The information I get from googling this issue is gibberish: some say that delays don't run in interrupts, others call external functions etc.
What is the proper way to achieve this ?

Can you give a more detailed description about what you expect and what is happening with this code? You just want to pull the buzzer pin to high on a rising edge (when the input pin goes from low to high)?

I want to pull the buzzer pin to high on CHANGE for one second.

But you don't need tone() then, correct? (Rising/change/falling are really irrelevant in this case)

I wanted to hear a high pitch tone rather than the default buzzer (beep) one.

But that's not only the point. I can't make it to delay the tone for one second. Only way it works is if the state changes inside the interrupt function which means the sound lasts as much as the reed switch pin is high.

You might need to enable interrupts inside the function. Try placing sei();  at the beginning of the function.

The tone() function initializes the PWM at the frequency and determines the number of toggles that equate to your desired length. Along with initializing a the Output Capture interrupt to coincide with each PWM toggle. Where the PWM's ISR decrements that counter.Hence being inside another ISR will prevent the OCI(or PWM) ISR. Gerben's suggestion of SEI() will help. But you should really write ISR() or functions called by AttachInterrupt() not to be LONG or blocking. ISR's should be quick in and out.

@mpflaga ok got it, but I am starting to think that the whole design of this function is wrong.

Don't do delay() calls inside an ISR. In all probability it will hang indefinitely. If you want to play the tone for a second all you need to do in the ISR is set a flag, which you test in the main loop. Turn the buzzer on when the flag changes state. Remember when you did that. When a second is up turn the buzzer off again.
In fact in your case you probably don't need the interrupt at all. Test for the reed switch change in the main loop as well. Don't overcomplicate it.


text:
Connecting an AB phase encoder motor to arduino
i'm trying to understand how to connect this motor:
"Mitsumi 334P/R AB"
Link to the motor i bought

connections are:
GND - Obvious.
5v - Obvious.
rest of the connections are a bit confusing to me and i do not want to fry my arduino trying.

do i need a driver or this looks like a built in one?
do i need to add any electrical components like resistors and capacitors ect?

It's just a regular motor, with a (optical) rotary encoder inside. So the first two motor pins are to run the motor. So connect to VCC and GND, or GND and VCC, if you want to run it in reverse. (VCC doesn't have to be 5v; it can be 3v to 30v).
Connect A and B to a digital input pin. You can see what kind of signal you can expect in the screenshot of the oscilloscope, attached to the ebay-listing. So you can measure the speed, and relative position of the motor-shaft.

is there a way to decide (like stepper motor) to rotate 200 right/left? or this is a different kind that only measures speed and rotations?

You can turn on the motor, measure how many steps it's making, and turn off the motor when you reach 200 "steps". This is however grossly oversimplified, as in reality, due to inertia, you will probably overshoot these 200 steps. You probably need to slow down the motor (using PWM), when it's closing in on 200. Some kind of PID control.


text:
Parsing JSON on the Arduino
I'm using the ArduinoJson library. There is a great example for parsing a single JSON object in the source code. I am attempting to iterate over an array of JSON objects:
#include <JsonParser.h>

using namespace ArduinoJson::Parser;

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

  char json[] = "[{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}, \
    {\"sensor\":\"gps\",\"time\":1351824140,\"data\":[50.756080,21.302038]}]";

  JsonParser<32> parser;
  JsonArray root = parser.parse(json);

  if (!root.success()) {
    Serial.println("JsonParser.parse() failed");
    return;
  }

  for (JsonArrayIterator item = root.begin(); item != root.end(); ++item) {
    // unsure of what to do here.

    Serial.println((*item)["data"]);
    // results in:
    // ParseJsonArray:21: error: call of overloaded
    //   'println(ArduinoJson::Parser::JsonValue)' is ambiguous

    JsonObject something = JsonObject(*item);
    Serial.println(something["sensor"]);
    // results in :
    // ParseJsonArray:26: error: call of overloaded
    //   'println(ArduinoJson::Parser::JsonValue)' is ambiguous
  }
}

void loop() {}

item is of type JsonValue. I would like to treat it as a JsonObject and pull some data out of it.

This is how I would write this loop:
for (JsonArrayIterator it = root.begin(); it != root.end(); ++it)
{
  JsonObject row = *it;

  char*  sensor    = row["sensor"];
  long   time      = row["time"];
  double latitude  = row["data"][0];
  double longitude = row["data"][1];

  Serial.println(sensor);
  Serial.println(time);
  Serial.println(latitude, 6);
  Serial.println(longitude, 6);
}

And, if C++11 is available (which is not the case with Arduino IDE 1.0.5):
for (auto row : root)
{
  char*  sensor    = row["sensor"];
  long   time      = row["time"];
  double latitude  = row["data"][0];
  double longitude = row["data"][1];

  Serial.println(sensor);
  Serial.println(time);
  Serial.println(latitude, 6);
  Serial.println(longitude, 6);
}

+1 for a great use case of the for loop.

Got it! Initially, casting the retrieval of the item from the JsonObject before printing was enough.
JsonObject something = JsonObject(*item);
Serial.println((char*)something["sensor"]);

Although, I think this looks better.
char* sensor = (*item)["sensor"];
Serial.println(sensor);


text:
Arduino TMP36 sensor
I am following the tutorial Tiny WiFi Temperature Sensor with Arduino. everthing works fine, but I have a little problem.
When the serial monitor is opened the sensor is reading fine like 23.20, 20.25 etc.,  but when I closed the serial monitor window I got wrong values, for example, 289.34, 289.90.
What does the serial monitor do?
I am stuck with this problem for last two days. Please give me a hand.

The baud rate is as you can see 115200 and i have changed it various time but it doesn't do anything.
I haven't test commenting out the Serial.println() lines
The values i can see at my server (see the function send_request).
The problem is when i am testing the program opening the serial monitor windows everything works fine for example: 29.20, 30.12, 28.12 but when i close the windows i start getting wrong values for exmaple: 289.45, 289.89 , etc... .

Here is my code.
#include <Adafruit_CC3000.h>
#include <Adafruit_CC3000_Server.h>
#include <ccspi.h>

/*
   Tiny WiFi temperature sensor with Arduino, the TMP36 sensor & the CC3000 chip
   Writtent by Marco Schwartz for Open Home Automation
*/

// Include required libraries

#include <SPI.h>
#include <string.h>
#include "utility/debug.h"
#include<stdlib.h>

// Define CC3000 chip pins
#define ADAFRUIT_CC3000_IRQ   2
#define ADAFRUIT_CC3000_VBAT  A3
#define ADAFRUIT_CC3000_CS    8

// WiFi network (change with your settings !)
#define WLAN_SSID       "ssid"        // cannot be longer than 32 characters!
#define WLAN_PASS       "password"
#define WLAN_SECURITY   WLAN_SEC_WPA2 // This can be WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA or WLAN_SEC_WPA2

// Create CC3000 instance
Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS, ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT,
                         SPI_CLOCK_DIV2);

// Local server IP, port, and repository (change with your settings !)
uint32_t ip = cc3000.IP2U32(10,0,129,108);
int port = 8080;
String repository = "/tiny-wifi-temperature/";

void setup(void)
{

  Serial.begin(115200);
  Serial.println("Start setup");

  // Initialise the CC3000 module
  if (!cc3000.begin())
  {
    Serial.println("Impossible to start");
    while (1);
  }

  Serial.println(F("\nDeleting old connection profiles"));
  if (!cc3000.deleteProfiles()) {
    Serial.println(F("Failed!"));
    while(1);
  }

  listSSIDResults();
  connectNetwork();
  displayConnectionDetails();
  /*
  while(!displayConnectionDetails())
  {
    connectNetwork();
  }*/

}

void connectNetwork(void)
{
  Serial.println(F("Trying to connect wifi ")); Serial.println(WLAN_SSID) ;

  /*
  uint32_t ipAddress = cc3000.IP2U32(10, 0, 130, 200);
  uint32_t netMask = cc3000.IP2U32(255, 255, 0, 0);
  uint32_t defaultGateway = cc3000.IP2U32(10, 0, 1, 1);
  uint32_t dns = cc3000.IP2U32(10, 0, 1, 1);
  if (!cc3000.setStaticIPAddress(ipAddress, netMask, defaultGateway, dns)) {
    Serial.println(F("Failed to set static IP!"));
    while(1);
  }
  */

  /*
  if (!cc3000.setDHCP()) {
    Serial.println(F("Failed to set DHCP!"));
    while(1);
  }*/

  // Connect to  WiFi network
  if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
    Serial.println(F("Failed!"));
    while(1);
  }
  Serial.println("Connected to WiFi network!");

  // Check DHCP
  Serial.println(F("Request DHCP"));
  while (!cc3000.checkDHCP())
  {
    delay(100);
  }

}

void loop(void)
{

  // Measure the temperature
  int sensorValue = analogRead(A4);
  float milliVoltsValue = sensorValue * 5000. / 1024.;
  float temperature = (milliVoltsValue - 500.) / 10.;

  // Print the result
  Serial.println(temperature);

  // Transform to string
  char temp[5];
  dtostrf(temperature, 5, 2, temp);

  // Send request
  String request = "GET " + repository + "sensor.php?temp=" + String(temp) + " HTTP/1.0";
  send_request(request);

  // Update every second
  delay(1000);
}

// Function to send a TCP request and get the result as a string
void send_request (String request) {

  // Connect
  Serial.println("Starting connection to server...");
  Adafruit_CC3000_Client client = cc3000.connectTCP(ip, port);

  // Send request
  if (client.connected()) {
    client.println(request);
    client.println(F(""));
    Serial.println("Connected & Data sent");
  }
  else {
    Serial.println(F("Connection failed"));
  }

  while (client.connected()) {
    while (client.available()) {

      // Read answer
      char c = client.read();
    }
  }
  Serial.println("Closing connection");
  Serial.println("");
  client.close();
}

void listSSIDResults(void)
{
  uint32_t index ;
  uint8_t valid , rssi, sec ;
  char ssidname[33];

  if (!cc3000.startSSIDscan(&index)) {
    Serial.println(F("SSID scan failed!"));
    return;
  }

  Serial.print(F("Networks found: ")); Serial.println(index);
  Serial.println(F("================================================"));

  while (index) {
    index--;

    valid = cc3000.getNextSSID(&rssi, &sec, ssidname);

    Serial.print(F("SSID Name    : ")); Serial.print(ssidname);
    Serial.println();
    Serial.print(F("RSSI         : "));
    Serial.println(rssi);
    Serial.print(F("Security Mode: "));
    Serial.println(sec);
    Serial.println();
  }
  Serial.println(F("================================================"));

  cc3000.stopSSIDscan();
}

bool displayConnectionDetails(void)
{
  uint32_t ipAddress, netmask, gateway, dhcpserv, dnsserv;

  if (!cc3000.getIPAddress(&ipAddress, &netmask, &gateway, &dhcpserv, &dnsserv))
  {
    Serial.println(F("Unable to retrieve the IP Address!\r\n"));
    return false;
  }
  else
  {
    Serial.print(F("\nIP Addr: ")); cc3000.printIPdotsRev(ipAddress);
    Serial.print(F("\nNetmask: ")); cc3000.printIPdotsRev(netmask);
    Serial.print(F("\nGateway: ")); cc3000.printIPdotsRev(gateway);
    Serial.print(F("\nDHCPsrv: ")); cc3000.printIPdotsRev(dhcpserv);
    Serial.print(F("\nDNSserv: ")); cc3000.printIPdotsRev(dnsserv);
    Serial.println();
    return true;
  }
}

Even though you've provided a link to the circuit (sort of) and the code that you think you're using, it would be good to include the actual code and some kind of documentation of the circuit – maybe a photo of what you've built. Also tell us what you've done so far towards debugging the problem. That will help us to focus and also to avoid telling you what you already know…

The incorrect values, I presume after reading the article, are seen on the browser at localhost?

The serial monitor gives you a way to "talk" relatively directly with the Arduino – in this case it give you a way to easily confirm that the basic circuit is working and that you are getting sensible temperatures. That's a foundation on which you can build.
It is unlikely – I think – that the serial monitor is causing the problem. But before you believe me, there is one thing you should consider. The serial monitor runs relatively slowly, so outputting the temperature via the serial monitor introduces a delay in your code. That could explain the difference.
So your next step is to trace your bad value. So, first more questions:

What baud rate are you running the serial monitor at? Does changing the baud rate affect the result? That would point to a timing related issue.
Is there any code that writes to the serial monitor (e.g., a call to Serial.println())? If there is what happens when you comment it out?
Where are you seeing the two values (the correct and incorrect values)? I assume that both are at the web server, but I want to confirm this.
Can you explain more clearly the process to demonstrate the problem? In the tutorial that you link to I don't think that the code pathway is the same to see the value on the serial monitor as it is on the server, so I'm wondering if an error was made as you changed the code.


text:
Finding connectors for push button component
What type of connectors would I use for these buttons?:
http://www.adafruit.com/product/1477
They sell wires with the connectors already crimped on, but I only need the connectors.
I found https://www.jameco.com, but i'm not sure which connector would be right, or what to look for specifically.

Go down to your local (decently-stocked) hardware store and ask for "quick connect terminals". From the dimensional drawing you'll need 2mm or 5/64" terminals.

You may not have to go to a hardware store for this as they can also be found online

These are also called "Quick Disconnect" connectors. Here is the category on Digikey and Mouser. Jameco also sells them, but doesn't have a very easily filterable category for them.

Try the local automotive supplier. They should have crimp kits with those connectors included.


text:
USB cable connector
The arduino has a USB port which can connect to a computer.  The cable used to make this connection has a standard USB connector at one end (that connects to the computer) and a "larger" connector on the opposite end (that connects to the arduino).  See picture below:

What is the name of this "larger" connector?

They are both standard USB. The end which goes into the computer is type A (or USB-A), and the end which goes into the Arduino is type B (or USB-B). The USB-B connector is also commonly used on devices such as printers and scanners. The distinction mainly exists so it's obvious which device is the host (i.e. the computer) and which device is the client (i.e. the Arduino).
As a side note, other types of USB connector exist as well. You will probably be familiar with mini and micro USB connectors, which can be found on various devices such as digital cameras and mobile phones.

No.  The larger connectors exist for legacy reasons, not for power handling.  High-power peripherals are not powered by the USB, but by external supplies.  Meanwhile micro-USB connectors are routinely used by dedicated chargers to charge mobile devices at currents exceeding what full-size legacy USB ports are specified to supply.

@ChrisStratton - Thanks for the correction. I must have been thinking of a different standard.


text:
Turning LED On/Off by using SIM808 with Arduino Mega
I am trying to turn an LED on/off by using GSM 808 module. Here #a0 = LED off and #a1 = LED on. I have used lcdShow function to display characters in LCD display. But nothing appears on display. What is wrong in this code?
#include <SoftwareSerial.h>
#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>
//I2C pins declaration
LiquidCrystal_I2C lcd (0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
SoftwareSerial SIM808 (10, 11);
char inchar;
const int LED = 2;

void setup ()
{

    Serial.begin (9600);
    SIM808.begin (9600);
    delay (10000);
    SIM808.print ("AT+CMGF=1\r");
    delay (100);
    SIM808.print ("AT+CNMI = 2,2,0,0,0\r");
    delay (100);

    lcd.begin (16, 2);
    lcd.backlight ();

    delay (1000);

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

void loop ()
{
    if (SIM808.available () > 0)
    {
        inchar = SIM808.read ();
        if (inchar == '#')
        {
            lcdShow (inchar);
            delay (10);
            inchar = SIM808.read ();
            if (inchar == 'a')
            {
                lcdShow (inchar);
                delay (10);
                inchar = SIM808.read ();
                if (inchar == '0')
                {
                    lcdShow (inchar);
                    digitalWrite (LED, LOW);
                }
                else if (inchar == '1')
                {
                    lcdShow (inchar);
                    digitalWrite (LED, HIGH);
                }
            }
        }
        SIM808.println ("AT+CMGD = 1,4");
    }

}

void lcdShow (char i)
{
    lcd.setCursor (0, 0);
    lcd.print (i);
    delay (5000);

}

Firstly your code was really poorly formatted, making it difficult to see what it did.
After reformatting my best guess as to why you LCD is blank is that the SIM808 is does not have any data available.  print something in the else statement.
Next it could be that the LCD is not working, print something out in setup().
You might also want to add a delay to loop() to prevent the Arduino spamming your SIM808.


text:
IR basic connection
Can I know how to change or connect from this circuit (three pin IR receiver) to two pin IR receiver because when I change the connection (3 pin to double pin), my arduino cannot receive the signal from transmitter.
I dont know because of my connection or because of there are different between tree and double pin IR receiver. Can anyone help me.
My code too long, so I just paste IR sensor for detect signal from transmitter.
{
  indicator();
  irrecv.resume();
  while(1)  //-------loop M1
  {
      HM_1();
      if(irrecv.decode(&results) >0 || digitalRead(SBB) == HIGH )
      // if IR receiver detect signal or button pressed
      {
         indicator();
         break;
        //irrecv.resume();
      }//
      else
      {    //-------else "if(sensor 2)"
          //go back to else "if(sensor 1)"
      }//-------else "if(sensor 2)" end
      //nothing
    }//-------while end
}

What is the part number? It looks like an IR LED (transmitter) to me.

There are some two pin receivers at the cheaper end of the market.  A part number would really help, but I suspect you haven't got one and can't find it.  I can't find any diagrams and I can't test one at them moment so this is a guess.  You need to leave out the red (vcc) wire from you diagram and connect the signal wire to +ve pin of the Receiver.  If that doesn't work switch the connections over.

To use a plain phototransistor to detect remote control signal with an Arduino at meaningful range in real world conditions, you will need to add either a circuit or software to select only signals with the desired modulation from the noise.  This is probably just barely possible with an Arduino's ADC, but will be a non-trivial project.  Unless you really want to spend time learning about signal processing and writing optimized AVR code, better to just buy the usual 3-pin type with an internal demodulator.

From what you have described, i think you are getting confused between the function of the two types. The 3 leg style is designed to receive coded pulses from remote controls (TV,Video, etc) where as the 2 leg is typically used, but not limited to, IR switching, where a signal is generated when the light path between the sender and receiver is broken with an opaque blade or similar or a beam is reflected back from an object as it passes. So trying to use the same code for the two types is provably where you are having problems.
Two example of this are here this uses a reflected IR beam where as this slot sensor is the break a beam type, often used in a limit or timing situation. One half of this is similar to the 2 leg diode you show.
It just depends on what situation you are using it in as to which is appropriate.
Without seeing your code, this is about as far as i can go, post your code so the forum can view it and make suggestions.

I already put my code.

To expand on Doug's answer:
There are two types of IR receiver. The two-pin one you have is basically a photodiode with infra-red filter. When infra-red light hits it the transistor gets biased and turns on. This is the most basic type you can get and is very hard to work with for anything other than simple on-off signals.
The second type is the IR receiver module. This contains a photodiode as above, but also contains extra circuitry. It receives IR light on the photodiode and filters it through a band-pass filter. A remote control sends a sequence of pulses of light which itself is further made up of high frequency pulses (36KHz square wave, for example). It's this high frequency pulsing that is allowed through the band-pass filter. The internal circuitry then turns these pulses of high frequency square waves into pulses of ON or OFF signals by low-pass filtering them to remove the high frequency component.
This latter type of receiver is far easier to work with for sending of data or commands from (eg) a remote control. But it can't detect a steady-state IR signal. The modulation and filtering means that a much weaker signal can be extracted from the background IR light meaning much greater distances can be achieved using much weaker transmission LEDs.
So while it is possible to use the former type with an Arduino you have to realise that the software required to do all the filtering and detection, as well as the extra hardware required to interface it, makes them considerably harder to use. That is why almost everyone uses the three-pin versions that do all that for you.
One thing to note with the three-pin versions: they have to match the carrier frequency of the transmitter. So a 36KHz transmitter has to be paired with a 36KHz receiver. Otherwise it won't be able to detect the signal. Just like a radio - it has to be tuned to the right band.

Thanks for expanding Majenko, I am not that technically proficient. Doug


text:
Visual clock with millisecond display refresh rate
I need to create a millisecond capable visual clock - I will use the clock for visual frame synchronization of multiple cameras. I found this project but it seems to use a LED display that only has resolution of one 1/100th of a second. Not sure if the digits can be shifted to show milliseconds.
I guess I need to use LED instead of LCD display because of the ms refresh rate? Can someone help with my project please? I am a SW programmer and have zero experience in HW programming. So I am new to Arduino too - I have not done any project at all yet. I do own neither Arduino nor LED display.
Thanks!

What is the project for? Take another project an modify it. It only really needs to show the right mills when you stop it so don't worry about the refresh rate.

I need to visually measure synchronization difference of a stereo camera, so I actually need ms refresh rate. Edited the question accordingly.

Thanks for the clarifications. What is the maximum time you would need to measure? I have seen this done with a ring of white LEDs going around in a circle.

Well what I basically do so far is try to lock my FPS to Xs (now 2s) in OpenCV and just do a visual check of both camera streams next to each other on a PC monitor. So I actually need only last seconds digit + milliseconds (example: 5.123). But in the future I may want to test a video sync and maybe let it run for hours - however probably same amount of digits would suffice since the sync is not expected to drift by thole 10s. I would prefer LED display with numbers, instead of pure 0/1 led "bulbs". Say I expect measurement in range of 100ms so I would need 100 pcs of simplest LEDs anyway.

"Say I expect measurement in range of 100ms so I would need 100 pcs of simplest LEDs anyway." No, actually you do the LEDs in binary and you can get 256ms with 8 LEDs, 512ms with 9, 1024 with 10 etc

While it may be the simplest setup possible regarding the readability of the LEDs I think I dont want a binary output. I need to be able to read time quickly not having to convert it from binary to decimal.

Most cameras run at 50 of 60 frames per second. That means that 2 numbers appear during the recording of one frame. If those numbers are e.g. 6 and 7, the frame will probably show something like a 8. In other cases weird thinks will appear in the last segment, rendering it completely useless, and giving you only 1/10th of a second accuracy. You could use the 7-segment for the first few numbers and a circle of leds for the 1/100th seconds. I'd suggest buying an arduino with more pins than the arduino uno, as you'd need quit a few pins for all those leds.

you could just get a binary counter IC, binary to 7 seg IC, and 555 timer.

@Gerben: You are one order of magnitude too big - 60 Hz yields 16ms resolution which is aprox. 1/100th of a second. But I want to get 16x more accurate - from 16ms to 1ms. The idea of having circle of LEDs is nice though - I could have one circle for 1/100th digit and one for 1/1000th (ms) digit. I could at least measure the exposure time like that if more LEDs shine within one circle.

Unless you have high speed cameras, I don't see the point. Also cameras have a "rolling shutter" creating inaccurate led-readings.

what range of shutter speeds do you plan to use?

You need to define the parameters of the problem more clearly.
First, and most importantly, what is the shutterspeed you'll be using? If it's longer than 1 ms, then you can't use a 7-segment display to show the MS count, since the camera shutter would be open for multiple values.
Even if your shutterspeed is a single MS, your shutter won't be synchronized with your timer, so sometimes the shutter will be open when the display switches. That can even happen with the seconds digit of your time display.
If you're using a video camera, assume the frame rate is 60 fps, which gives a likely shutterspeed somewhere around 16.6 ms. That's way too long to display ms time values using 7-segment displays.
The ring of LED idea is good, but I would tweak it.
Here's what I would do: Build an LED clock to display whole number seconds. Don't multiplex, use latches and drive each 7-segment display constantly. (There are off-the-shelf CMOS chips that are latching 7-segment drivers.) If you only care about the 1s digit of the second value, only use 1 7-segment display. That will make things easier to wire.
Use 3 rings or columns of 10 LEDs for the MS display: tenths, hundredths, and thousandths. I would lean towards using columns since it would be visually easier to read.
The display will show your seconds as numbers, and 3 columns of 10 LEDs, showing the sub-second time range in 10ths, 100ths, and 1000ths. If the shutter opening spans multiple MS, as it will very likely do, all the LEDs that represent the sub-second time will be lit in the image, so you will get a nice clean visual image of the time SPAN that the shutter was open (All the LEDs from the start to the end of the shutter opening will be lit.)
You could drive the 3 columns of LEDs using 3 4017 divide-by-10 counters. These chips have both a 1-of-10- output, which will drive an LED, and a count/10 output, which would feed the next stage.
Write Arduino code that generates a short positive pulse every MS. Feed that into the clock input of the 4017 driving the thousandths digit. Feed the out/10 output of that chip to the clock input of the hundredths 4017, and the output of the hundredths 4017 into the clock input of the tenths 4017.
You can drive the whole ms display with 2 Arduino lines: The ms clock, and a reset line tied to all your 4017 counters' reset lines. To start timing, first pulse the reset line to zero them all out, then start your ms clock.
My CMOS cookbook doesn't say how much current the 4017 will put out to it's 1-of-10 outputs, but I bet it's enough to drive a display LED directly. You could wire all 10 LEDs in each column as common cathode, with a single current limiting resistor between each column's common cathode and ground.
You could probably set up a timer pin on the Arduino to generate a millisecond pulsed output, but that's not something I've learned how to do yet.
Occasionally you'll get a whole second 7-segment display with 2 different values captured in a frame, but that will be rare, and you will be able to figure out what happened from the frames immediately before and after it. (Previous frame shows a 5. Current frame shows a 5 and a 6 superimposed, so it's a mess. Conclusion, this frame shows the end of second 5 and the beginning of second 6.)

Thanks for a very long and valuable answer! As I am new to HW I dont even know what a HW "counter" (like the 4017) is. So to bypass the counter I guess I could connect everything directly to GPIO outputs on the Arduino board itself? If I would do all in LED without 7-segment (40 LEDs) does that mean I need 40 GPIO pins + 1 for the input voltage? Which board can provide 41 or at least 31 pins (I could omit the seconds probably)?

I mean, since I am a SW programmer it would be easier for me to implement all the necessary logic in SW only without any integrated circuits (HW counters etc.).

Yes, you would need 40 pins to do it directly from the Arduino, plus 7 pins for the 7-segment display. Do yourself a favor and buy a copy of the "CMOS Cookbook." It's very helpful for stuff like this.

I'm a programmer too, but I don't think you will be able to do that. You'd need 47 logic lines. The chip I mention, the 4017, is very easy to use. You give it a clocked input, and it sends a logic 1 to 1 of 10 outputs, and switches outputs on each pulse of the clock. Then it resets back to the beginning and starts again. It also has an output that is a clock count that's 1/10 of the input frequency. Check this link for an explanation of using the 4017: http://www.doctronics.co.uk/4017.htm

It might be counterintuitive, but it's actually easier to do this sort of project with ICs. You will drive yourself nuts trying to wire up 47 output lines to an Arduino, then troubleshoot everything. The Mega 2560 does have enough I/O lines, but then you won't be able to do much else with the board.

Thanks for valuable comments. I admit design with ICs really is simpler. What if I do not want to loose the 1ms precision beyond the ms-decade (beyond 1/100th of s)? I could run more than 10 LEDs in 1ms interval - say 50 or even 100 so that I can measure sync even with longer shutter speeds and still not loose precision. Say I would need a "counter" with 50 or 100 (1ms) outputs, or chain multiple decade counters somehow. I may run a 2ms or even bigger step to reduce number of LEDs but still get sub 10ms precision for longer shutter.

I think I need something in this direction: http://www.instructables.com/id/16-Stage-Decade-Counter-Chain-Using-two-4017-Chi/

I see, I can chain the counters but I will loose one stage since they have to be chained on 9th pin not to loose the frequency... so for 50 LEDs I would need 6 of them not 5. Is there a counter that has more than 10 outputs? Maybe 20 or more? Or can this be solved differently?

In case someone is interested you can do more than 10 LEDs by cascading multiple 4017s - see here: http://electronics.stackexchange.com/questions/33652/how-to-cascade-4017-decade-counters

I think Duncan C's 'user interface' is excellent. It is clean, simple and elegant.
Using individual LEDs is much better than digits. IMHO it is much more flexible, and avoids the ambiguity of digits.  +1 for the concept.
However, I would make it 'softer', and use a lot fewer components.
By going 'softer' you could have more flexibility, which would give you the ability to expand the useful resolution of the 'clock'.
Duncan C made a very important point that digits are useless if a digit changes during the photograph. However, that is still a potential problem with the three lines of LEDs. When the exposure time is longer than the duration of the 'lower digit' line of LEDs, information is lost.
Certainly Duncan C's design could be speeded up or slowed down to adjust for that, but it has a built in resolution limit because it counts in 10's. Imposing the digital idea of '10' on an analogue system (which is similar to a child's abacus) loses some of three inherent flexibility in the fundamental superiority (in this case) of an analogue display. I suggest making it 'soft' so that the system can be 'tweaked' in software after the electronics are completed.
Instead of fixed function decade counters, use shift registers . Then there is complete flexibility to change the 'user interface' in software.
To reduce the number of components use shift registers designed to drive LEDs.
For example, Texas instruments make many LED-drivers. The lowest cost ones, in Dual-In-Line packages (which can be used in a breadboard, and so would be easier to prototype) that I found on RS were TLC5916/TLC5917. Each device drives 8 LEDs, so Duncan C's design would use 4. This is more expensive than decade counters. However, I think the cost (about 5GBP) may be worth it.
One benefit is they are 'constant current' drivers, and so eliminate the current-limiting resistors on each LED. Each device uses one resistor to program the current for all 8 LEDs. That won't save much money, but it will save a lot of wiring.
These shift registers are fed a pattern of data bits, one at a time, using a second 'clock' signal to tell the shift-register when the data bit is valid. Toggling the clock loads the data bit. So you could cascade them, end-to-end, exactly like cascaded counters. To reduce the CPU load, the input to the chain of shift registers could be loaded autonomously, 8 bits at a time by using the SPI peripheral in the Arduino.
Alternatively, you could use 4 pins to load data simultaneously, with one pin driving a shared clock. Those shift registers can operate much faster than even Arduino assembler (upto 30MHz/bit). So this needn't take much time.
The outputs of the shift registers do not change until a further signal is sent. Then they all change output simultaneously. So your cameras won't be confused by seeing the data being loaded.
So there is more software complexity than cascaded counters. However, there is no constraints on what data they show. For example, you might decide that you would like 20 LEDs worth of resolution, so that cameras have a wider exposure time and the frames can still be synchronised or 'positioned' relative to one another in time.
Anther advantage of this 'soft' behaviour is, you could add lots more LEDs and get pretty much any resolution you might need, using exactly the same hardware technology.
This approach shares an advantage of Duncan C's design. Time is indicated by discrete points of light, and not shape. So it should be relatively straightforward to use image processing to process images. That might be very important if the cameras are video cameras.
Edit:
To clarify a few points.
It is purely software which determines the behaviour of the LEDs in a shift-register based approach. Hence it is practical and straightforward, to simulate decade counters. So the 'user interface' can not be worse.
The complexity of a chain of shift-registers is the same as decade counters, if you want to use them that way. However for a few pins more, the shift registers could be loaded independently, which might have some benefits.
Using constant current LED drivers reduces the number of resistors to wire by a factor of 8. TI and others sell devices with 16 and 24 LED drivers, so the number of packages might be reduced.
The decade counter has a built in restriction. Not suprising, it gives no more than 10% resolution. However if you need 5%, it can't do it.
The shift-register-based electronics could emulate a 'clock face', so if 5% is needed, use 20 LEDs for that part. If 1% is required, add some more shift registers and LEDs
Summary:
Duncan C's concept of using an 'analogue abacus' display is, IMHO, a more robust user interface than LED Arabic digits.
However, IMHO a hard-wired implementation using decade counters is an unnecessary restriction, limiting resolution. Shift registers make the display 'soft'. Wiring up shift registers is the same complexity as decade counters. Using LED drivers, saves a lot of wiring.

Your suggestion of shift registers would be more flexible, but I think it's waaaay past the OP's comfort level in working with hardware. He pushed back on my suggestion, which would use 3 chips and very few connections. As for the resolution of my suggestion, if the shutter is open for more than 1 MS, a range of LEDs will be lit, showing the start and end time for the shutter. If the shutter is open for 5 ms, 5 of the thousandths LEDs will be lit in the picture. Beyond 10 MS, you'd lose MS level of detail because all the "thousandths" LEDs would be lit, but I think that's ok.

@DuncanC - 1. Using shift registers can be exactly the same electronic complexity as decade counters. 2. using LED drivers removes 26 components, which is quite a lot of extra work to build and debug. 3. Kozuch wrote "I am a SW programmer ...", so shifting complexity to software appears to be the most helpful thing to do. 4. It is straightforward to emulate a decade counter in software, so the user interface can't be inferior. I agree with your analysis. My point is extremely simple and pertinent; the user interface is improvable to suit the application after the electronics completed.

your point on flexibility is well taken. What 26 components does your approach remove, though? If you read my description carefully, I recommend driving the LEDs directly from the 4017, and wiring each set of 10 LEDs with a common cathode and a single current limiting resistor between each common cathode and ground. Only one LED in each "decade" will ever be lit, so that should work perfectly. My design needs 3 chips, 3 resistors, and 30 LEDs. LED drivers would eliminate the 3 resistors, but use several more ICs.

Actually, after reading up on the TLC5916/17 (and the related TLC5925) I found that it was both a shift register AND LED driver in 1 package. Each chip takes a resistor that sets the output current for all the LEDs it drives, so I think the component count would be nearly identical. If you used two TLC5925's (each of which will drive 16 LEDs) then you'd need one less current limiting resistor, but a difference of 1 or 2 resistors is not important.

Assuming you camera's shutter is fast enough to capture a display updating every millisecond:
Get individual digit seven segment (LED) displays. The ones with multiple digits together are usually multiplexed and that might not work for your application(the multiplexing frequency would have to be higher than 1000 Hz or only one/some digits would be visible at a time). Using single digit displays, hook up each digit to a shift register such as the 74HC595. Then you only need two Arduino pins to control each digit (Data and clock, latch clock can be shared by all the shift registers). Use protection resistors for each individual segment diode and mind the current limit of the shift register when lighting all segments.
At 16 MHz you have 16000 instructions per ms so that shouldn't be an issue.
I don't know too much about LCD displays, but with LED's and a latching shift register transitions should be update pretty much instantaneous(from a millisecond perspective).

No, you have 16,000 instructions per ms. (16,000,000 per seconds / 1,000 ms in a second)

Yes, you are right, corrected the answer(you are also welcome to edit).

You wrote "The ones with with multiple digits together are usually multiplexed and that won't work for you application(only one digit will be visible at a time)". That is likely incorrect and may be misleading. For example if the application is a video camera, the 'shutter speed' is 16ms or 20ms. Even at 1/1000 of a second, one millisecond, there is enough time to draw all of the digits of a multiplexed LED, so that it looks fine.

Except that the display update isn't going to be synchronized with the shutter, so when the display changes, a given picture will likely contain lit LEDs from both values. If the shutterspeed is 20 MS and the clock changes it's screen every MS, the picture will capture 20 different values, which will be an indecipherable mess.

@gbulmer I didn't consider the shutter time, but it would have to be fast for a 1 ms timer display. I usually multiplex at 200 Hz(whole display) when done on the MCU, to avoid burning too many CPU cycles, but of course it could be done faster or with a dedicated driver IC multiplexing at 1000+Hz. I updated the answer to be more elaborate.

@user2973 - I think my answer adds to Duncan C's, which I believe is a very good way to go. Having said that, I think it is completely feasible to update the all of the digits in a multiplexed display at 10kHz or faster to avoid any shutter speed problems, using less than 20%. However, Duncan C's approach is much more robust than human readable digits, so I'd still recommend doing that. My answer improves on the flexibility and electronic complexity of Duncan C's implementation.

@DuncanC - my comment was addressing the assumption that "(only one digit will be visible at a time)" user2973 has updated the answer to incorporate my comment. I fully agree with you, using something more 'analogue' is much better than arabic digits. Your proposal is like a child's abacus and is demonstrably superior to arabic digits for many purposes.


text:
How to program a CAN-BUS Arduino shield to control car windows?
My project is to control car windows using voice recognition. I have successfully controlled some LEDs using the EasyVR Arduino shield using and Arduino MEGA. Now I want to take control of the windows using the CAN-BUS arduino shield.
Because the car that I own doesn't have an OBD-II connector, I am using two Arduinos with two CAN-BUS Arduino shields making one a sender and the other a receiver. How can I program the CAN-BUS Arduino shield to make a simulation of the car's windows?
CAN-BUS shield that I am using: https://www.sparkfun.com/products/10039
Arduino Mega: https://www.sparkfun.com/products/11061

Are the Arduinos going to directly control the window motors or do you want to talk to the car's door module controller and command it (also, does your car have a CAN bus)?  Do you just have 2 CAN shields so you can test talking to the door module...you need to clear that up.

No my car doesn't have an OBD-ii module, and yes I have 2 CAN-BUS shields mounted on 2 ardnino boards (Arduino Mega). My problem now is how to programme the shields so that I can simulate the connection with the car's CAN-BUS.            Thanks in advance

You would need to find the command specifications for a CAN-connected window controller, and implement something which matches.

Yes that is my problem, I can't find those commands for the CAN-BUS that will control the windows or the headlights. I am beginning to feel that there is nothing like that.

What model car do you have?  Most cars do not have the ability to control power windows from the car computer.  Late model cars will have the ability to control the window motors using bidirectional functions on a scan tool.  On any car, the window motors have two wires, if one wire is given power and one ground it will spin if you switch the wire that gets power with the wire that gets ground it spin in the opposite direction.  In my experience the way power windows work are both wires are ground while the switch is in the neutral position and by flipping the switch the switch will disconnect one of the grounds and replace it with a power.  Find a wiring diagram for your car, and look at how the windows are controlled.
Get a 2 relay breakout board such as this one (make sure you check the current ratings):
http://www.amazon.com/SainSmart-2-CH-2-Channel-Relay-Module/dp/B0057OC6D8/ref=sr_1_1?ie=UTF8&qid=1400730995&sr=8-1&keywords=arduino+relay+12v
Connect the ground wire to the normally closed (when no power is applied to the relay this is connected to the output wire) side of both relays and the 12v power to the normally open (when power is applied to the relay this is connected to the output wire)side of both relays.
In order to control the relay breakout board you choose one io pin per relay and set it as an output, then connect those pins to the corresponding pin on the breakout board. Set one of the pins to high (you apply power to one relay) the motor now has a power and a ground connection, set the opposite pin high to spin the other way.
I would place this in the driver side door underneath the window master switches because you can have access to every windows wires as they come out of the master switch.
Some late model cars will have a different set up than the one described, but the window motor will only have two wires (it is just a brushed DC motor) just find the window motor and hookup there.
I hope this helps.

So the motor is designed to be powered in blocked condition? (window fully opened/closed) I would expect there to be an over current protecting circuit to prevent overheating the coils. Could be built into the motor of course.

Sorry my response took so long.
Yes they have a circuit breaker. Here is a nice article detailing the various systems:
http://auto.howstuffworks.com/power-window2.htm

the central lock system will close the car doors and close the windows, i think you should build your system with the same idea, dealing with windows motors as normal motor without special commands for the window


text:
ArbotiX-M Problem uploading to the board
I have an ArbotiX-m Arduino board, and have followed the setup guide on Trossen robotics all the way to the 5th step. I have a Mac running OS X 10.10 and use Arduino 1.0.5. I installed the necessary drivers and copied the files to the Sketchbook directory. When I try to load the sample ArbotiXBlink program:
// Pin 0 maps to the USER LED on the ArbotiX Robocontroller.
int led = 0;

// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
}

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

It verifies just fine, but when I click upload, I get:
Binary sketch size: 1,088 bytes (of a 65,536 byte maximum)
avrdude: stk500_recv(): programmer is not responding

Any ideas?
EDIT: The board was trying to get power from the 5V instead of USB

I figured why my board wasn't responding! Apparently, the power pin was connected to the 5V supply instead of usb. Silly me!

Please add it as an edit.

No, this is proper as answers are the vehicle for solutions (even when they come from the asker), while question edits are the means of adding additional detail about the problem.


text:
Getting the highest value from analog reading?
I am doing a project using an FSR (Force Sensitive Resistor), I'm currently reading values with no problem every 100milis. I want to output via Serial.print the highest value, I've read.
I am having a hard time doing so. The project is use to "measure" the strength some projectiles hit the sensor. I want to get the highest value.
This is the code I have until now.
int fsrPin = 0;     // the FSR and 10K pulldown are connected to a0
int fsrReading;     // the analog reading from the FSR resistor divider
void setup(void) {
  // We'll send debugging information via the Serial monitor
  Serial.begin(9600);
}

void loop(void) {
  fsrReading = analogRead(fsrPin);

  Serial.print("Analog reading = ");
  Serial.println(fsrReading);     // the raw analog reading

  delay(100);
}

You need to learn about if and > (Greater-Than).

Majenko, thanks... I dont know how to use it when using the delay, since.... I want to have a fast rate reading, and once I output it, reset it so the next measure will compare again, as to output multiple impacts.

Ah, so you want the maximum value within the 100ms time frame then?

Majenk, 10ms, can be changed just used it for testing. (For this problem, I know I have to compare "last value" against "current value" and save the greater, but I am having trouble with, how fast should I "sample", and how to reset the "last value" variable, in order to be ready for the next impact.

You reset the "last value" by setting it to 0. As to when that happens, that is entirely up to you and is only something you can decide. How fast to sample? Well, I'd say as fast as you possibly can. There is no use for delay() in your code at all.

mmm I think it does... since lets say for the sake of an example: on time (lets call it t) t=0 measure=0, t=1 measure=10, t=2 measure=12, t=3 measure=30, t=4 measure=25, so on.... so, I want to output, this impact was 30, now I need to reset? so I start doing the same for the next impacts?

No, what you want is "Until t == 4 keep reading the analog and comparing it.". Once T has exceeded 4 (or whatever time you decide on) you print the maximum and reset. I will knock up a brief code to demonstrate:

You don't want to delay ever. Instead you want to change your thinking to "X miliseconds have passed, time to print and reset":
int maxval = 0;
uint32_t lastSample = 0;

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

void loop() {
    if (millis() - lastSample > 100) { // Every 100ms:
        lastSample = millis();
        Serial.println(maxVal);
        maxVal = 0;
    }
    int reading = analogRead(0);
    if (reading > maxVal) {
        maxVal = reading;
    }
}

Every 100ms it will print the maximum analog value read during the past 100ms.
You can replace the 100ms with any other value you choose, or even with a check to see if a button has been pressed, in which case you get the maximum reading since the last time the button was pressed:
// global
bool lastButtonValue = HIGH;

// in loop()
if (digitalRead(3) != lastButtonValue) {
    lastButtonValue = digitalRead(3);
    if (lastButtonValue == LOW) {
        // ... do the print and reset
    }
}

how short an event (<1ms) and rate of sampling determine chance of missing an impulse force peak.  software peak detection by a loop is a poor way for projectile peak force or g readings.

@TonyStewart What choice do you have though on an Arduino? All you can do is sample as fast as you can - theoretically at a frequency at least twice the reciprocal of the duration of an impact. Using free-running mode and an interrupt to read the values would give access to faster sampling rates, but that is beyond the ability of the OP I feel.

@Majenko Thank, man, you approach was what I was looking for, you are right the approach should be delay-less, and should be "X time has passed need to print and reset" I am getting good data now.... THANKS!

You add a small transistor emitter  follower and output to a small plastic cap to peak fast and hold as long as the interval between sampless. driving the input low after a slow decaying reading, resets the cap voltage to zero, momentarily, from a bidirectional port, then waiting for the next projectile.  This can be improved greatly but far better than trying to sample a detector.

@TonyStewart Maybe on the electronics.SE site that would be a good idea, but this is the Arduino site. Here it's done (for better or worse) using an Arduino.

ok but the design is flawed, I am pointing out why and how to fix that

@TonyStewart Whatever. Better would be to use a proper op-amp based peak detector circuit or you'll be losing voltage from your sample cap, no matter how huge you make it.

it is a matter of how large the impact voltage is created and yes I know it can be greatly improved as stated. (if any interest in making it work at all.) for example a PNP followed by an NPN has no offset with a storage cap in between for peak and hold or a Comparator and cap to charge if Vin>Vstored then a switch to dump after reading or....


text:
CAN Bus without Transceivers
I am trying to set up a CAN-bus with its two nodes on the same Arduino. By Using an Arduino DUE without any transceivers. As my first experiment, I want to send a message from one CAN unit to the other. But so far I have not been successful to see any signal on the bus. (I am using an Oscilloscope)
Here is the detail of my effort:
I have used this(1) library, and I want to run the CAN_EchoTest example(2).
As for the physical layer, I have created a circuit, according to a Method that is suggested here(3), here(4), and here(5). I set the transmission rate to 5Kbps, (lowest possible value provided by the library), to make sure that noise and propagation effects are minimal.
I implemented this mentioned Method to the Arduino board, using the Board's Schematics(6). In other words, I assumed that:
CANTX1 in the schematics, refers to PIN with the label '53' on the board.
CANRX1 in the schematics, refers to PIN with the label 'DAC0' on the board.
CANRX0 in the schematics, refers to PIN with the label 'CANRX' on the board.
CANTX0 in the schematics, refers to PIN with the label 'CANTX' on the board.

And I assumed the library that I am using configures the mutual PINS (DAC0 and 53), in a way that CAN controllers will be using them exclusively. I am not sure about the pair of diodes that I used: Vishay SS34A.
what is missing/wrong? Please be patient regarding any rookie mistakes. I can Provide further information if requested.
Thank you in advance
(1) github.com/collin80/due_can
(2) github.com/collin80/due_can/tree/master/examples/CAN_EchoTest
(3) www.mikrocontroller.net/attachment/28831/siemens_AP2921.pdf
(4) electronics.stackexchange.com/questions/30564/is-a-can-enabled-microcontroller-sufficient-to-drive-a-can-bus
(5) www.keil.com/download/files/canprimer_v2.pdf
(6) www.arduino.cc/en/uploads/Main/arduino-Due-schematic.pdf

You might wanna look at this question. http://electronics.stackexchange.com/questions/30564/is-a-can-enabled-microcontroller-sufficient-to-drive-a-can-bus. And you should check weather an atmega328p-pu has support for it.

Thank you man, That was supposed to be link number 4, I have made a mistake of copying the same link for number 4 and 5.

I see... I'm not that familiar with CAN so I won't be able to help you out a lot. I've only repaired and modified an existing CAN system with transceiver. Though, I've edited your question by making them actual links. It needs to be approved now.

Ensure diode polarities are correct. Method should work ok. Using voltmeter measure RX pin voltage when no "traffic" - should be "high". Measure when sending - should drop. SS34 diodes are OK. Resistor can probably be say 10k but 3k3 should be OK.

SS34 datasheet here Ensure line side goes to TX pins. Use meter diode-test or Ohm test.

I made it work. I guess the problem is that the library acts irrational when you try to set a frequency other that the library's default frequency: CAN_DEFAULT_BAUD. (defined in due_can.h).
for changing the frequency I just change the default value itself.

You will have to play some games to make it work.  CAN is a bus with dominate and recessive states.  This is how it arbitrates.  When a unit starts sending a message and another starts concurrently they will both keep transmitting until one is sending a dominate signal and the other is recessive.  At that point the unit placing the recessive signal on the bus backs off and waits until the bus is idle before re-trying.
You can simulate this with a few transistors (not real CAN but will work).  Monitor the bus with the receive side and drive it with the transistor with a pull up resistor.  When the transistor is on that is the dominate state when the transistor is off that is the recessive state.  This automatically places a priority order to each unit. Also you cannot operate with 1 CAN device, each message has to be acknowledged by another. It is imperative that you receive what you send.  Transceivers are very cheep on eBay and they have the Maxim chip which is very good.
Good Luck,
Gil