text:
Stray\342 inprogram
What does this mean?? Stray\342 inprogram
// Basic sketch for EmonWRT
// Version 1.2

#define FILTERSETTLETIME 15000 // Time (ms) to allow the filters to settle before sending data

const int CT1 = 1;
const int CT2 = 1; // Set to 0 to disable CT channel 2
const int CT3 = 1; // Set to 0 to disable CT channel 3
const int VOLT = 1; // Set to 0 to disable

const int UNO = 1; // Set to 0 if your not using the UNO bootloader (i.e using Duemilanove) – All Atmega’s shipped from OpenEnergyMonitor come with Arduino Uno bootloader
#include <avr/wdt.h>
#include <JeeLib.h> // Download JeeLib: http://github.com/jcw/jeelib
ISR(WDT_vect) { Sleepy::watchdogEvent(); } // Attached JeeLib sleep function to Atmega328 watchdog -enables MCU to be put into sleep mode inbetween readings to reduce power consumption
#include <EmonLib.h>
EnergyMonitor ct1,ct2,ct3; // Create instances for each CT channel
float power1, power2, power3;
float voltage;
const int LEDpin = 9; // On-board emonTx LED

boolean settled = false;
boolean firstsensor = true; // Just to know if a , must be added in the CSV output

void setup()
{
delay(10000);

Serial.begin(9600);
Serial.println(“emonWRT CT123 and Voltage v1.2”);
pinMode(LEDpin, OUTPUT); // Setup indicator LED
digitalWrite(LEDpin, HIGH);

if (UNO) wdt_enable(WDTO_8S); // Enable anti crash (restart) watchdog if UNO bootloader is selected. Watchdog does not work with duemilanove bootloader // Restarts emonTx if sketch hangs for more than 8s
ct1.voltage(3, 225, 1); // Voltage: input pin, calibration, phase_shift

}

void loop()
{

power1 = ct1.Irms; //ct.calcIrms(number of wavelengths sample)*AC RMS voltage
power2 = ct2.Irms;
power3 = ct3.Irms;
voltage = ct1.Vrms; // AC Mains rms voltage

// because millis() returns to zero after 50 days !
if (!settled && millis() > FILTERSETTLETIME) settled = true;

if (settled) // send data only after filters have settled
{
digitalWrite(LEDpin, HIGH); delay(2); digitalWrite(LEDpin, LOW); // flash LED
**Serial.println(“EMONWRT “);**

if (CT1) {
if (!firstsensor) Serial.println(" ");
firstsensor = false;
Serial.print(power1);
}

if (CT2) {
if (!firstsensor) Serial.println(" ,");
firstsensor = false;
Serial.print(power2);
}

if (CT3) {
if (!firstsensor) Serial.println(",");
firstsensor = false;
Serial.print(power3);
}

if (VOLT) {
if (!firstsensor) Serial.println(" ");
firstsensor = false;
Serial.print(voltage);
}

firstsensor = true;

//Serial.println(” “);
Serial.println(" ");

delay(100);

Sleepy::loseSomeTime(5000); // sleep or delay in seconds – see emontx_lib
}
}

Typographic quotes (“ and ”) are not part of C/C++ language for defining string literals.
For that you must use straight quotes (i.e. ").
Hence replace:
Serial.println(“EMONWRT “);

with:
Serial.println("EMONWRT ");

Typographical quotes might get automatically created when using a word processor (e.g. MS Word) to type your source code, or when copying code from a Word document into the Arduino IDE.
The best is to keep away from word processors when typing source code.

Indeed, this can be a very nasty and subtle issue with modern computers and tools - and it's not just word processors, for example, I had some of these sneak in when some command line instructions where copy and pasted though a collaboration chat tool.


text:
How do I change fuse bits - not communicating?
Currently I'm working on a project using an ATmega 2560 microcontroller card with a 10 MHz crystal. My main goal is to use the Arduino IDE to upload sketches to this chip to run my bread board circuit. In the beginning I had planned to use Atmel Studio to upload Arduino Sketches, but I decided to go with the more direct route. I am using two programmers, the Atmel ICE, and the Atmel AVR ISP MKii.
Anyway, here is my issue. I tried to use the Arduino IDE and the MKii to burn the bootloader to the chip. However, it did not work. It uploaded, but I was at that point no longer able to communicate with the device. When I switched to Atmel Studio, and used the ICE programmer, my chip could not be read and recognized (whereas before it could). I can't even program it. (I had bought two.)
I then figured I would try and read the fuse bits on the other programmer and burn the bootloader using Atmel Studio (since the Arduino IDE has no information on this), and I looked up the proper bits to change and then burned the bootloader. It worked fine, and I then changed the fuse bits which resulted in an error and now I again could talk to the device.
I am guessing that something is going wrong with the suggested fuse bits, but I do not know how to change them or how to fix this. The original fuse bits that I read from the device are listed below (before I messed it up).
I checked my wiring a billion times and it is all perfect. I just need suggestions to fix this mess, thanks.
BODLEVEL = DISABLED
OCDEN = [ ]
JTAGEN = [X]
SPIEN = [X]
WDTON = [ ]
EESAVE = [ ]
BOOTSZ = 4096W_1F000
BOOTRST = [X]
CKDIV8 = [ ]
CKOUT = [ ]
SUT_CKSEL = INTRCOSC_6CK_0MS
EXTENDED = 0xFF (valid)
HIGH = 0x98 (valid)
LOW = 0xC2 (valid)
LB = NO_LOCK
BLB0 = NO_LOCK
BLB1 = NO_LOCK

LOCKBIT = 0xFF (valid)

Detected device
Device name       ATmega2560
Device signature  0x1E9801

Make sure the crystal is connected and the proper capacitors are connected to it.

You can check your fuse bit setting here https://www.engbedded.com/fusecalc/
it will tell you what your current fuse bit setting is doing. and if you are really messed up with the fuse bit that you can not even talk to the controller now then the high voltage programming method is a way to fix this and set new fuse bits.

If AVR is bricked because of wrong fuses I suppose it's typically non-working external oscillator you need provide signal to particular AVR pin to get programmer working again. Thread related to unbricking http://www.avrfreaks.net/forum/locked-out-atmega-328p-possible-clocklow-fuse-byte-issue.

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:
Arduino PWM Frequency - Pros and Cons of Modifying
I am interested in using an Arduino Uno to produce an analog signal by running PWM through an RC low-pass filter.
I'll be controlling a highly dynamic object and need a clean voltage signal to avoid instabilities.  Per this calculator on RC designs, it's suggested that one strategy to reducing voltage ripple is to increase the PWM frequency.
With PWM configured to a default of 980Hz for pins 5 and 6, and PWM of 490Hz for the remaining pins, I've decided that this will create too much voltage ripple for my filter.  I've found resources that describe how to configure the registers to increase the PWM frequency rather drastically.
My question is very simple: Are there any disadvantages to using a higher frequency PWM?  Why is the default set to be so slow?
Thank you!

Aside from the clock (if using timer0), the only consequence seems to be in how the components you drive with the PWM handle the frequency. Some might heat up a bit more, and/or jitter less. Burning lasers may yield slightly different results.Ignacio makes a good point about servos, too.

A PWM frequency of 490Hz means a period of approximately 2.041ms. This allows a high period of 2ms, which is the maximum pulse length required by a large number of inexpensive servos. Obviously if your design uses no servos then this is not a consideration.
Timer 0 itself is used for the various Arduino timing functions (delay(), millis(), etc.), so if you change the frequency used for timer 0 then those functions will no longer have accurate results.

timer 0 is used for pins 5 and 6. So you better go with pins 9 and 10 (timer 1), or 3 and 11 (timer2), as to not break functions like delay, millis etc.

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


text:
avrdude: usbdev_open(): did not find any USB device "usb"
I was programing the arduino and things were going great.
Then I plugged in another chip, and went to burn a boot loader.
(New chips) now, I get:
avrdude: usbdev_open(): did not find any USB device "usb"

when I try to upload code to old chips, I get:
avrdude: usbdev_open(): did not find any USB device "usb"

ten times.
I have tried reseting, and it doesnt do anything.
when I plug the device in,
dmesg shows that the device responds to my PC
[526199.130716] usb 3-1: new full-speed USB device number 7 using xhci_hcd
[526199.149422] usb 3-1: New USB device found, idVendor=2341, idProduct=0043
[526199.149427] usb 3-1: New USB device strings: Mfr=1, Product=2, SerialNumber=220
[526199.149430] usb 3-1: Manufacturer: Arduino (www.arduino.cc)
[526199.149433] usb 3-1: SerialNumber: 649343332353518022F0
[526199.149579] usb 3-1: ep 0x82 - rounding interval to 1024 microframes, ep desc says 2040 microframes
[526199.149766] cdc_acm 3-1:1.0: ttyACM0: USB ACM device

IDE settings:
board: Audruino Uno
serial posrt /dev/ttyACM0
Programer: AVRISP mkII
I also tried AVR ISP
in the command line, I tried:
   avr-gcc -DF_CPU=16000000UL -mmcu=atmega328 -o Balls.out Balls.c
   avr-objcopy -O ihex -R .eeprom Balls.out  Balls.hex
   sudo avrdude -V -F -c stk500v1 -p m328 -b 19200 -P /dev/ttyACM0 -U flash:w:Balls.hex

each time, I get:
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00

How can I troubleshoot the Arduino Uno?
Is this thing broken?

You (or your IDE) are using the wrong command line arguments for an Arduino UNO - although connected via USB, as far as avrdude is concerned it is a serial device, not a USB one.  In the case of your linux box, the first one connected appears to be /dev/ttACM0

it is on /dev/ttyACM0

Yes, you need to make use of that information.  If you are using the IDE, try the various selection menus.  If you are using the command line, edit what you have now into your question and you'll get suggested corrections.

Ive tried variations. Im doing the exact same things that have worked previously. How does someone troubleshoot an arduino uno?

First, add yourself to the dialout group or whatever owns /dev/ttyACM0 and re-login so you can get the sudo out of there.  Next, which error message are you currently getting?  Are you still getting the USB one?  If you are just getting the not responding complain, that points more towards a bad baud rate, an unreset board, missing bootloader, or damage.

the usb error is when i try to burn a bootloader.
the programmer not responding is when I try to upload code

Sounds like you should describe (connection and command) your attempt to burn a bootloader.

Question has been abandoned without the followup necessary to resolve, voting to close.

I agree with @Chris. Because this question is needlessly complex. I'll re-ask the question with my answer.

Generated from IDE
Because this is a generic error, I'll answer it. I was getting this on STDERR when using the IDE:

avrdude: usbdev_open(): did not find any USB device "usb"

This is because in the IDE I was using

Sketch → Upload Using Programmer [Ctrl + Shift + U]

However, I should have been using

Sketch → Upload [Ctrl + U]

Ultimately the comments clarified that this error was produced when trying to burn a bootloader rather than when trying to load a sketch.  Burning a bootloader can only be accomplished by means of a programmer.  It is unclear what programmer was available to the original poster - specifically if it was one connected via a (virtual) serial port or one connected as a native USB device.

@ChrisStratton new question with answer

Evan, you deserve a place in heaven for this answer!


text:
seeeduino can-bus shield v2: can't read can bus and write on SD card
I'm using a seeeduino V4.0 and a CAN-BUS shield v2.0 with industrial grade SD card.
I'm using the default library given by the wiki of seeed.
I've simulate a can bus with two mcp2515. I can read it without trouble and everything is fine.
I can write/read on the SD card with the exemple given in the SD library.
But when I use this example, the can bus and SD card start without error. The can bus read normally and show the can bus data. But when I read the SD card, the file is created but completly empty.
I've tried to modify to write on a .txt instead of .csv and when I try a
myFile = SD.open("test.txt", FILE_WRITE);
if (myFile)
{
  ...
}
else
{
  Serial.println("error: file not reachable");
}

The "myFile" return false.
ps: I don't ask a lot of question here. Sorry for bad formating my question.

I don't have any good ideas, so here's one bad idea: print something showing that it made it to myFile.close();  You may not have any writes until you close(), flush(), or fill a sector.  Given what you've shown and what I've read about the shield etc, it seems like this shoudn't be a problem though.  Which Arduino are you using?  You did not change the CS selection on the board right?

I got the same "bad idea" but even with the close() (and withouthe the if(myFile)) The SD card don't write anything. If I process to write before using MCP2515, it works fine.
It look like a problem with the ISP to determinate the slave to talk to.
My board is a seeeduino V4.0

That is more or less what I think, but I didn't find anything confirming that when I went looking through the code of the two libraries.  At some point I may try setting up an UNO with an SD card and some SPI device as a stand-in for your MCP2515 (I don't have one of these).  Though, by then someone else may already have answered.

I did more digging, but I'm not turning up anything clear.  In their example flagRecv should be volatile qualified, as volatile unsigned char flagRecv = 0;  But I have little confidence that this is actually the problem.  I kind of expect that as a bug it would manifest differently if at all in this usage.  It should be fixed though in any case.  If it actually solves it though, let me know and I'll stick it as an answer.

Thank you for your help.
The volatile don't help. Still the same issue.
I tried to force the SPI to use the slave 4 (SD) and not the 9 (CANbus)
digitalWrite(4,LOW);             digitalWrite(9,HIGH);              if (!SD.begin(4)) {               print error             }             print success             myFile = SD.open("can.txt", FILE_WRITE);
and put ss 9 to low right after that. It show a success
It read as usual but still nothing on the SD.
Look like the spi is saturated by the mcp2515. If I remove the sd card, I got an error.

Despite the "the library example must be correct, It's work for other people before you", I'm not sure a lot of people make it works.
I've seen that even when the mcp2551 don't receive anything on can bus, the SPI bus is saturated by the mcp2551.
The solution was to use a simplest library make for 8MHz cristal chip. Modify it to works with standard 16MHz and use the interrupt pin (pin 2 on board) as interrupt.
If anybody got the same issue, just post a comment here and I'll do a better and more complete response.
Thank you very much @Timemage for your help

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


text:
Execute Code While Refreshing a 7 Segment LED Display
I'm using the following library to drive a 4 digit, 7 segment LED display:
http://playground.arduino.cc/Main/SevenSegmentLibrary
The display is showing the temperature which it gets from a DS18B20 temperature sensor.  Since the LED display constantly needs to be refreshed, when the code runs to get the current temperature, the display temporarily turns off because the LEDs are not being refreshed.  The code I am using is below. Is there anyway to prevent the LED display from turning off while the temperature request code runs?
#include <SevSeg.h>
#include <OneWire.h>
#include <DallasTemperature.h>

SevSeg sevseg;

unsigned long timer; // the timer
unsigned long INTERVAL = 30000; // the repeat interval (30 seconds)

#define ONE_WIRE_BUS 2
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

void setup() {
  byte numDigits = 4;
  byte digitPins[] = {A2, A3, A4, A5};
  byte segmentPins[] = {8, 10, 6, 4, 3, 9, 7, 5};

  sevseg.begin(COMMON_CATHODE, numDigits, digitPins, segmentPins);
  sevseg.setBrightness(90);

  // Get the initial temperature and show it on the LED display
  sensors.begin();
  sensors.requestTemperatures();
  sevseg.setNumber(sensors.getTempCByIndex(0), 1);
  timer = millis(); // start timer
}

void loop() {
  if ((millis()-timer) > INTERVAL) {
    // Reset the timer and get/display the current temperature
    timer += INTERVAL;
    sensors.requestTemperatures();
    sevseg.setNumber(sensors.getTempCByIndex(0), 1);
  }

  sevseg.refreshDisplay(); // Must run repeatedly to refresh the LED display
}

The problem here is that the display is driven using a timer interrupt.  The temperature sensor, being a one-wire device, has to have very careful timing to communicate with it.  As a result it disables interrupt so it has exclusive use of the CPU and can properly predict its timing while it's communicating.  And so the display can't refresh at the same time.
So what can you do?  Well, nothing really.  You can't have perfect timing for the temperature sensor while at the same time interrupting it for displaying the value.
So there's really two main options:

Change the temperature sensor.  Use an SPI or I2C temperature sensor that has a real hardware interface to communicate with it so you don't have to use big-banging.
Change the display.  A non-multiplexed display or a display with its own built in driver (most often with some serial protocol like I2C or UART) would mean you don't have to use interrupts to update the display.

Basically you have two technologies that won't sit together well on the same chip.

Update:
I missed the sevseg.refreshDisplay() function call since the website had scrolled it off the bottom of the code block.  Bah!
Ok, so it's not using an interrupt.  That could be a good thing, or it may be meaningless.  It takes time to do the temperature reading, and it's that getting in the way of the refreshing.
There's a chance you may be able to push the update "into the background" by attaching it to a timer interrupt, but if the OneWire communication does disable interrupts then the problem will still persist (I don't have OneWire to hand to look at the code right now).

I don't think that library uses a timer interrupt. See sevseg.refreshDisplay(). Communication between the arduino and one-wire device will only take a few milliseconds. Not enough to be noticeable. The big problem is that the Arduino wait a while between requesting a measurement, and retrieving the measured value.

@Gerben Oops - that line was scrolled off the bottom of the code area - I completely missed that.


text:
Why does my analogRead work on Teensy but not Arduino Uno?
I have successfully made a voltage measurement circuit on my Teensy 3.1 that reads a voltage coming out of digital pin 0 set high and coming back into an analog pin A0 to read voltage.
Basically:
int timer = 100;
int ColA = 0;
int Output;

// Setting digital pin functions

void setup()
{
  Serial.begin(38400);
  pinMode(0, OUTPUT);

}

// Program

void loop()
{
  digitalWrite(0, HIGH);
  delay(timer);
  Output = analogRead(A0);
  Serial.println(Output);
  delay(timer);
}

It works fine with my circuit on a Teensy 3.1 running 3.3v however when i run this code on an Arduino Uno running 5v wired exactly the same way I just get this print out of numbers that cycles back and forth from ~128 down to 0 and back constantly.
Any insight on the differences here would be great. I need the 5v micro-controller to run a 4051 multiplexer!

What happens if your remove the digitalWrite from the loop and put it in setup? And do you have an oscilloscope? That'll tell you what electrickery is happening.

If you're still using D0 as your output on the Uno then yes you are doomed to failure.
D0 and D1 are the serial port. You are using that to communicate with the PC. You cannot use them for any other purpose at the same time.
Pick a different IO pin to be your voltage source.


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

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

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

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

Remote Control Bluetooth  Specifications:

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

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

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

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

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

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

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

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


text:
Piezo not making sound
I've used the piezo on other projects with no problem, but for some reason this project isn't working out so hot.
Here's a photo of my current set up.

Here's the basic code that I presumed would make a sound, but no such luck.
void setup() {}

void loop() {
  tone(12,260);
  delay(10);
}

Not sure where to begin debugging this...

I can't see any wires connecting to the Piezo.

@Majenko 2 and 6 on the breadboard connect to the piezo.

No they're not - they're on the wrong side of the board.

As Majenko pointed out, the wires are not connected to the piezo.  By moving the piezo to the correct rails on the other side of the board, the circuit would be completed and the piezo should work.
Edit:
Building on Nick Gammon's comment, the rows of each side of a breadboard are not connected (to allow DIP packages).

To explain a bit more: for each number abcde are interconnected, and so are fghij, but those pairs are not connected.

And the reason for this is: You can plug a chip into the middle of the board, one set of legs is on one side, and you can plug your breadboard wires into them, and the other set of legs is on the other side. If the sides were connected together, the chip wouldn't work.

Ah! Perfect. That did the trick. Thanks so much!


text:
Edit variables through Serial?
Hello in a previous question i was able to set variables through if statements
  const uint16_t inputLength = 512;
int ss = 0;
int bHold = 0;

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

 void loop() {
  if ( Serial.available() > 0 )
  {
    static char input[inputLength];
    static uint16_t i;
    char c = Serial.read();

    if ( c != '\r' && c != '\n' && i < inputLength - 1)
      input[i++] = c;

    else
    {
      input[i] = '\0';
      i = 0;

      uint16_t array[80];
      uint16_t j = 0;

      if ( !strncmp(input, "ss", 2) )
      {
        char* p = input + 2;
        while ( (p = strchr(p, ' ')) != NULL )
          array[j++] = strtol(p, &p, 10); //

        for ( uint8_t i = 0; i < j; i++ )
        {
          ss = array[i];
          Serial.println(ss);
        }
      }

      if ( !strncmp(input, "bHold", 5) )
      {
        char* p = input + 5;
        while ( (p = strchr(p, ' ')) != NULL )
          array[j++] = strtol(p, &p, 10);

        for ( uint8_t i = 0; i < j; i++ )
        {
         bHold = array[i];
         Serial.println(bHold);
        }
      }

      if ( !strncmp(input, "Whos There", 10) )
      {
        Serial.print("me");
      }
      if ( !strncmp(input, "hello", 5) )
      {
        Serial.print("hi");
      }
      if ( !strncmp(input, "sa", 2) )
      {
        Serial.print("  ss= ");
        Serial.print(ss);

        Serial.print("  bHold= ");
        Serial.print(bHold);

        Serial.println(" ");
        Serial.println("==============================");
      }
    }
  }
}

if works! but if i keep adding variables i have to keep adding if statements and this will get longer. so then i went with code like this that allows me to set all variables at once
#define INPUT_SIZE 30

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

}
void loop()
{

  while (Serial.available() > 0) {

    int _mode = Serial.parseInt();
    int _ss = Serial.parseInt();
    int _bHold = Serial.parseInt();

    if (Serial.read() == '\n') {
      ss = _ss;
      bHold = _bHold;
      mode = _mode;

    }
  }

}

this works awesome! but i have to set all variables at once. my question is is there a way i can simply input a command like ss = 10 press enter then bHold = 30 and not have to input any other variable?
thanks i advance. please point me in right direction  Maybe make a function?

For this kind of user interaction you might find my CLI library quite useful - it takes the drudgery out of parsing user input. https://github.com/MajenkoLibraries/CLI

Somewhere along the line you have to tell your program how to map names to actual variables. Once you have compiled your program it forgets the names of the variables - those only exist in the source code.
So you have to have some other manual list of those variable names - be that in the form of if(...) statements, or an array of structs with the name in them, or whatever.
There's no getting away from it - you need that manual mapping in some form or other.
The closest you could get would be to set up some kind of hash system using structs and linked lists, whereby you could set any key/value pair, but then of course your program would still have to know to look for certain keys in the hash to do things with them, so that would be pretty pointless since you've just moved the variable mapping from one place to another.

You can store variables on the fly in a simple array or linked list.
A linked list would probably be better, but for now we'll just use an array.
const int MAX_VARS = 10;
const int NAME_SIZE = 16;

typedef _var
{
    char  name[NAME_SIZE];
    int   value;
} Var;

Var variables[MAX_VARS];
unsigned int var_count = 0;

void loop()
{
    char *command = getSerialInput(); // get a line of input from the serial stream

    // parse the command "set varname=value"
    if (strncmp(command, "set ", 4) == 0)
    {
        char *new_name = command + 4; // skip the 'set '

        char *ptr = strchr(command,'='); // find the equals character
        if (ptr != NULL)
        {
             *ptr = '\0';              // Break the string in half about the '='
             char *new_value = ptr+1;  // Everything after the equals is the value

             // Now we have a parsed variable name, and value
             // Have we already stored this variable?
             int i;
             for (i=0; i<var_count; i++)
             {
                 if (strcmp(variables[i].name, new_name) == 0)
                 {
                     // Found an existing copy - update it
                     variables[i].value = new_value;
                     break;
                 }
             }

             // Did we find the variable already?  No - add a new one
             if (i == var_count && i< MAX_VARS)
             {
                 strncpy(variables[i].name, new_name, NAME_SIZE);
                 variables[i].name[NAME_SIZE-1] = '\0'; // fix any strncpy() overflow
                 variables[i].value = new_value;
                 var_count += 1;
             }
             else if (i == MAX_VARS)
             {
                 Serial.println("Out of variable slots");
             }
        }
    }
    // parse the command "get varname"
    else if (strncmp(command, "get ", 4) == 0)
    {
         char *new_name = command+4;
         int i;
         for (i=0; i<var_count; i++)
         {
             if (strcmp(variables[i].name, new_name) == 0)
             {
                 // Found an existing copy - output it
                 Serial.println(value, DEC);
                 break;
             }
         }

         // Did we find the variable already?  No - error
         if (i == var_count)
         {
              Serial.print(new_name);
              Serial.println(" - not found");
         }
    }
}
else
{
    Serial.println("HELP: \"set <name>=<value>\" or \"get <name>\"");
}

This would be better with dynamically allocated memory, so the programme only uses exactly what it needs.  But I wanted to show a way of storing a list of user input without complications.  Obviously this programme omits a lot of error checking too - like when you run out of array slots in variables; or when the user input is bad.


text:
Control servo motors with buttons and via web application
I have this assignment and I have been tinkering a long time about it. I need to make a simulation of a parking lot where servos would represent the ramps.
I will be using 2 Arduinos running the same script, one representing the entry ramp and the other one the exit.
Servos are controlled by reading a json request of an web application and manually by buttons. I have connected two LED's when the buttons are pressed. I would also need to make state when servo would be always up or always down (that would represent the off times of parking lot), should I add extra buttons for that? Any idea would be appreciated.
The problem I'm having with this project is that servos are not responding well on push buttons. They are shaking and very slow moving. And I think that it isn't a good solution to move the servos while they are sending application request because it can lead to conflict. Please help me there.
I have written pretty major piece of script, but it still needs adjusments. Any help is welcomed.
Here is the code:
#include<Servo.h>
#include<Ethernet.h>
#include <SPI.h>

Servo myservo;
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
char server[] = "ramp-rampcontrol.rhcloud.com";
EthernetClient client;
IPAddress ip(192,168,1,17);

int button_5 = 5;
int button_6 = 6;
const int ledPin = 3;
const int ledPinG = 2;
int time = 5*1000;
int val=0;
String content = "";
boolean begin1 = false;

void setup() {

Serial.begin(9600);
pinMode(button_5, INPUT);
pinMode(button_6, INPUT);
pinMode(ledPin, OUTPUT);
pinMode(ledPinG, OUTPUT);
myservo.attach(9);
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
// no point in carrying on, so do nothing forevermore:
// try to congifure using IP address instead of DHCP:
Ethernet.begin(mac, ip);
}
// give the Ethernet shield a second to initialize:
delay(1000);
Serial.println("connecting...");

// if you get a connection, report back via serial:
if (client.connect(server, 80)) {
Serial.println("connected");
// Make a HTTP request:
client.println("GET /api/actions?parking_id=39 HTTP/1.1");
client.println("Host: ramp-rampcontrol.rhcloud.com");
client.println("Connection: close");
client.println();
}
else {
// kf you didn't get a connection to the server:
Serial.println("connection failed");
 }
}

void loop()
{

val = digitalRead(button_5);
if (val == HIGH)
{
  performServoAction("up");

      digitalWrite(ledPin, HIGH);
      delay(1000);
      digitalWrite(ledPin, LOW);
      delay(1000);

}

val = digitalRead(button_6);
if (val == HIGH)
{
  performServoAction("down");

      digitalWrite(ledPinG, HIGH);
      delay(1000);
      digitalWrite(ledPinG, LOW);
      delay(1000);
 }

 while(client.available()) {
 char c = client.read();
    if(c == '{'){
      begin1 = true;
    }

  if (begin1) {
    content += c;
   }

  if (c == '}') {
      break;
    }
 }

  if (!client.connected()) {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
    performAction();
  }
  }

bool performServoAction(String action_type) {
if (action_type == "up") {
    Serial.println("doing up");
    myservo.write(95);
    delay(time);
   // lastRampStatus = action_type ;
   // notifyServerAboutAction("true", action_id);
    return true;
  }

  if (action_type == "down") {
    Serial.println("doing down");
    myservo.write(135);
    delay(time);
    //lastRampStatus = action_type;
  // notifyServerAboutAction("true", action_id);
    return true;
  }
}

 void performAction() {
  int nstart = content.indexOf("action_id") + 12;
  int nend = content.indexOf(",", nstart);
  String actionID = content.substring(nstart, nend);

    int nstart1 = content.indexOf("action_type") + 14;
   //Get position of "action_type" in a string, increment by 13
    (length of 'action_type":"')
    int nend1 = content.indexOf("\"", nstart1); // Get next position
    of '"' starting from nstart
    String actionType = content.substring(nstart1, nend1);
    //Return substring between this position
    performServoAction(actionType);
    Serial.println(nstart1);
    Serial.println(nend1);
    Serial.println(actionID);
    Serial.println(actionType);
    Serial.println(content);
}

Do the servos behave when moving after receiving the json command? You have the program waiting for 5 seconds after the servo is told to move 'up' or 'down' -  I don't see where a conflict could creep in to cause the servos to move slowly.

They just vibrate, and they dont react to the push buttons. I'm starting to think that it may be a hardware problem.

I would start with just some servo example sketches and make sure you haven't made a simple mistake. It happens to us all.

Yeah sounds like the problem is servo issue just play with a servo example and then expand.

Instead of using:
myservo.write(135);
You should use:
myservo.writeMicroseconds();
https://www.arduino.cc/en/Reference/ServoWriteMicroseconds


text:
Bluetooth connection and RX ,TX
I have connected a RN-42 bluetooth (TX-D0, RX-D1, VCC-5V, GND_GND) to arduino.The problem is that when I run this code ,nothing happens it just upload to infinite or it doesn't. I am checking with tera term. Is there a problem with the connection of the pins? Also when I pair my android phone to the bluetooth it says paired on the phone but the blue light of the bluetooth doesn't switch on, like it's not connected.
  #include <SoftwareSerial.h>// import the serial library
   SoftwareSerial Genotronex(1, 0); // TX,RX
   int ledpin=13; // led on D13 will show blink on / off
   int BluetoothData; // the data given from Computer

  void setup() {
  // put your setup code here, to run once:
   Genotronex.begin(9600);
   Genotronex.println("Bluetooth On please press 1 or 0 blink LED ..");
   pinMode(ledpin,OUTPUT);
  }

  void loop() {
    // put your main code here, to run repeatedly:
  if (Genotronex.available()){
     BluetoothData=Genotronex.read();
   if(BluetoothData=='1'){   // if number 1 pressed ....
  digitalWrite(ledpin,1);
  Genotronex.println("LED  On D13 ON ! ");
   }
  if (BluetoothData=='0'){// if number 0 pressed ....
   digitalWrite(ledpin,0);
   Genotronex.println("LED  On D13 Off ! ");
   }
}
   delay(100);// prepare for next data ...
 }

There is no need to use software serial on the hardware UART, the D0 and D1 pins are for communication with the PC, in line with what Owen answered try his suggestion.

Are you sure that the bluetooth module is already connected/paired correctly? Is your bluetooth module in master or slave mode?

VCC to 3.3V? https://www.sparkfun.com/datasheets/Wireless/Bluetooth/rn-42-ds.pdf

As commenter by RSM
The issue you are facing is because you are using pins 0 and 1
These are used by the arduino for uart.
So for starters please use any pin other that 0 and 1.  But if you insist that you do need to use these pins,  then you don't need softwareserial you can use the default serial itself, but you will need to disconnect the bluetooth while programming.

The simplest solution to this is to just unplug the Bluetooth module from the TX and RX ports and click to upload. Your sketch will be uploaded and you can plug the pins back.
For a permanent solution use the digital pins aside 1 and 0 because they are the same pins your computer uses to upload your sketch to the Arduino board.

If you use RX, and TX in default pin then it is not necessary that you should include SoftwareSerial library.

Try taking off the bluetooth module, this will allow communication with
the computer, not the bluetooth module. I had the same problems with my
hc-06, and have not solved the ladder yet.


text:
Multiple definition error in STM32CubeIDE
How do global variable declarations work?
For example:
In file1.c I am defining:
#define volt_add 0x20

uint8_t vol[8]= {0x53, 0x35, 0x05, 0x22, volt_add,0x00,0x00,0x00};

uint16_t EM_vol;

I need to use all above variables in file2.c.
I tried to define them in the global.h file and included that file in both file1.c and file2.c, but I am getting a multiple definition error, first defined here error.
How can I do it?

If you want global variable accessible from everywhere you include global.h, you'll need declaration of that variable in header (declatation only):
// globals.h:
extern uint8_t vol[8];

Anywhere else you'll #include "global.h"
But there must be one cpp or c file with:
#include "global.h"
uint8_t vol[8]= {0x53, 0x35, 0x05, 0x22, volt_add,0x00,0x00,0x00};

If you make this definition in header or more than one .c file, you'll get multiple definition error.
Another way would be make it static and make whole definition in the header, however each compilation unit will be using it's own instance and it won't be visible from other compilation units (compilation unit == every c file compiled into own .o file). This is issue on MCUs and if you even want to write into it, it'll be total mess (although nobody uses const correctness in C)


text:
How can an Arduino output a specific (i.e. 56 kHz) carrier frequency?
I'm working on a free space optics project to send data wirelessly between two points. To accomplish this I'm using an IR LED connected to an Arduino Uno that pulses with a 56 kHz carrier frequency for the transmitter and a second Arduino with a 56 kHz IR detector module for the receiver.
I tried using delayMicroseconds() between pin high and pin low commands in order to create the carrier frequency. This kind of works, but the frequency isn't always the same and any additional delays for pulsing the signal (i.e. the time required to call the function and decrementing) can change it.
Reading the datasheet for the ATmega328 it appears that there is a way to set a more accurate pulse using the chip's timers. Is that possible, and if so, how do you create a 56 kHz pulse using the timers?

What is the accuracy you need for your 56KHz frequency? I.e. what frequency range is acceptable in your project? I ask because using Arduino timers alone, precision has limitations.

55.5khz to 56.5khz would be ideal in order to maintain a high level of responsiveness in the detector.

It is indeed possible to generate a 56 kHz signal with an Arduino timer.
A timer actually can be seen as a special register, in the MCU, that holds a value (starting at 0) that gets incremented at a frequency that is the MCU clock frequency (16 MHz on Arduino Uno), possibility divided by a factor called prescaler. When that value reaches a limit, called Compare Match, that you specify, then two things happen:

The timer register value is reset to 0.
One ISR (interrupt service routine) callback function gets called (you can define it to point to your own code).

The idea is to use that ISR to change the output of a logical pin every time it is called (HIGH, then LOW, then HIGH...).
Now, in order to generate a 56 kHz square wave, you'll need your ISR to be called 56000 * 2 times per second (* 2 because you need to change the output value twice per period).
You can choose the prescaler value you want for a timer among the following list:

1 (clock frequency is not divided, hence 16 MHz)
8 (clock frequency is divided by 8, hence 2 MHz)
64
256
1024

There are two sizes of timers/counters on Arduino Uno (they are called timer/counter actually): 8 bits and 16 bits.
On Arduino Uno (ATmega328P), you have three timers overall, but some may be used by the Arduino core library or other libraries used in your sketches (you'll have to check that by yourself):

timer0 (8-bit)
timer1 (16-bit)
timer2 (8-bit): this one has more prescaling options (1, 8, 32, 64, 128, 256, and 1024)

Now you need to generate a 56 kHz wave from 16 MHz, hence, without prescaling, you would need to count to:
16000000 / (56000 * 2) - 1 = 141.857 (- 1 because a timer counts from 0 to this value and resets only after it has been reached)
From this calculation, we can draw two observations:

141.857 is not an integer and thus you won't be able to generate a wave of exactly 56 kHz.
Without prescaling, you need a 16-bit timer as 285 is not representable as an 8-bit unsigned integer.

From now you have two options:

Use a 16-bit timer (timer1), use prescaler = 1, and select 142 as the Compare Match; that will give you the following frequency: 16000000 / (2 * (142 + 1)) = 55944 Hz
Use an 8-bit timer (timer0), use prescaler = 8, and select 17 as the Compare Match; that will give less precision with the following frequency: 16000000 / (8 * 2 * (17 + 1)) = 55555 Hz which is still within the required range.

Now, regarding how to write your sketch for that, I advise you to check out this instructable which is very complete and very interesting to read.
Of course, the ATmega328P complete datasheet is also important if you want to understand, in the slightest details, what you are doing.
Some important notes:

An ISR is executed with disabled interrupts and must thus be as short as possible. In particular, there are several functions from the Arduino library that shall not be called from an ISR.
Arduino Uno clock is not very accurate (it uses a ceramic resonator instead of a quartz, which would have been much more accurate), so this means the output frequency will shift further.

Also when the specified limit is reached the hardware can toggle a pin. Thus there is no need to use ISRs at all. There will always be jitter with an ISR because an instruction cannot be interrupted once it starts. However the hardware will always toggle the pin at the desired rate.

It is somewhat surprising that the Arduino Uno uses a ceramic resonator, but a source for it is Arduino UNO FAQ (near "Does the Uno use a resonator or a crystal for the processor clock?").

I've found tone() useful for generating high frequency pulses on any pin. It should be able to handle 56 KHz. (Edit: As noted by jfpoilpret, the closest you could actually get on a 16 MHz Arduino is about 55.944 KHz)
The difficulty will obviously be combining it with your data signal. I don't think you could do that in software without resorting to low level code. It should be pretty easy in hardware though, since it's digital.
All you'd need to do is output your data signal on a different pin, and then combine it with the carrier using an AND gate. The combined signal can go straight to your IR transmitter.
If you don't have an AND gate handy then it's quite simple to make your own using a pair of transistors. Just search online for "transistor and gate".

Recievers often have active low outputs generally. If you connect the top of the LED to the 56khz, and the bottomto your data pin, when the data pin goes low you get IR output, which should make the reciever go low. No and gate needed, just an led and resistor. Only problem is being limited to whatever current io pins can drive.

The accepted answer of jfpoilpret is very well written, perfectly valid and in 99% of the cases I will do exactly what he explains. His solutions are well within your defined parameters, so they should work very well. But what is better than "very well"? Perfection! After all, the question is about generating a exact value. As said close enough is good in most cases (arguably all), and even when dealing with something as a clocks when 1 second need to be 1 second, you still have to suffer inherited parts imperfections.
What I will suggest is not always possible. In some cases, it's possible, but with much more hassle and effort than this case. Is it worthy depend on a case-by-case basis. My goal is mostly to show a alternative for future references that is better in somewhat fringe cases. This is written with novice Arduino users in mind that don't have extensive experience in electronics.
For more advanced people this probably will look too verbose and dumbed down. But I believe that, those same people probably already know it and don't need this answer. This is also applicable to every microcontroller and every manufacturer and architecture. But for other microcontrollers you will need to consult the correct datasheet to find out proper registers and prescale names and values.
In your case, you need a specific frequency and the nice thing about it, is that exactly 56 kHz actually can be achieved very easy (not counting practical imperfections of the parts). So this is also a perfect example case.
Generating a signal depends on the timers and clock source of the microcontroller, as explained well by jfpoilpret. His answer deals with the problem of one point of view only and that is fiddling with timers. But you can fiddle with the clock source too, or even better with both for synergy and awesome results. By changing the parameters of the environment, in this case hacking the system and replacing the clock source, we can deal with a specific problem with much, much more ease and simplicity.
First to remind, because of toggling the pin state, you need to execute the ISR two times more than the signal frequency. This is 112,000 times per second. 56,000 and 16,000,000 don't add up very nicely as pointed out already. We need to change either the signal frequency or tact frequency. Let's deal for now with an immutable signal frequency and find a better clock speed.
It would be most straightforward to choose a clock with some order of magnitude bigger than 56 kHz (or 112 kHz, but it is practically the same), as you only add zeros and this kind of math is simplest for most people. Unfortunately everything in this world is some kind of compromise with something. Not every value will work.
The first example is with a too low tact generator speed.
If you choose a 56,000 Hz clock you won't be able to do anything as you will need to call the ISR every cycle and can't do anything else. It is utterly useless. If you choose 10 times faster speed (560 kHz), you will have 9 (10 cycles for the timer to reach its max value - one cycle to call ISR function) microcontroller cycles to do your work and this quite possible can be not enough. You simply often need more computational power.
If you choose a value far too great at other hand, as 56 MHz the microcontroller simply can't work with it. It is way too fast. So, simply choosing the biggest value in the shop won't cut it either.
Original Arduino Uno R3 have a stock clock at 16 MHz, so anything slower that that is guaranteed to work. The next value that is an order of magnitude bigger than 56 and lower than 16 MHz is 5.6 MHz. This will lead to be able to call the ISR every 50 cycles and will create the perfect 112,000 Hz timer frequency. And your signal will be exactly 56 kHz. You will have 49 MCU cycles to execute your program between ISR calls, but it is still around 1/3 of the speed of the original clock. One can use 112 as base and use a 11.2 MHz clock and this will give a about 2/3 of the stock 16 MHz resonator. The ISR function will be called every 100 cycles and still generating a perfect 56 kHz signal.
However two major problems exist with these values.

The first problem severely depends on your needs: You sacrifice about 1/3 (with 11.2 MHz) of your maximum computational power to get the exact signal frequency that use an easy-to-find register value (OCR iirc). You may be fine with it or you may not.
The second problem is a hard showstopper: It is very easy to find values, but very often they simply do not exist as a manufactured clock source. This is Farnell's resonator web page that simply lack both 5.6 MHz and 11.2 MHz.

To circumvent this we can look at available resonator values and find out something else that can be used to generate exactly desired values. If we divide 56 by 4 we get 14 and luckily there is a 14 MHz resonator. This provides us with much higher speed and more power and with equally easy to find register value. To call the ISR 112,000 times per second we need to put value of decimal 124 or hexadecimal 0x7C in the OCR register, so with counting 124 cycles + 1 for calling the ISR, we get our desired perfect value.
N.B.

ISR - interrupt service routine (this is the code that is executed only on generated interrupts)
How big your program can be depends on the memory size! It has nothing to do with the clock speed and has nothing to do with how often you call the ISR.
When the microcontroller starts with program command a counter is incremented. If an interrupt is generated, the ISR is called and this value is stored in a special register. When the ISR code completes, the value of the program counter is restored from this special register and the program continues from where it was interrupted as if it had never happened.
I will give an extremely dumbed-down example. If you are a purist, I warn you: Nose and eye bleeding can occur.
Imagine you have to walk from somewhere to somewhere. The step-by-step route instructions are your main program and its commands. How fast you walk or run, depends on your "clock speed", but not on the route instructions (30 steps forward, 1 turn 90 grad. left, 10 steps forward, 45 grad. right, etc.) They are always the same. Now imagine a little kid or a greedy corrupt local politician untie your shoes now and then. This is the event that generates an interrupt. Then you halt after your last step, kneel and tie your shoe again. This is your ISR program.
Then you continue from the place you have stopped; you do not start from beginning. When you walk without a care in the world and with all the time, you don't care even if you have to tie your shoe every other step. If you however do it with time constrains, like running in 100 meters on the Olympics (or running from a hungry flesh-eating predator), stopping and tieing your shoes can have dire consequences. The same is with microcontrollers. Even if you execute only one line of code your program will continue, albeit slow. If you don't care about speed at all, it won't be a problem. If you have to do some time related, like using other timer dependent actions, interference can be very unwanted and problematic.
Less is more! A faster clock is not always better. Slower clocked devices use considerably less power. This can be a crucial point in a battery-operated device.
The needed cycles are derived from this formulae:
(clock speed / (prescaler value * needed ISR calling frequency)) - 1

TLDR: Desolder the ceramic 16 MHz oscillator and replace it with another that allows exactly 56 kHz by integer division (e.g. 14 MHz and divide by 250).

You can turn the carrier on and off simply by toggling the carrier pin mode between output and input. I have used this to control a heat pump through the 37KHz infrared (remote control) port.

There is no need to use an ISR to create the carrier. Just set up a timer to produce a 50% PWM output at the required carrier frequency. The ISR is then just in charge of modulating the carrier - typically at 0.5 or 1ms intervals - a far more comfortable rate. In my experience a 5% error in carrier frequency is tolerated by most IR receivers. I used a Freetronics EtherMega 2560 (which has plenty of timers) but I'm sure other CPUs will do just as well.

How exactly is the modulation of the carrier implemented then? Changing the mode for the timer output capture pin between input (carrier off) and output (carrier on)?


text:
Compile problem when using keyword 'new' on Raspberry Pi
I have the following line of code in my Arduino sketch:
static double *temps = new double[arraySize];  //Declare array to hold tempratures, place the array on the heap where it will not be deleted and keep the pointer as a static
//double temps[arraySize];

When I compile with the Arduino IDE on Ubuntu it compiles just fine. However, when I compile on the Raspberry Pi, it throws up the following error:
xxx.cpp.o: In function `last Function in file()':
xxx.cpp:[last line in file]: undefined referance to `operator new[] (unsigned int)'
collect2: error: ld returned 1 exit status

Is this a bug? If so, how do I report it? If not, why is it throwing this error or how else can I declare a static array of doubles (needs to be static, I calculate an average of some incoming data over several function calls)?

What version of arduino is the Pi running?

The Arduino uses AVR libc which does not provide a complete C++ environment.
Among other things AVR libc does not support new and delete. See the FAQ for more information.
Some versions of the Arduino libraries may provide new and delete but they are just wrappers around malloc and free. I suggest not using new and delete on arduino because they do not have the same behavior as C++. For example destructors will not be called on the arduino when delete is called.

how else can I declare a static array of doubles (needs to be static,
  I calculate an average of some incoming data over several function
  calls)

When you find a bug in the Arduino software, please do report it to the appropriate place -- http://arduino.cc/en/Main/ContactUs has the contact details.
One way to declare a static array of doubles is like this:
double boxcar_average(double new_sample) {
  const int arraySize = 3;
  static double old_sample[ arraySize ] = {0};
  double sum = new_sample;
  for(int i=0; i<arraySize; i++){
    sum += old_sample[i];
  }
  old_sample[0] = old_sample[1];
  old_sample[1] = old_sample[2];
  old_sample[2] = new_sample;
  return( sum / 4 );
}


text:
Why is this spitting giberish instead of serial numbers?
#include <TrueRandom.h>

void setup() {
  char* ss= (char*)TrueRandom.random(111111111,999999999);
  char* finalss;
  Serial.begin(9600);
  finalss[0] = ss[0];
  finalss[1] = ss[1];
  finalss[2] = ss[2];
  finalss[3] = '-';
  finalss[4] = ss[3];
  finalss[5] = ss[4];
  finalss[6] = '-';
  finalss[7] = ss[5];
  finalss[8] = ss[6];
  finalss[9] = ss[7];
  finalss[10] = ss[8];
  Serial.println (finalss);
}

void loop() {
  ; // Do nothing
}

This is supposed to output a randomly generated number in this format nnn-nn-nnnn.
Updated Code (Doesn't seem to output anything):
#include <TrueRandom.h>

void setup() {
  String ss;
  ss = (String)TrueRandom.random(111111111,999999999);
  String finalss;
  Serial.begin(9600);
  finalss[0] = ss[0];
  finalss[1] = ss[1];
  finalss[2] = ss[2];
  finalss[3] = '-';
  finalss[4] = ss[3];
  finalss[5] = ss[4];
  finalss[6] = '-';
  finalss[7] = ss[5];
  finalss[8] = ss[6];
  finalss[9] = ss[7];
  finalss[10] = ss[8];
  Serial.println (finalss);
}

void loop() {
  ; // Do nothing
}

That's still casting.

I don't understand what you propose I'm new to C and have always used Python where casting would work.

Arduino uses C++, not C. And Python doesn't have casting.

str parentheses anything parentheses in python turns anything into a string it also works for turning str to int or int to float

It passes the argument to the str constructor, but that is not casting.

or it doesn't print you because it is in loop??? :) add line in void loop Serial.println("Already printed"); delay(1000);

I mean to see what it printed you have to reset each time. Just in case you missed that :)

Casting a number to a char* doesn't convert the number to a string. Instead it converts the number to a pointer and starts reading chars from that location.
Either pass the number to a String constructor, or pass it through ltoa().
EDIT:
String ss(...);

or
char ss[11];
ltoa(..., ss, 10);

Also, don't forget to allocate memory for finalss and NUL-terminate it.
char finalss[12];
 ...
finalss[11] = 0;

I tried to the best of my knowledge to follow your advice but seemingly I didn't understand what you meant. I updated the code.

void setup() {
  long longrand = TrueRandom.random(111111111,999999999);
  char ss[9+1], finalss[13+1];

  Serial.begin(9600);
  (void)ltoa(longrand, ss, 10);

  finalss[0] = ss[0];
  finalss[1] = ss[1];
  finalss[2] = ss[2];
  finalss[3] = '-';
  finalss[4] = ss[3];
  finalss[5] = ss[4];
  finalss[6] = '-';
  finalss[7] = ss[5];
  finalss[8] = ss[6];
  finalss[9] = ss[7];
  finalss[10] = ss[8];
  finalss[10] = '\0';

  Serial.println (finalss);
}

void loop() {
  ; // Do nothing
}

TrueRandom.random() returns a long, not a string, so you need to assign the value to a long variable while you translate it.
Your code didn't allocate any memory for the arrays you tried to use, so the third statement does that. I made them larger than the number of characters you used because the range you gave to TrueRandom.random() is a set of 9-digit numbers. I don't know how you need to punctuate your numbers so I allocated finalss[] larger yet. You should confirm that the array sizes will be sufficient for your needs.
The fifth statement, ltoa() converts a long to an ascii string in the ss[] array.
I left your finalss[x] = ss[x];' statements alone except to add the necessary NUL terminator at the end offinalss[]`.

I haven't tested this but it compiled with no errors other than my not having TrueRandom.h. But it should get you a lot closer to (what it looks to me as if) you intended.

I am really assuming you are doing this on a arduino, do you have the serial terminal switched on, you are putting that entire code in setup, means it executes only once and that maybe before you can get your serial terminal on.
So if you are putting it on setup, you need to push the reset button to get a number.
check the code at -
https://code.google.com/p/tinkerit/wiki/TrueRandom and see if that works
A better way to write your code may be -
#include <TrueRandom.h>

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

  Serial.print(TrueRandom.random(111,999));
  Serial.print('-');
  Serial.print(TrueRandom.random(11,99));
  Serial.print('-');
  Serial.println(TrueRandom.random(1111,9999));

}

void loop() {
  ; // Do nothing
}


text:
Why does my servo twitch and turn on its own?
I've been trying to write a very simple program using Arduino to tell a servo to go to a specific angle when a button is pressed, and to another specific angle when it is released. I find that, even though my sketch is but the simplest possible if then else statement without anything added to it, the servo goes to the right angle when the button is pressed, but when it is released, the servo oscillates between the two specified angles at a regular rate (about once every second). What's even stranger is that when i add delay time to the end of the loop in my sketch, the oscillation becomes more like twitching, and the more delay i add the weirder and less predictable the twitching becomes.
added info
#include <Servo.h>
Servo Servo1;
int const switchPin = 4;
int switchState = 0;
void setup()
{
    Servo1.attach(11);
}

void loop()
{
    switchState = digitalRead(switchPin);
    if (switchState == HIGH) {
        Servo1.write(40);
    } else {
        Servo1.write(70);
        delay(39);
    }
}

the power supply is the regular usb connector plugged from the board to my computer. The circuit is virtually similar to the "mood cue" project on the arduino projects book, except there is a button connected to digital pin 4 instead of a potentiometer.

If you want some help, please post your code, even if it is that simple. A description of your wiring, along with information on power supply, may be useful too.

@jfpoilpret here is the code: #include <Servo.h>
Servo Servo1;
int const switchPin = 4;
int switchState = 0;
void setup() {
Servo1.attach(11);
}
void loop() {
switchState = digitalRead(switchPin);
if (switchState == HIGH) {
Servo1.write(40);
}
else {
Servo1.write(70);
delay(39);
}
} the power supply is the regular usb connector plugged from the board to my computer. The circuit is virtually similar to the "mood cue" project on the arduino projects book, except there is a button connected to digital pin 4 instead of a potentiometer.

If it does what you expect when the button is pressed, but behaves unpredictably when released, you almost certainly have a floating input.
See Switches tutorial.
In particular, this is a no-no:

Random fluctuations in voltages will make the switch read HIGH and then LOW, and your servo will chase around trying to change positions.
The simplest fix (without changing anything else) is to add a pull-down resistor between the pin and ground, so now the pin reliably reads LOW when not pressed.

Other methods are discussed on that page, including debouncing.

I see two potential issues in your code.

There is no button debouncing in your code: this means everytime you push the button down or up, the digitalRead() call will return HIGH and LOW several times until the signal is stabilized; that could make the servo twitch as you observed.
For any call to servo.write(), you need to give time to the servo to reach the desired position, typically a few dozen milliseconds.

For the first problem, google for arduino button debouncing and you'll find various solutions for it.
For the second issue, you just need to add delay() after every call to servo.write(); note that in your code you added delay(39); but only for one call to servo.write() not for both calls.

I'm assuming you do not have a potentiometer hanging out of the servo motor its self.
2 things i could see here, without seeing the actual circuit itself.
1- The inputs are left floating therefore the input is thinking it sees a high state when you never push the button due to electrical noise. To fix this add a 10k Resister to ground on pin 4 while the switch is wired to 5v/3.3v on one side and the other side going into pin 4. This will fix noise going into pin 4.
2- Power supply on board is overheating or lack of power since computer usb port has a max power of 500mA. Use an external power supply to the servo and connect power supply ground to the board's ground to have a common ground.


text:
Exceed AREF voltage
Let's say that I use a 5V Arduino board, and I set AREF to 3V, thus 0-3V equals to 0-1023 of the analog inputs.
If I exceed the AREF voltage, powering an analog pin with 4V, could that damage the analog input pin? If not, what would be the reading?
Thank you.

The reading would saturate at 1023 when the voltage on the input pin exceeds AREF.
The datasheet (for the ATmega328P) states as absolute maximum rating for the "Voltage on any Pin except -RESET with respect to Ground" VCC + 0.5 V. So applying 4 V to AREF for a 5 V Arduino board should not (necessarily) damage the ATmega. (But you also won't be able to extend the 10-bit resolution range, if that is what you're after...)
In short, choose the reference voltage above the maximum expected voltage.

... should not (necessarily) damage the ATmega. Could you clarify the "necessarily" statement?

Yes: I don't think it would do damage, but I won't give you a guarantee :) When you apply 4 V you are well inside the absolute maximum rating (which would be 5.5 V) but also quite a bit above the max value given under ADC Characteristics (which is VREF, i.e. 3 V).


text:
How to fade in and fade out led strip connected to arduino based on continous analog input from capacitative sensor?
So I've been trying to get a capacitive sensor made from aluminum foil to work. And I have had success the kind of proximity and readings I need to light up a single LED and produce basic tone. Using this very basic code :
{
  Serial.println(value1);//value that i get from analog sensor
  //this is just to get the values in order for the led and sound
  if (value1<=8) value1=-100;
  analogWrite(ledPin,value1+100);//these weird calculations seem to work for me
  tone(tonepin,value1+100,100);
  delay(10);

All this works perfectly for me, the delay isn't perceivable, the response is for all practical purposes simultaneous to input. Except it's not beautiful, because the LED keeps flickering when values reduce or increase because the jumps are sudden I suppose.
SO I thought I'll try to fade in and fade out to different values from present values.  Used the fading examples. Here:
Serial.println(value1);
  if (value1<=8) value1=-100;

  if (value1+100<=value2+100) {
    for(int fadeValue = value2+100 ; fadeValue <= value1+100; fadeValue +=5) {

    analogWrite(ledPin, fadeValue);

    delay(10);
    }
  }

  else
  {

    for(int fadeValue = value2+100 ; fadeValue >= value1+100; fadeValue -=5)
    {
        analogWrite(ledPin, fadeValue);

    delay(10);
    }
  }
  //analogWrite(ledPin,value1+100);
  tone(tonepin,value1+100,100);
  delay(10);
  value2=value1;

But this takes away the responsiveness, the whole thing is so slow to react, the sound and the light are obviously not in sync as I read my code. But also the light is not really fading, still blinking, but there seems to be some effect but I am not sure.
Any help with what I could do and what I am doing wrong would be nice.

You need to do away with all those delay() calls.  delay() is eeeeeeeeeeeevil.

That helped with making it responsive again, at least closer to how it was. Great. Now the only problem remains to have perceivable fade in fade out. Especially when the analog value drops to zero, the LED just goes back to off state. The fade in fade out doesn't seem to be working. Any ideas?

You need to replace the delay() calls with another method of slowing things down that doesn't block the whole system.  I.e., take a look at the BlinkWithoutDelay example program in the IDE and learn from it.

Smooth the change in output value by taking, e.g 10% of the new value, and 90% of the old value. You can try experimenting with different ratios and longer/shorter delays.
int lastValue = 0;

{
  Serial.println(value1);//value that i get from analog sensor
  //this is just to get the values in order for the led and sound
  if (value1<=8) value1=-100;
  value1 = (1*value + 9*lastValue)/10;// smooth the change in value by taking 10% of the current value, and 90% of the previous value
  analogWrite(ledPin,value1+100);//these weird calculations seem to work for me
  tone(tonepin,value1+100,100);
  lastValue = value1;
  delay(10);

so I changed that part of the code to this
`int value1=0;
Serial.println(value);
if (value<=8) value=-100;
value1 = (1value + 9lastValue)/10;// smooth the change in value by taking 10% of the current value, and 90% of the previous value
analogWrite(ledPin,value1+100);//these weird calculations seem to work for me
tone(tonepin,value+100,100);
lastValue = value1;
delay(10);`
Where value is the actual input from the sensor. and it sort of works as I changed one to the new value ( LED) And used directly for the sound.
The LED doesnt seem to switch off ever, some residue feel

Try value1 = 0.1*value + 0.9*lastValue; instead

Nope, similar results. Do you think using some kind of counter would help slowly fade it out when the sensor is not being played with?

Some more playing around. If I remove the statement that makes the counter -100 and put a zero instead and change the +100 values everywhere I use value1/value then the LED dies out when not interacting, but the upper limit also drops.
`int value1=0;
Serial.println(value);
if (value<=8) value=0;
value1 = (1value + 9lastValue)/10;
analogWrite(ledPin,value1);
tone(tonepin,value,100);
lastValue = value1;
delay(10);`
Tried the same code by substituting +100 by *10 and removing -100, but then the smoothing obviously also starts scrambling to some degree.
Delay is the key?

I think a nice way to redefine this challenge at this time would be to say that we need to figure out a way to keep the smoothed response while widening the range of output which has the minimum at 0 and maximum at a nice high range. While all this happens the minimum value should be achieved if low input values occur over a time ( seeing them as feedback and not really input)

Another try with a counter produces the best result as of now, but something instinctively feels off, maybe I will share a small video later.
int value1=0;      Serial.println(value);   if (value<=8) value=-100;   if (value<=0) counter=counter+1;   value1 = (1*value + 9*lastValue)/10;   if (counter>=50) { value1=-99; counter=0;}   analogWrite(ledPin,value1+100);   tone(tonepin,value+100,100);    lastValue = value1;   delay(10);

You need to re-think the entire way of dealing with the fading.
Instead of saying "The value has changed, fade the LED to that brightness", you need to say "The value has changed. I want the LED to be this brightness." followed by "Is the LED the brightness I want? No? Then move it a bit towards the brightness I want".
Something like, in pseudo-code:
TargetBrightness = SensorValue
if LEDBrightness < TargetBrightness
    increment LEDBrightness
    set LED to LEDBrightness
if LEDBrightness > TargetBrightness
    decrement LEDBrightness
    set LED to LEDBrightness

If that all happens too fast then you need to only run the brightness tests at certain periods.  Something like:
TargetBrightness = SensorValue
Has 10ms passed since last check? Yes?
    Remember the time this check happened.
    if LEDBrightness < TargetBrightness
        increment LEDBrightness
        set LED to LEDBrightness
    if LEDBrightness > TargetBrightness
        decrement LEDBrightness
        set LED to LEDBrightness


text:
Sending Serial Hex Command from Pin 1 (Tx)
Using Arduino Uno with 3.5mm Jack connected to ground and pin 1 for TX
Need to send two commands
I want to send
0XAA13FE010113 for Mute on, and
0XAA13FE010012 for Mute off.
Simple Serial Command to turn Monitor Mute on and off every 5 seconds....
tried everything byte character, array, write with hex, print :(
Thx for a helping a rookie
I want to impress my team

Ideal quick answer below. thx to @martynas
uint8_t muteON[] = { 0xAA, 0x13, 0xFE, 0x01, 0x01, 0x13 };
uint8_t muteOFF[] = { 0xAA, 0x13, 0xFE, 0x01, 0x00, 0x12 };
....
void loop() {
 Serial.write( muteON, sizeof(muteON) );
 delay(5000);               // wait for 5 second
 Serial.write( muteOFF, sizeof(muteOFF) );
 delay(5000);               // wait for 5 second
}

What have you tried so far? Don't expect people here to do EVERYTHING for you! How would you "impress your team" with something other people would have completely done for you?

Please add some code to your question so we can help debug it.

there are 6 bytes just make
byte muteON[] = {0xAA,0x13,0xFE,0x01,0x01,0x13};
byte muteOFF[] = {0XAA,0x13,0xFE,0x01,0x00,0x12};
...
/* To send mute ON comand */
for(byte i =0;i<sizeof(muteON);i++)(Serial.write(muteON[i]));
/* To send mute OFF comand */
for(byte i =0;i<sizeof(muteOFF);i++)(Serial.write(muteOFF[i]));

I do not know you, your programming level etc. Wrote as clear as i could

So is it working?

Also you can use SoftwareSerial. Then you can choose Tx pin

I am using Arduino uno.
when setting   Serial.begin(9600);
does that send serial output via usb and pin 1?

No you just set the output baud rate.


text:
Serial.prints ignored
I've been working on a project where I want to transmit data from one arduino to another using an Xbee network and then parse it to update some PWM outputs accordingly (Building a system which controls some LED lamps).
The thing is I wanted to debug the receiver using a number of Serial.print() but it appears a lot of them are "ignored" by the Serial Monitor. For instance, if you take a look at the image below you will notice there is a "Zone:" that should be displayed somewhere on screen. It isn't. I also got a Serial.print("Coucou") in the loop() that is never displayed.
Has anyone ever encountered a bug of this kind ?

As asked, the code that is producing the output
#include <EEPROM.h>
#include <Dispositif.h> // Custom class i wrote.

// how much serial data we expect before a newline
const uint8_t MAX_INPUT = 196;

//zone = 1, id = 1, idNode = 2
Dispositif dispositif;

void setup ()
{
  Serial.begin(9600);
  //delay(1000);
  Serial.println("Cool");
} // end of setup

// here to process incoming serial data after a terminator received
void process_data (const char * data, unsigned int input_pos)
{
  uint8_t value = 0;
  uint8_t i = 1;
  uint8_t currentZone;
  char c;

  if(data[0] != '<')
  {
    i = peekNextP(data);
  }
  while (data[i] != '>' && i < input_pos - 3)
  {
    // zone
    value = 0;
    i = peekNextDigit(data, i);
    do{
      c = data[i];
      i++;
      if(c >= '0' && c <= '9')        // is c a digit?
        value = value * 10 + c - '0';
    } while(c >= '0' && c <= '9');
    currentZone = value;
    Serial.print(currentZone);
    Serial.print(F("("));

    // 1st order
    value = 0;
    i = peekNextDigit(data, i);
    do{
      c = data[i];
      i++;
      if(c >= '0' && c <= '9')        // is c a digit?
        value = value * 10 + c - '0';
    } while(c >= '0' && c <= '9');
    Serial.print(value);
    Serial.print(F(","));

    if (currentZone == dispositif.zone) {
      dispositif.setBrightness(0, value);
    }
    // 2nd order
    value = 0;
    i = peekNextDigit(data, i);
    do{
      c = data[i];
      ++i;
      if(c >= '0' && c <= '9')        // is c a digit?
        value = value * 10 + c - '0';
    } while(c >= '0' && c <= '9');
    Serial.print(value);
    Serial.print(F(","));

    Serial.print(F("Zone:"));
    Serial.print(dispositif.zone);
    if (currentZone == dispositif.zone)
      dispositif.setBrightness(1, value);

    // 3nd order
    value = 0;
    i = peekNextDigit(data, i);
    do{
      c = data[i];
      ++i;
      if(c >= '0' && c <= '9')        // is c a digit?
        value = value * 10 + c - '0';
    } while(c >= '0' && c <= '9');
    Serial.print(value);
    Serial.println(F(")"));

    if (currentZone == dispositif.zone)
      dispositif.setBrightness(2, value);
  }

}  // end of process_data

uint8_t peekNextDigit(const char* data, uint8_t i)
{
  int c;
  while (1) {
    c = data[i];
    if (c >= '0' && c <= '9') return i;
    ++i;
  }
}

uint8_t peekNextP(const char* data)
{
  uint8_t c;
  uint8_t i = 0;
  while (1) {
    c = data[i];
    ++i;
    if (c == ')') return i;
  }
}

void processIncomingByte (const byte inByte)
{
  static char input_line [MAX_INPUT];
  static unsigned int input_pos = 0;

  switch (inByte)
  {
    case '\n':   // end of text
      input_line [input_pos] = 0;  // terminating null byte

      // terminator reached! process input_line here ...
      process_data (input_line, input_pos);

      // reset buffer for next time
      input_pos = 0;
      break;

    case '\r':   // discard carriage return
      break;

    default:
      // keep adding if not full ... allow for terminating null byte
      if (input_pos < (MAX_INPUT - 1))
        input_line [input_pos++] = inByte;
      break;

  }  // end of switch

} // end of processIncomingByte

void loop()
{

  Serial.println("Coucou");
  // if serial data available, process it
  if (Serial.available () > 0)
    processIncomingByte (Serial.read ());

}  // end of loop

The Serial output is :
<o>1(255,255,255)<o>
<o>1(0,0,0)<o>
<o>1(255,255,255)<o>

What I am aiming for :
Cool
Coucou
<o>1(255,255,Zone:1255)<o>
Coucou
<o>1(0,0,Zone:10)<o>

My library :
#include <Dispositif.h>
#include <EEPROM.h>

#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

#define pin1 5
#define pin2 6
#define pin3 9

Dispositif::Dispositif()
{
  pinMode(pin1, OUTPUT); // absolutely necessary because we use a custom PWM
  pinMode(pin2, OUTPUT);
  pinMode(pin3, OUTPUT);

  setBrightness(0, 50);
  setBrightness(1, 50);
  setBrightness(2, 50);

  last_value[0] = 50;
  last_value[1] = 50;
  last_value[2] = 50;

  zone = EEPROM.read(0);
  id = EEPROM.read(1);
  idNode = EEPROM.read(2);
}

Dispositif::Dispositif(uint8_t zone, uint8_t id, uint8_t idNode)
{
  zone = zone;
  id = id;
  idNode = idNode;

  pinMode(pin1, OUTPUT);
  pinMode(pin2, OUTPUT);
  pinMode(pin3, OUTPUT);

  setBrightness(0, 50);
  setBrightness(1, 50);
  setBrightness(2, 50);

  last_value[0] = 50;
  last_value[1] = 50;
  last_value[2] = 50;

  EEPROM.write(0, zone);
  EEPROM.write(1, id);
  EEPROM.write(2, idNode);
}

void Dispositif::setBrightness(uint8_t number, uint8_t value)
{
    if (!Serial)
      Serial.begin(9600);
    unsigned long currentMillis = millis();
    unsigned long lastMillis = 0;

    while(value - last_value[number] > 25)
    {
      currentMillis = millis();
      if (currentMillis - lastMillis > 1000)
      {
        Serial.println("At least i'm here");
        Serial.println(last_value[number]);
        last_value[number] += 25;
        setPWM(number, last_value[number]);
        lastMillis = currentMillis;
      }
    }
    setPWM(number, value);
    last_value[number] = value;
}

void Dispositif::setPWM(uint8_t number, uint8_t val)
{
    if (1 == number) // pin 6
    {
      sbi(TCCR0A, COM0A1);
      OCR0A = val; // set pwm duty
    }
    else if (2 == number) // pin 9
    {
      sbi(TCCR1A, COM1A1);
      OCR1A = val; // set pwm duty
    }
    else // pin 5
    {
      sbi(TCCR0A, COM0B1);
      OCR0B = val; // set pwm duty
    }
}

void Dispositif::changeZone(uint8_t newZone)
{
  zone = newZone;
}

The code is not really pretty, because at one point I was using the SD library and had to reduce program space.

Cab you show us some more of your script?

Instead of posting a picture of your IDE, can you please post the actual code and the actual serial output? Thanks!

I added all the involved code. I apologise for its messiness.


text:
Arduino and C++ Serial communication
I am using this header: http://playground.arduino.cc/Interfacing/CPPWindows
My main:
#include <iostream>
#include <stdio.h>
#include <tchar.h>
#include "SerialClass.h"
#include <string>

int main(int argc, _TCHAR* argv[])
{
    Serial* SP = new Serial("\\\\.\\COM4");

    if (SP->IsConnected())
        printf("We're connected\n");

    std::string tryStr;
    int value;
    DWORD bytesSend;

    /* Loop */
    while(SP->IsConnected())
    {
         /* Take a value from user */
         printf("Value: "); scanf("%d",&value);

         /* Send Arduino */
         BOOL retVal = WriteFile(SP->hSerial, &value, sizeof(value), &bytesSend, NULL);

        /* I have no idea what is this for? (SP->status.cbInQue) */
        ClearCommError(SP->hSerial, &SP->errors, &SP->status);

        /* Read string from arduino */
        DWORD bytesRead;
        tryStr.assign("");
        bool check = true;
        char tempCharacter;
        while (check==true){

            ReadFile(SP->hSerial, &tempCharacter, sizeof(char), &bytesRead, NULL);
            tryStr += tempCharacter;

            if(tempCharacter == '$'){
                check = false;
            }
        }

        /* Print the string */
        std::cout << tryStr  << std::endl << std::endl ;
    }
    return 0;
}

My Arduino Code:
int LedPin= 10;
int value;
String  incomingData = "hello$";

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

void loop (){

  while(!(Serial.available() > 0)){
    /*Wait until take data */
  }

  value=Serial.read();

  if (value == 20)
  {
      digitalWrite (LedPin, HIGH);
      incomingData.setCharAt(0,'o');
      incomingData.setCharAt(1,'p');
      incomingData.setCharAt(2,'e');
      incomingData.setCharAt(3,'n');
      incomingData.setCharAt(4,'n');

      Serial.print(incomingData);
  }
  else if (value == 15)
  {
      digitalWrite (LedPin, LOW);
      incomingData.setCharAt(0,'c');
      incomingData.setCharAt(1,'l');
      incomingData.setCharAt(2,'o');
      incomingData.setCharAt(3,'s');
      incomingData.setCharAt(4,'e');

      Serial.print(incomingData);
  }

}

This code works perfectly. Output:

We're connected  Value: 20  openn$
Value: 15  close$
Value: 20  openn$
Value: 20  openn$
Value: 15  close$
Value: 15  close$
Value: 20  openn$

But now I want to add another condition in my Arduino code:
int LedPin= 10;
int value;
String  incomingData = "hello$";

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

void loop (){

  while(!(Serial.available() > 0)){
    /*Wait until take data */
  }

  value=Serial.read();

  if (value == 20)
  {
      digitalWrite (LedPin, HIGH);
      incomingData.setCharAt(0,'o');
      incomingData.setCharAt(1,'p');
      incomingData.setCharAt(2,'e');
      incomingData.setCharAt(3,'n');
      incomingData.setCharAt(4,'n');

      Serial.print(incomingData);
  }
  else if (value == 15)
  {
      digitalWrite (LedPin, LOW);
      incomingData.setCharAt(0,'c');
      incomingData.setCharAt(1,'l');
      incomingData.setCharAt(2,'o');
      incomingData.setCharAt(3,'s');
      incomingData.setCharAt(4,'e');

      Serial.print(incomingData);
  }
  else{                                      // new line added
                                             // new line added
      incomingData.setCharAt(0,'g');         // new line added
      incomingData.setCharAt(1,'g');         // new line added
      incomingData.setCharAt(2,'g');         // new line added
      incomingData.setCharAt(3,'g');         // new line added
      incomingData.setCharAt(4,'g');         // new line added
                                             // new line added
      Serial.print(incomingData);            // new line added
  }                                          // new line added

}

But it didn't work. ScreenShot:

What went wrong? The led blinked correctly but the output string is wrong.

BOOL retVal = WriteFile(SP->hSerial, &value, sizeof(value), &bytesSend, NULL);

You're writing sizeof(value) bytes to the Arduino. Since value is an int, which is typically 4 bytes in size for PC compilers/processors, when you send 20, what actually gets to the Arduino is 0x00000014. Your processor is apparently little-endian so the order of bytes sent is 0x14, 0x00, 0x00, 0x00.
You're reading a single byte in every loop() iteration. Your first sketch worked because you didn't provide any else clause for unrecognized bytes. The Arduino merely ignored those leading zeros. However, your second sketch handled unknown bytes (such as 0x00) by printing gggg. So what you get for every value you send to the Arduino is exactly what you'd expect and what you see in your shell -- the result you want (openn == 0x14), followed by 3 gibberish results (because of the leading zero bytes).
You can fix it by either declaring value as a uint8_t in your CPP code (after including stdint.h) or only reading chunks of 4 bytes on the Arduino and then parsing what you get. The former solution seems more reasonable/reliable.


text:
Light sensor always getting max value
I have build a simple voltage divider with a light resistor and a 5.6k resistor. I am reading the input on A0 on my arduino board but it is almost always at 1023, independent of light. If I cover it it might go down to 1020 but not more than that.
Do I have to use a greater resistor than 5.6k to achieve more difference in the sensor?
The light sensor is similar to this: http://www.ebay.com/itm/20x-5549CDS-Photo-Light-Dependent-Sensitive-Resistor-Photoresistor-LDR-Photocell-/281425650814?pt=LH_DefaultDomain_0&hash=item418646a47e
I think that the resistance is pending between 1k-10k.
The circuit is like this image:

Where Vin is 5V from the arduino. R1 is the light sensor, R2 is 5.6k and Vout is connected to A0.

Can you show a diagram of your exact circuit?

A pointer to the datasheet for the photo-resistor would help, too. At the very least, we'd need to know its resistances when dark and bright.

5.6k sounds good. Is A0 connected between LDR and Resistor? Can you check that LDR works using an Ohm meter?

A circuit is essential. A description in words in the absence of a circuit is a logical minimum if you actually want an answer. LDR should go from eg A0 to Vcc and resistor from A0 to ground or vice versa - is that what you did? Where did you get the information? Datasheet for LDR? (There are zillions of types). ...

I updated the question now!

Have you tested the voltages and resistances with a Multimeter?

What have you selected as the analog reference? And if 'external', what is connected to the Vref pin?
For the LDR resistances of 10K and 1K, you  Vout should be ~ 1.8v at 10K, and ~ 4.2v at 1K, and giving A/D readings of somewhere around 370 counts and 860 counts, respectively, with a 5v analog reference.
If your analog reference selected to the 1.1v internal reference, either LDR resistance should give you the max reading, but an LDR = 20K could give just over a volt and pretty close to the reading you're getting.

Judging by a datasheet (that I found on the web) that has a resistance of:

100 k to 200 k in the light
1 M in the dark

Given that Vout =  Vin * R2 / (R1 + R2) we can work out:
Light:
Vout = 5 * 200000 / (200000 + 5600) = 4.86 V

Dark:
Vout = 5 * 1000000 / (1000000 + 5600) = 4.97 V

Do I have to use a greater resistor than 5.6k to achieve more difference in the sensor?

Yes, I would measure the resistance in the light, and choose a similar resistor for the other side of the voltage divider. So if you measure 100 k on the sensor, another 100 k will at least divide the voltage in two nicely.


text:
Uploading a simple sketch takes forever
I am trying to upload this simple sketch into my arduino with a shield I made. It takes forever (note I have the right COM port on)
  int sensorValue = 0;

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

  void loop(){
     sensorValue = analogRead(A4);
     delay(10000000);
     Serial.println(sensorValue);
     delay(10000000);
  }

Enable verbose output in the settings. That way you can see what's going on, and what part of the compiling and uploading process takes so long. Also make sure you have an up to date version of the Arduino IDE, as some previous version didn't cache the previously compiled libraries properly.

if you want such a long delay in loop(), you should use the millis() function, it should free the MCU for other stuff.

Please copy and paste the messages you see when uploading. Why are you waiting 2.7 hours before displaying the value you read? How does that help?

My solution was to select the right version of the board (Tools->Board) mine was Arduino Leonardo. It was selected something else..

Are you sure the problem is in the upload time? delay() takes the number of milliseconds you want to wait. In your code, it should take about 3 hours before the Arduino sends some data through the serial port.

I think this is a reasonable answer - sometimes people misinterpret one delay for another

I had the same problem. I noticed that the RX & TX LEDs we're not flashing as they normally do when I upload a file. I'm using an older knock off nano.
My solution:
Under Tools> processor.... I switched from the defaulted "ATmega328P" to the "ATmega328P(Old Bootloader)" option. The next upload attempt was quick and successful. Normal flashing RX &TX LEDs during the upload as well. Hope this helps someone.

Your solution saved my day!  I was about to recycle my board.

Check the end of this thread for the reply by 'Toshibass', Unbelievable slow compilation of simple sketches

I was having same same problem compile took > 3 minutes for small sketch using serial or OTA however I found solution The program that was slowing down compile was IBM's Trusteer .. Rapport which is a fraud prevention program distributed by my bank once I de-installed it, same compile took 10 seconds, now all I need to do is find an alternative or hope IBM produce a fix after I filled in a issue report to them.

It worked for me, the culprit was some software called 'Trusteer'.

I have added a direct link to the post that you refer to, as well as quoting the reply. As it stood, your answer was a "link-only answer". Please provide greater detail in your future answers. :-)

If you are taking too much time for uploading means there is communication between another device is happening, please remove all TX and RX pins.

If the problem does indeed lie in the upload (see DoubtBearer's answer), then you should turn on verbose output, to see exactly what part of the upload is giving issues.
In your IDE, click File -> preferences; look for the section "Show verbose output during:" and tick both Compilation and Upload.
Re-run your upload, and see what is taking up all the time. If you can't figure it out from that, please post the log (it will appear in the black area at the bottom of the IDE, you should be able to cut & paste).

Try downloading CH340 drivers. You must not have drivers for uploading the code to arduino board and to identify the right COM port.
Download and install the drivers, find the COM port number from device manager and update Tools->Port in your Arduino IDE.

I'm curious to know what the thinking behind this is.

I am not that active so sorry to reply so late. I believe that OS had drivers for some of the Arduino devices but it didn't had the appropriate drivers to communicate with my Arduino Nano. I struggled through the comments with no benefit and as soon as I figured out, I posted the solution here.


text:
Maintaining Arduino on Ubuntu 14.04
I used to use Arduino on Windows but I changed to Linux last week and I was wondering how to have a maintained version of the Arduino terminal:
Indeed, I'm not sure my version is quite recent:

The icon seems to have lived ages without a little lifting...
Maybe I'm wrong but it seems so when I open the "Tools" option for instance...
Furthermore I tried to copy and paste this code:
//ONG LIT YIT 2013-07-20
//This following code plays happy birthday melody on Arduino
//Put Piezo Buzzer on GDN and 9 (Positive and negative are reversible)
//this project requires a Piezo Buzzer and

// an Arduino board and

//jumper wires to connect Buzzer's (+) to ~9 and (-) to GND (any GND)

//HAVE FUN

//this project requires a Piezo Buzzer and

// an Arduino board and

//jumper wires to connect Buzzer's (+) to ~9 and (-) to GND (any GND)

//HAVE FUN

int speakerPin = 9;

int length = 28; // the number of notes

char notes[] = "GGAGcB GGAGdc GGxecBA yyecdc";

int beats[] = { 2, 2, 8, 8, 8, 16, 1, 2, 2, 8, 8,8, 16, 1, 2,2,8,8,8,8,16, 1,2,2,8,8,8,16 };

int tempo = 150;

void playTone(int tone, int duration) {

for (long i = 0; i < duration * 1000L; i += tone * 2) {

   digitalWrite(speakerPin, HIGH);

   delayMicroseconds(tone);

   digitalWrite(speakerPin, LOW);

   delayMicroseconds(tone);

}

}

void playNote(char note, int duration) {

char names[] = {'C', 'D', 'E', 'F', 'G', 'A', 'B',

                 'c', 'd', 'e', 'f', 'g', 'a', 'b',

                 'x', 'y' };

int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014,

                 956,  834,  765,  593,  468,  346,  224,

                 655 , 715 };

int SPEE = 5;

// play the tone corresponding to the note name

for (int i = 0; i < 17; i++) {

   if (names[i] == note) {
    int newduration = duration/SPEE;
     playTone(tones[i], newduration);

   }

}

}

void setup() {

pinMode(speakerPin, OUTPUT);

}

void loop() {

for (int i = 0; i < length; i++) {

   if (notes[i] == ' ') {

     delay(beats[i] * tempo); // rest

   } else {

     playNote(notes[i], beats[i] * tempo);

   }

   // pause between notes

   delay(tempo);

}

}

And not all of it appeared in the Arduino terminal.

That is a very old version. Please download from the Arduino Software page https://www.arduino.cc/en/Main/Software. I normally install to ~/opt/arduino-x.y.z. Run the arduino binary from that directory.

Okay! Thanks! How do I install it to  ~/opt/arduino-x.y.z. ?

Go to the download page. Click on the Linux version you require (32 or 64 bit). Wait for the download to complete and the Archive Manager is started. Push extract and select where you want to "install" it.

Basically you un-archive it as Mikael Patel said, and then just double-click the Arduino icon to execute it. You may need to fiddle with permissions or settings or it might just open it in a text editor.

Just mark the arduino file as executable and launch it through the terminal. (cd into the directory and launch it) Then lock it to the sidebar. Next time you can just easily launch latest Arduino IDE from the sidebar.

FYI, the reason Ubuntu packages such an old version of the IDE is that the Arduino licensing needs to be updated/clarified. As is, Ubuntu cannot legally distribute the latest Arduino version: https://github.com/arduino/Arduino/pull/2703 The rest of the work to include it in the Ubuntu repository is done, so there's nothing more they can do about it.

If you want to get maintained (automatically updated) version of Arduino IDE then you install if from a package repository with its dependencies e.g. using apt-get:
sudo apt-get update
sudo apt-get install arduino arduino-core

However, this way you get a very old version (currently 1.0.5). Obviously, it is not updated too often if at all.
If you already installed from the package repository via apt-get you can uninstall the package and its dependencies like this:
sudo apt-get remove arduino arduino-core
sudo apt-get autoremove

Better way is to download and install Arduino IDE yourself. This way Arduino software won't automatically be updated, so you should check Arduino website every now and then and download a new version if one is available.
Open a terminal window (e.g. by pressing CTRL-ALT-T), and run uname -m to check if you are running 32 bit or 64 bit platform:
uname -m

See output:
x86_64 ==> 64-bit kernel
i686   ==> 32-bit kernel

Go to Arduino Download page on Download the Arduino Software and download the 32 bit or 64 bit version, depending on the Ubuntu version installed on your computer.
In a terminal window extract the package and move it to your preferred location, e.g. /opt. You need sudo rights to move it to /opt. Finally, run the install script if you want to start the IDE graphically (adds desktop icon, MIME type, default application for .ino). See the example commands below for installing the latest 32 bit version as of the time of writing to /opt.
cd ~/Downloads
tar xf arduino-1.6.7-linux32.tar.xz
sudo mv arduino-1.6.7 /opt
/opt/arduino-1.6.7/install.sh

You can also start the IDE from the terminal:
/opt/arduino-1.6.7/arduino

Why into /opt? Why not just keep it under /home and launch it there?

@Avamander It makes sense if you aren't the only user of the computer. If you are the one and only user of the Linux box then keeping it under your home dir if just fine.