text:
Can't communicate with arduino using python (Windows)
I am new to programming and am trying to communicate with my arduino using python through serial communication. I am using the following code:
Arduino code:
int ledPin = 11;

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

void loop() {
  digitalWrite(ledPin,LOW);
    if (Serial.read() == 'M'){
      digitalWrite(ledPin,HIGH);}
}

Python code:
import imaplib
import serial
ser = serial.Serial("COM3",9600)
ser.write(b'T')
ser.close()

I get the following error on running the python script:

serial.serialutil.SerialException: could not open port 'COM3': PermissionError(13, 'Access is denied.', None, 5)

After you figure out why you get that error (based on the answers below) there is another potential problem in your python code - when opening the serial port the Arduino will reset, so anything sent immediately after connection will not get to your sketch. Using a delay after connection will help

There can be several reasons as highlighted in these questions:

https://stackoverflow.com/questions/6032568/using-serial-on-python-win7
https://stackoverflow.com/questions/6105182/error-while-opening-port-in-python

They include:

port is already in use by another application
permissions are set to deny access to normal users
problems in the code (top answer in first link)

Try to run with administrator priviledges ("run as administrator"). Others claim that a simple retry might help.

Are you by any chance using Jupyter Notebok? I was having a similar error today and managed to solve it by opening Jupyter Notebook through Anaconda Navigator instead of opening it through Anaconda Prompt.

Either run your python program in "administrator mode" or close any other programs using the port intended for

you must use this code
>>> import serial
>>> ser.close()             # close port

Please add detail on how this solves the problem the OP is asking.


text:
How convert eight hex characters to uint32_t using strtol() function?
I want to control 4 pins using hexa code like this ff00ff00 (255, 0, 255, 0).
strtol() function works fine with three pins like 00ff00, but when i add two extra caracters to &payload[1] variable like this ff00ff00.
((rgba >> 24) & 0xFF) is equal to 127 when it should be 255.
How to make this work?
each analog pin should be set from 0 to 255
    analogWrite(LED_WHITE,  ((rgba >> 24) & 0xFF));
    analogWrite(LED_RED,    ((rgba >> 16) & 0xFF));
    analogWrite(LED_GREEN,  ((rgba >> 8) & 0xFF));
    analogWrite(LED_BLUE,   ((rgba >> 0) & 0xFF));

    uint32_t rgba = (uint32_t) strtol((const char *) &payload[1], NULL, 16);

The function strtol() is not able to convert numbers that are larger than LONG_MAX and smaller than LONG_MIN as it uses signed numbers.
You should use the function strtoul() instead (for unsigned long integers).
Cheers!

source: Stack Exchange

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

sort: votes


text:
What is exactly MQ-2 sensor?
What does the MQ-2 sensor detect?
I know it detects concentrations of flammable gas. But does it detect smoke from fires too?
What about smoke from cigarettes, and other things?

Simple answer is no.
There are about 10 similar sensors, each detect specific kind of chemicals

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


text:
Unstable system when controlling power to serial peripheral devices and sleeping
In the process of trying to make a small system that will last a while on 4 AA batteries, I've reduced my Arduino project to a barebones system that when asleep draws a tiny amount of current from the batteries.
However, to achieve this, I found it would be necessary to cut power to the two attached peripheral devices (connected to an ATMega328P-PU). One of them is an I2C device, and the other is a serial device, and both are attached to the hardware serial/I2C pins as appropriate.
In terms of powering the peripherals, the bases of two transistors are connected to two of the digital pins, and power to them is controlled from code via these transistors. Both devices are 5V, and when the system is running the total current draw is around 200mA.
Basically this setup works, however I'm getting "random" system hanging and essentially an unreliable project. Sometimes when I power it up it will work as normal, but then hang and not sleep. Other times, it will sleep, but then freeze after waking or just get stuck during waking (which I can tell because the serial device powers up first and does nothing, but the I2C device remains off).
My best guess is the root of the cause is either something to do with the serial communication being interrupted by sleeping the MPU (I'm using the maximum power saving sleep, which is woken by an external interrupt on pin 2), or possibly some sort of power problem (sudden current draw from battery?) that occurs when the peripherals are powered on in code (though I don't know how I should test this).
So far, I've tried calling Serial.end() before sleeping the MPU, and Serial.being(9600) on waking, and have scattered delay(1000)s throughout to ensure everything has enough time to get running, but the problem still remains.
Does anyone have any pointers on things I could change/test, or an alternative approach I could take to make the same power savings?
EDIT: Some more details
The transitors used are TIP 120's. The connections are essentially an exact copy of the image here: https://ctheds.files.wordpress.com/2007/10/tip120.jpg, except the resistors used are 560 Ohms (just what I had to hand, no other reason, didn't think it would change anything).
The I2C peripheral is a 20x4 LCD (which I believe is HD44780 compliant). The serial device is an GT511C3 fingerprint sensor. I don't believe either of them have any automatic power saving features, though I haven't looked for such things in the documentation explicitly.
The exact code I use to call sleep is
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
sleep_enable();
sleep_mode();

which I'm lead to believe is the lowest power mode, and aside from this problem works well for my system.

Please show us how you connected the peripherals with the transistors? Which transistors did you use? What peripherals do you use, as some have power saving features themselves? Also, please post the code where it hangs. Power spikes/dips seems like a possible explanation. You could use the watchdog timer to reset the arduino when it hangs, but that isn't really a fix for original problem.

What sleep mode do you use? In some recent experiments, I found out that ATmega USART (serial comm) was not compatible with ANY sleep mode except the IDLE mode.

Also you might consider replacing your transistors with MOSFETs, which shall reduce consumption further.

Does it work as intended if you remove the transistors, but use the sleep mode? I mean, maybe the sleepmode is the problem itself

Thank you all for your comments, I have updated the question with more details.
@Gerben I had considered the watchdog timer, but as you say it wouldn't help me as I would lose the state my program was in before it was reset.

@jfpoilpret I'm interested to hear more about your experiments. Do you mean serial will simply not work after sleep? Just to be clear, I am not using a serial interrupt to wake the MPU.

@AllanNørgaard The previous iteration of my project did exactly this. The MPU was put to sleep, but the peripherals were always on. The battery just didn't last long enough to be viable.

Make sure all output pins going to the peripherals are set to high, or you might damage them. Try adding a large capacitor to the power rail, and see if that helps. You probably want to disable the brownout detection during sleep (sleep_bod_disable()). (I haven't had problems with powerdown and serial communications.)

@Gerben Thanks for the suggestions. I already have a 10uF capacitor on the rails. I don't think I need to go bigger? It seems the chip I'm using doesn't have BOD sleep, since when I try to compile with it I'm told it's not defined. I've done a few more experiments and I'm "quite" sure that the serial device is causing the problem. I'm not sure if it helps to mention, but the library can be found here: http://goo.gl/jOemCc. By default the library uses SoftwareSerial, which I thought was the problem, so I modified it to use HW serial. Have you needed to call Serial.end() to sleep in the past?

I didn't call Serial.end(), but I only used it to send data to my PC, never to receive. The sleep_bod_disable() Macro isn't available in the Arduino IDE for some reason, but you can probably find the actual code somewhere (or use this one). I'd try a bigger cap, if you have one, as it's very little effort, and might just fix it. Where did you put the transistors? On the 5v or on the GND going to the fingerprint reader.

@Gerben Thanks, I'll give the bigger capacitor a try. I'm using the transistor to switch the sensors ground wire, the 5V is connected to the 5V rail. I assume you were using hardware serial in your project as opposed to a software serial port?

If you switch the GND, you have to make sure all the pins going into the module are also 5V or (high impedance) inputs. Or current could flow from the 5V rail, through the module, to the GND on the signal wire, possibly damaging the module, and even the arduino. I'm not saying that's the case here, as it depends on how the module/IC is build. Most datasheet tell that the input voltage should be more that a few tenths of a volt below ground. If ground is disconnected/floating, a low input signal will be like -5V. PS yes, I used hardware serial.

Be aware that running the AVR straight from the battery works, but might require to speed down the clock (16MHz requires a minimum of 3.7v according to the spec) I had a couple of similar problems in my project and 'solved' them with a rather brutal approach (https://holadimake.wordpress.com/2015/01/24/building-a-cellular-tracker-part3a-circumventing-unreliable-watchdog-with-external-555-timer/).

I see, do you mean use a 555 timer to act as a slower, external clock? My power source is 4.8V, so I would have thought that would be good enough to mean that an external clock is not necessary?

I'd suspect the clock rate too. Plus make sure you don't run out of memory. Most common causes for freezing code is low memory.

Using an NPN transistor to control power to a peripheral may be problematic.
An NPN transitor would presumably be used as a low-side switch interrupting the peripheral's ground line, however, even when turned on this will have a non-trivial voltage drop.
Most logic level definitions are asymmetric, ie, the maximimum legal voltage for a logic "0" is relatively low. If you insert the voltage drop of a bipolar transistor into a peripheral's ground line, then it may be borderline unable to drive a fully legal '0' to the ATmega, which is reference to the lower true ground and would see the peripheral's ground difference added to its output voltage.
A better approach would be to use either a high-side switch (as there is typically more room between the minimum legal '1' and the supply) or else to use an FET switch which would have a much lower voltage drop.
Also keep in mind that most IC's are not specified to tolerate lasting I/O voltages much outside of the range of their power suppliers, and in fact their protection diodes may mean that application of such voltages effectively powers them through the I/O pin.  So before turning off power to a peripheral, you probably want the ATmega software to assert all shared I/O lines towards the side of the peripheral supply which is not being disconnected, ie, for a low side switch drive everything high and for a high side switch drive everything low.
Finally, the process of power cycling could potentially confuse peripheral interface engines and it is possible that some error flags set in this process might never be cleared.  So you may want to clear the flags of and generally re-initialize your USART, I2C, etc on resume.

Sadly, this is a long dead project, and the bits to put it back together are a bit scattered... Nevertheless, I am most interested by your take on things. These are problems I hadn't considered (or even realised existed, coming from a largely software background). Thanks very much! I hope that if I get around to trying something like this again in the future it will succeed!

I hear great things about the cosa core for Arduino. It's a fantastic alternative Arduino core and exposes the power management capabilities of the micro-controller that are not exposed by the standard Arduino core.
You might find it is too different for your experience but then again it is excellent and worth a look.
https://github.com/mikaelpatel/Cosa


text:
Changing timing intervals with millis()
My goal is to run a vibrating motor for specific time intervals. I am using the millis() function to successfully turn the motor on and off, but only if the intervalOn = intervalOff. The problem comes when I try to change the intervals to turn the motor on for e.g. 120 ms, then turn off for 200 ms etc. My code seems to cause AVR restart and my motor sometimes stays running. First I thought this is caused by insufficient decouple capacitor (I have 100 uF one) but when running the millis() code with one no-changing interval, it all works flawlessly...
Is there any other way to change the intervals?
The Vibrating() function gets called from the loop() whenever vibrEnabled = true
unsigned long interval = 0;
unsigned long previousMillis = 0;
int last = 120;
int pause = 200;

void Vibrating()
{
unsigned long currentMillis = millis();
static byte cyclesPassed = 0;

if((unsigned long)(currentMillis - previousMillis) >= interval)
{
    PORTC ^= (1<<PC1);//toggle motor

    if(interval != last) //this part causes the problem
        interval = last; //
    else                 //
        interval = pause;//

    cyclesPassed++;
    if(cyclesPassed == 8)//motor is on 4x
    {
    cyclesPassed = 0;
    vibrEnabled = false;
    }

    previousMillis = millis();
 }
}

I am pretty sure your problem is not related to changing the interval.  I advice to add all your code. Your problem could be hardware related. To see wether it is hardware related or not: remove the hardware and add serial print statements to your code so you can see what the code does in the serial monitor.

You are right, I connected a buzzer to pin 9 and my code works well. The problem seems to be in my vibrating motor. I have 100 uF decoupling capacitor for my AVR but the vibrating motor has none. I'll try adding one.

I tried this snippet in a while(vibrEnabled) Vibrating(); test and the code works, how I can see it being used. This is a hardware related problem, you should if possible post your hardware set up, schematic and such.

The problems were caused by the vibrating motor. It's shaking caused the rotating part touched the surface and the motor stopped for a while.
Thank you for you help.

Maybe your vibrating motor is actually shaking something loose. A dodgy batter clip or something.
Maybe your vibrating motor is drawing too much current and power-cycling the board.
Maybe your vibrating motor is doing weird, bad things like generating back-EMF spikes that it's sending back into the arduino.

It's probably number 3. Generally speaking, you never power motors off an output pin. Run the output into a mosfet or something with a flyback diode across it. Google "circuit to power motor from digital out".


text:
PID and pulseIn()
I am making a system of regulation of the temperature using PID.
I want to keep my temperature in 37 celsius.
in order to understand the stability of my system easily, I want to see the fuction of temperature in terms of time.
I found a function pulseIn() who Read a pulse (either HIGH or LOW) on a pin.
But I don't know how to do it into my program.
this is the program of my PID system:
#include <PID_v1.h>
#include "math.h"
int c=0;
int  i=0, output2 = 0, output3 = 0;
double val=0.0;
double val2 = 0.0;
//Define Variables we'll be connecting to
double Setpoint, Input, Input2, Output=0;
double tOnMax = 50.0;

//Specify the links and initial tuning parameters
PID myPID( &Input, &Output, &Setpoint,10,20,20, DIRECT);

void setup()
{
  //initialize the variables we're linked to
  Setpoint = 37; //temperature a reguler

  //turn the PID on
  pinMode(9, OUTPUT);
  myPID.SetOutputLimits(-100, 100);
  myPID.SetMode(AUTOMATIC);
  Serial.begin(19200);
  while (!Serial);
}

void loop()
{
  // phase haute
  digitalWrite(9,HIGH);
  delay(output2);
  // phase basse
  digitalWrite(9,LOW);

  for (i = 0; i < 64;i++)
      val += analogRead(0);
  val /= 64.;

 for (i = 0; i < 64;i++)
      val2 += analogRead(1);
  val2 /=64.;

  float mv = round (( val/1024.0)*5000);
  float mv2 = round (( val2/1024.0)*5000);
  Input = mv/10;
  Input2 = mv2/10;
//  Serial.println(Input);
  myPID.Compute();
  output2 = map(Output, -100, 100, 0, tOnMax);
  output3 = map(Output, -100, 100, 0, tOnMax);
//  Serial.print("output is :");
//  Serial.println(output2);
//  Serial.print("Input: ");
for (c=0; c < 500; c++) {}
Serial.println(Input);

}

thnak you in advance

pulseIn() returns the number of microseconds that a digital signal is in a specific state. I fail to see what that has to do with measuring temperature.

well! is there any way to see the temperature in terms of TIME?

Temperature is temperature, time is time. I don't understand what you are asking.

There is a problem in that the timebase for the looping/PID sampling is variable, with the on pulse being delay(output2) milliseconds and the off time being whatever the calculation/printing time of the rest of the loop.  As is, with low, but non-zero, output2 it will just loop() faster and might not add less energy to the heated system.  Add a delay(tOnMax - output2); in phase basse to fix that and get a more stable  timebase.

@Majenko I want to see the evolution of the function tempertaure (t), in other words, i want to see in my screenfor exemple: 24.1C -> 20ms ; 25C-> 200ms; 26 -> 500ms ....

Second, With a Setpoint of '37' for the PID, and using Input=mv/10, then Input is temperature.  Your output of the PID is  a bit odd, as -100 to 100 mapped to (0,tOnMax) (you could skip the map() and SetOutputLimits(0,tOnMax) directly) and the (mapped) output value is what the PID is trying to drive.  You can treat that as TIME or output2/tOnMax as a duty cycle or percent of power if you correct the off-time as above.

Third, Physics-wise, the time-temperature relation depends on how fast energy leaks out of your heated system, and depends on the ambient temperature.  If you know the wattage of your heater, you could multiply it by the duty cycle to give you a power in, and your question might evolve to be more about mapping wattage to temperature, and that you'd have full watts with a large error, and a steady-state wattage when you reach temp.  How many watts is your heater and at full power, how long would it take to get half-way from ambient to 37C?

@Dave X thank you very much for your comments. actually, the heater has 10 watts... and it takes around 30 mn to reach to the value 37

OK, with such a slow heater as compared to the calculation time of the arduino, you likely want to use a much longer sampling time.  You could disconnect the PWM time and the sampling time from the loop() time by replacing the delay() with millis() as in http://arduino.stackexchange.com/questions/17918/using-arduino-for-simultaneous-lighting-effects/17929#17929 , and with a sampling time of 1s or 1minute,  the parameters of the PID could start making sense.  i.e. the D term would conform to watts/(degreeError/minute), the I term to Watts/(degreeError*minutes) and P to watts/degreeError.

I don't want to edit your code, but for a quick fix, set tOnMax=6000, add the delay(tOnMax-output2), and drop the for loop.  This will set your timebase to 10s.  And then reconsider your PID settings.  PID myPID( &Input, &Output, &Setpoint,10,0,0, DIRECT); would start to proportionally turn it off at 37-6000/(10*200)=34C, which might be good enough.

Also, add a 'val=0.0; val2=0.0;' to initialize them within the loop.  Otherwise they will grow unbounded, overestimate the temp and turn things off.

Is your question still about pulseIn()?  or would a title like "Reporting PID heater system output" be more descriptive?

sorry to be late for the answer, my title will be more descriptive if I rename it ''Reporting PID heater system output''. and actually, I followed your advice and my system works correctly, thank you very much Dave X :)

OK, with such a slow heater as compared to the calculation time of the arduino, you likely want to use a much longer sampling time. One could disconnect the PWM time and the sampling time from the loop() time by replacing the delay() with millis() as in Using Arduino for simultaneous lighting effects and below, and with a sampling time of 1s, 10s or 60s, the parameters of the PID and the integral and derivative terms could start making sense. i.e. the D term would conform to watts/(degreeError/minute), the I term to Watts/(degreeError*minutes) and P to watts/degreeError.
One nice way to think of a PID controller is that it converts process errors into a control variable.  If you want to convert "degrees below setpoint" into "milliseconds of heat per tOnMax second cycle", set that directly:
// Tuned for full power (1000ms/sec) up to 35C: P=1000/2
PID myPID( &Degrees, &millisecondsOn, &Setpoint,500,0,0, DIRECT);
myPID.SetOutputLimits(0, tOnMax);
...

Or "duty cycle of heater"
// Tuned for full power (100%) up to 35C: P=1.0/2
PID myPID( &Degrees, &millisecondsOn, &Setpoint,0.5,0,0, DIRECT);
myPID.SetOutputLimits(0, 1.0);
...

I didn't want to edit your code too much, but went for a 1s PWM frequency, 10s sampling or PID cycle time.   The 1sec PWM/cycle time is the minimum most commercial PID controllers work with (typically 1s-999s to handle a range from solid-state-relay controlled resistive heating elements to relay controlled mechanical systems like pilot light heaters or fan/pump systems) and should be plenty fast enough for your system.  Slower PWM times are better for mechanical systems, and faster times are better for thermal cycling of resistive elements.
The 10s cycle time is ~200x slower than your initial code looks like it is sampling, but the 10s time might be more in keeping with the physical changes in your system as compared to your resolution.  I can't tell the temperature resolution of your sensor for your code, but assuming it is 0.1C, taken with a (37C-20C)/30m=0.0094C/s rate of change, it would take about 10s to make 1 bit of  detectable change.  If you sample faster than that, all you will be getting is noise or no change.  Sampling significantly faster than the physical process changes can serve to confuse a PID in the integral and derivative terms--Derivative because the derivative of error is mostly zeros or noise, and Integral because the integral accumulator can wind up before the system even begins to move.  Looking at the Arduino PID library code at https://github.com/br3ttb/Arduino-PID-Library/blob/master/PID_v1.cpp#L57 with a I=20, output limits of (-100,100), a t0=20C, a setpoint of 37, sampling time of 50ms, and a temperature rate of change of 0.0094C/s, the Iterm accumulator would be wound up to 100 in just 0.300 seconds.  The wound-up integral would guarantee an overshoot until the integral accumulator erodes afterwards (For example: 37.5C for 10s? 37.1C for 100s? ???)
With a 1000ms PWM and 10s sampling time base, you would need to reconsider your PID settings.   In particular, the I and D terms strongly sensitive to the sampling time and the output range.  As a start, PID myPID( &Input, &Output, &Setpoint,500,0,0, DIRECT); would start to proportionally turn the heater off at 37-1000/500)=35C, which might be good enough for your needs.  If that isn't close enough, you could increase P more to tighten the proportional band.  ("Proportional band" is error band where the P*error term of the PID doesn't saturate the output limits, i.e., PropBand = +/-(tOnMax/P) )   Alternately, you could fiddle with the I term to completely eliminate the droop.
#include <PID_v1.h>
#include "math.h"
int c=0;
int  i=0, output2 = 0, output3 = 0;
double val=0.0;
double val2 = 0.0;
//Define Variables we'll be connecting to
double Setpoint, Input, Input2, Output=0;
double tOnMax = 1000.0; // 1 second PWM controlling 10w heater
unsigned long sampleTime, heaterTime;

//Specify the links and initial tuning parameters
// Process takes 30m to come to 37C from 17C at 10W
// Proportional: Full power to setpoint-2C, then proportional taper: P= tOnMax/2
// Integral: 30m = 300 samples, so area under curve = 20*300/2=3000
// so for integral to roll up to 50% power (1/2 tOnMax) in 30m:
// I = tOnMax/2/3000 = 1000/2/3000 = 0.15
// Derivative: Max slew rate of 20C/30m = 20C/300 10sSamples = 0.067C/sample
// Ignore the derivative for now to avoid potential noise problems,
// but D=tOnMax/0.067=15000 would anticipate and counteract the maximum slewing rate
PID myPID( &Input, &Output, &Setpoint,tOnMax/2,0.15,0, DIRECT);

void setup()
{
  //initialize the variables we're linked to
  Setpoint = 37; //temperature a reguler

  //turn the PID on
  pinMode(9, OUTPUT);
  myPID.SetOutputLimits(0, tOnMax);
  myPID.SetMode(AUTOMATIC);
  Serial.begin(19200);
  while (!Serial);
  heaterTime=sampletime=millis();
}

void loop()
{
  unsigned long now = millis();
  if(heaterTime < now){
     if(digitalRead(9)) {// phase haute -> basse
        heaterTime += tOnMax-output2; // schedule on
        digitalWrite(9,LOW);}
     } else {  // phase basse -> haute
       heaterTime += output2);  // schedule off
       digitalWrite(9,HIGH);
     }
  if (sampleTime < now ) {
      sampleTime = sampleTime + 10000;  // every 10 seconds
      val=0=val2=0;
      for (i = 0; i < 64;i++)
          val += analogRead(0);
      val /= 64.;

      float mv = round (( val/1024.0)*5000); // convert to degrees*10?
      Input = mv/10;        // degrees
      myPID.Compute();
      output2 = Output;
      Serial.print(Input);
      Serial.print("C -> ");
      Serial.print(output2);
      Serial.print("ms / ");
      Serial.println(tOnMax);
   } // end sample
}

thank you again for your response I really appreciate your help. I still have a question about what you said ''but went for a 1s PWM frequency, 10s sampling or PID cycle time. With a 1000ms PWM and 10s sampling time base, you would need to reconsider your PID settings.'' actually can you give me some details about the 1s PWM frequency and 10 s sampling time ... i failed to understand it, thank you in advance

The 1s PWM frequency is set in my edit by the tOnMax of 1000 ms, and the PID chooses a duty cycle within with an on-time of output2 and an off time of tOnMax-output2.  The sampling time is how often one would take a measurement.  Since your process seems slow (assuming 20C to 37C in 30 minutes at full power, or about 0.5C per minute = 0.0094C/sec),  fast sampling times won't detect much, so I chose 10s sampling time.  At that rate, the most the process will change is 0.09C/sample, which might(??) be significantly less than your sensor resolution.

I added some to my answer about my choice of times.

I want to see the evolution of the function tempertaure (t), in other words, i want to see in my screen for exemple: 24.1C -> 20ms ; 25C-> 200ms; 26 -> 500ms

Quite apart from managing the heater, it sounds as if you need to sample the temperature at a constant rate, compare its value to any of several temperature-intervals, and, when it moves out of one interval into another, report the time it spent within the previous one. This will require saving which interval the temperature was last observed in, and the time it entered that interval, re-saving both when it moves into a new one. You may need to apply some smoothing to the temperature data to if there is any noise in the temperature data to prevent it appearing to jitter back and forth between intervals during interval edge crossings.


text:
Make a PC graphical interface for Arduino - Any easy software?
What's the best/easiest software to make a PC-Arduino interface? Ideally, I need to create a .exe that shows up a simple graphic interface, where the user can display data acquired from sensors connected to the Arduino (eg. Voltage, current etc.) and from there he should be able to control Arduino outputs through graphical buttons/switches.
To say that I am not a programmer, so if there's some sort of 'graphical coding' or 'non coding' software to make such things it'd be great!
Thanks for your help!!!
UPDATE:
Image of how the user interface should look like:

Welcome to Arduino SE! This question is off topic since it's not about Arduino, it's general programming (with an Arduino connected to the computer, but that's not even really significant in the question). Thanks!

The "best" software for me is the free Visual Studio Express for Desktops.
Using C#, I would add a SerialPort component to the form, configure it for the same COM port as the Arduino/FTDI, then send commands to it.

Visual Studio is "stupid simple" (I'm not implying anything :D). Double-click Button in the toolbox(1) and it creates one. Double click the button(2), and it outlines the code and attaches the Click event to it for you. Double click Components>SerialPort(3) to create one. My code is highlighted in blue to the right and this took all of 1 minute to create.
To point you in the right direction on the Arduino side, here is the structure of the "command" I sent in the screenshot:
XXXYYYZZ
Where:
XXX = 000b for "turn off", 001b for "turn on", 010b for "toggle", 011b for "read pin"
YYY = Pin number //Max = 111b = 7 (+ 0) = 8 uniquely addressable pins (using 3 bits)
//Pin number does not have to match the MCU port/pin designations
//MCU will convert logical pin #'s 0-7 into the correct physical port+pin
//For more pins, steal another bit from ZZ; Max for YYYY = 1111b = 15
ZZ = Spare bits //Tell the Arduino whether to acknowledge or not, etc.

00100100b = "Set pin 1 high"
01001000b = "Toggle pin 2"
10000000b + 0xAA (two byte command) = "Reply with contents of register 0xAA"

Additional commands can be created to tell the Arduino to reply with a specific variable or status.
bool isRegisterRead = false;
bool isMultiByte = false;
while (true)
 if (wasByteReceived) //This flag is set in the RX interrupt and the byte is saved to byteReceived
  if (isMultiByte) //Second byte received
  {
    if (isRegisterRead)
    {
      //We need to read and send the value of the register at the address in byteReceived
      ReadAndSendRegisterValueAtAddress(byteReceived);
      isRegisterRead = false;
    }
    else DoSomethingWith(byteReceived);
    isMultiByte = false; //Start over
  }
  else //First or only byte received
  {
    //Consider using a ZZ bit to indicate more data instead of listing them explicitly
    if (byteReceived == 0x80) //A multi-byte "read register" command
    {
      isMultiByte = true; //Next byte received is money
      //For my example we need to set a flag somewhere to indicate that we are reading a register
      //isRegisterRead should be set to true by DoSomethingWith
    }
    //Is there any processing for the "command" byte? (i.e. extract and save the pin number)
    DoSomethingWith(byteReceived); //Process one-byte command or first of two-byte command
  }

Answer tip: to view image in full size, right click and open image in new tab (chrome) or save it on your PC. Thumbs up for excellent answer btw.

Almost impossible to answer really. Questions with "best" are always going to yield opinions which probably won't apply to your situation. For example, I would do a C# desktop application because that's what I do, and nothing in that environment hinders communication with an Arduino. So, what's best for me is best because of "familiar and will work" and we can't decide what meets those criteria for you.
If you will update your question to describe more about your application, details about your interface, users, and what skills you have, then I will update this answer, but as it stands "the world is your oyster" because almost any programming environment capable of making an application will be able to interface with Arduino in some way.
For "graphical" programming look into LabView - I can think of a lot of reasons to not go that way though.  http://www.ni.com/labview/
Here's a tutorial for interfacing a c# application with Arduino:
http://www.codeproject.com/Articles/473828/Arduino-Csharp-and-Serial-Interface
The gist of it is this:

Some version of Visual Studio up and running - you can use the free version mentioned in Jon's answer (Express version for desktops).
A working Arduino connected to your computer with the USB.
Create a new Windows Forms Application and drop whatever controls you need onto the form
Write your Arduino-connecting code into the events of the controls

That is the basic method of creating Windows Forms apps regardless of what you're doing. You create forms with controls and your custom code goes into the events of those controls. If you read the tutorial it explains how that code works, but here's a sample... (In the tutorial, they are doing a WPF app, which is slightly different from Windows Forms in how the controls are defined, but the code is basically the same). This is an event of the serial port - you respond to the event by displaying the received data into a text box. Very simple!
void mySerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) {
    string data = mySerialPort.ReadTo("\x03");
    myForm.myTextBox.Text = data;
}

Thanks for your answer Jasmine!
Agree, "best" is not the right term in this situation.
I am trying to make an application to monitor voltages and currents fed back from a number of Arduino units wirelessly to a PC. The user, through the application, should also be able to control simple high/low output states on the Arduino (under the control panel - see updated image above).
I am not particularly skilled in software programming, that is why I asked for a graphical software. However I can pick up the logic quickly as I know some C, VHDL and Assembly.
Why wouldn't you recommend LabView?

LabView "apps" are hard to distribute. The software itself is expensive ($1000 base). The controls have a 'rustic' look. LabView as a skill is hard to market because the industries which use it are fairly narrow - aerospace, hard sciences mostly. So, learning it to do this simple task wouldn't be worth it.

And, have you considered using physical controls, making the device self-contained? This would be better than using a computer interface, but a little more expensive in parts cost.

The device is also self-contained. I need the application to run the manual mode so the user can manage them at any time. Any other suggestion about what programming language or software is most suitable to make such app?

No, even with the additional information I would still go with a c# desktop app. There's a lot of good ways to do it.


text:
How to debug an Arduino sketch on a Mac?
I have 2 Lowpowerlab WaterMote's talking to each other using the 'out of the box' pre-installed sketch that just confirm they're talking to each other. I verified this by opening a COM connection and saw traffic of 'receiving packets...' That was just to show that they are functioning and talking to each other.
Now, using Arduino IDE on Mac OS X 1.9.x (Lion?) I have loaded the WaterMote sketch (found on Github) on the Moteino with the sensor (not the gateway) as it should be. The traffic looks like it's working, except the text being transmitted (number of Gallons) stays the same at 0.02 Gallons.
So... I want to debug the WaterMote sketch, but I do not see an option in my Arduino IDE on Mac OS X. Is there a way to debug sketches using Macs? Searching online shows various and preferred options, but mostly on Windows (of which I don't have any at home).
My current setup

Moteino Gateway (as out of the box) connected to a Raspberry Pi (with ssh enabled)

Connected via USB to the RasPi

Moteino with WaterMote sketch loaded

Connected via USB to the MacBook Pro
Arduino IDE running, but I see strange "[][][]" square output in the Serial connection.
I do not know what to make of this since that text is not in the WaterMote sketch.

Is there a way to debug sketches loaded on Arduino clones using Arduino IDE on Macs?
I found a debugging article:

Visual Micro

Hello and welcome to Arduino Beta! I cannot find any of these "debugging" pages you are talking about. Can you post a link in your answer? Also, for the strange square output, are you sure you have it on the right baud rate and nothing is connected to pins 1 or 0 on your Arduino clone? Those both could be causes of garbled text in the serial connection window.

Yes, please link to these "debugging" tools you have found

While I did find several articles on how to debug Arduino, I only still had one open, so that's the one I provided (sorry). For those interested, search for "Arduino debugging", "Atmel Arduino", "Arduino Visual Studio" or "Arduino Eclipse". Hope this helps others.

So... I want to debug the WaterMote sketch, but I do not see an option in my Arduino IDE on Mac OS X. Is there a way to debug sketches using Macs? Searching online shows various and preferred options, but mostly on Windows (of which I don't have any at home).

It's definitely possible to debug a sketch with OS X. But it's definitely an advanced AVR topic, and if you're not experienced enough with embedded programming you should first try to avoid it, except if it is really necessary.
Debugging a sketch for an ATmega328 implies:

Running a flasher such as the AVR Dragon, the JTAG ICE 3, the STK500 or the AVR ONE; no cheap flasher implements the DebugWire protocol;
Setting up the debug fuse, which is an operation that can brick your MCU.

If you're using an ATmega32U4 (or alike), you won't be able to do it out of the box, as the 32U4 needs a JTAG connection for on-chip debugging.
Finally, once you got through that, you can bind a gdb to the AVR using AVaRICE. I'm not getting you through all that, because I really, really, strongly advise you not to do it until you're experienced enough to know what you're doing.

Moteino with WaterMote sketch loaded
         connected via USB to the MacBook Pro
         Arduino IDE running, but I see strange "[][][]" square output in the Serial connection.
         I do not know what to make of this since that text is not in the WaterMote sketch.
  Is there a way to debug sketches loaded on Arduino clones using Arduino IDE on Macs?

It is very likely you did not setup the correct baudrate for the serial outputs. Arduino IDE defaults to 9600 bits/s connections, whereas the WaterMote source code defines a 115,200 bits/s connection. When you open the Serial Monitor change the setting at the right of the status bar.
And finally, be sure to uncomment the #define SERIAL_EN line to enable the serial communication and debug outputs.

I did use the 115200 baud rate in Serial connection. I know I set this correctly since that's how I was able to upload the WaterMote sketch. I do have it connected to PIN1 since that's what the WaterMote sketch references but I will keep pluging away "#define INPUTPIN      1". When I find the answer I will post it back here. Thanks all !

Aha! Now I understand what you meant! Yes, I did have a cable connected to PIN1, BUT since that prevents uploading sketches, that was the problem. I changed the sketch to use PIN2 AND also moved the cable from PIN1 to PIN2. Now the sketch loads properly and, most importantly, I'm able to see Debug information on the Serial console. Thanks so much!!! Now to figure out how to get proper readings.


text:
How to read pH value
I am trying to read the pH value from a analog pH meter, SEN-01454. From the source code I found, voltage maps to pH value. This is the code:
pHArray[pHArrayIndex++]=analogRead(SensorPin);
      if(pHArrayIndex==ArrayLenth)pHArrayIndex=0;
      voltage = avergearray(pHArray, ArrayLenth)*5.0/1024;
      pHValue = 3.5*voltage+Offset;
      samplingTime=millis();

But then the value is not correct. So how do i actually do it.
The example code from Wiki page for product.

What value do you expect?

the value of the liquid

ok a bit more specific, what liquid are you testing. Do you know what that liquids' pH is, this is of use if you are calibrating it. If you are testing a liquid and don't know its pH before testing you might actually be getting the right value.

Sodium Hydroxide which is pH value of 12.

and the value you are getting?

This is SOME of the code. We are missing the avergearray() function.. I suspect you're taking one reading and averaging it with both old & future ones, but this code clearly is meant to sit in a loop..
From another source, I got this:
/*
# This sample codes is for testing the pH meter V1.0.
 # Editor : YouYou
 # Date   : 2013.10.12
 # Ver    : 0.1
 # Product: pH meter
 # SKU    : SEN0161
*/

#define SensorPin 0          //pH meter Analog output to Arduino Analog Input 0
unsigned long int avgValue;  //Store the average value of the sensor feedback
float b;
int buf[10],temp;

void setup()
{
  pinMode(13,OUTPUT);
  Serial.begin(9600);
  Serial.println("Ready");    //Test the serial monitor
}
void loop()
{
  for(int i=0;i<10;i++)       //Get 10 sample value from the sensor for smooth the value
  {
    buf[i]=analogRead(SensorPin);
    delay(10);
  }
  for(int i=0;i<9;i++)        //sort the analog from small to large
  {
    for(int j=i+1;j<10;j++)
    {
      if(buf[i]>buf[j])
      {
        temp=buf[i];
        buf[i]=buf[j];
        buf[j]=temp;
      }
    }
  }
  avgValue=0;
  for(int i=2;i<8;i++)                      //take the average value of 6 center sample
    avgValue+=buf[i];
  float phValue=(float)avgValue*5.0/1024/6; //convert the analog into millivolt
  phValue=3.5*phValue;                      //convert the millivolt into pH value
  Serial.print("    pH:");
  Serial.print(phValue,2);
  Serial.println(" ");
  digitalWrite(13, HIGH);
  delay(800);
  digitalWrite(13, LOW);

}

which reads in the array first and then averages it. Is this what your code does? If so, what sort of errors are you seeing?

There is no error. But i can't get the correct value of the pH

So what values do you get instead? And, with respect, there probably is an error - or it would work!


text:
How big of a difference is there between an Arduino Uno and the rest?
Lately I've been fooling around with a project for my Microsoft Sidewinder Force Feedback Pro Joystick. I've found out that there is a project currently for it built for the Teensy 2.0. On the page for the Teensy 2.0 there is a link for an Arduino Library for the very same project that was (I guess) converted. There isn't much documentation for it, and I don't think there is much progress being made on it anymore. However when I grab the files and try to upload it to my Arduino Uno it spits out an Unsupported device. Doing some digging around I found where it shows what devices are supported in the includes.h.. Which happen to be
#if defined(__AVR_AT90USB162__) || defined(__AVR_AT90USB82__)
 #define __AVR_AT90USBX2__
#elif defined(__AVR_ATmega16U4__) || defined(__AVR_ATmega32U4__)
 #define __AVR_ATmegaXU4__
#elif defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__)
 #define __AVR_AT90USBX6__
#else
 #error "Unsupported device"
#endif

Which ends up being the red arduino, arduino micro, arduino leonardo, and I think a few teensys.
What I want to know is if you can upload this code onto a UNO. I'm not really wanting to purchase a teensy just to check if this will work or not.

You can try removing the #error line and see what happens.

No that won't work

@BrettAM Actually that was the first thing I tried lol. Its trying to verify what Arduino I am uploading to. Which if I change the board in the arduino software it will compile and attempt to upload. However will ultimately fail.

The code won't work as a traditional project when uploaded on an Uno, because the Uno does not talk directly to the Host, it only speaks UART.
But good news is that the Uno uses another atmega chip, an Atmega8u2 on the older models or Atmega16u2 on the others. That IC handles directly the USB connection with the host on behalf of the Atmega328. And that code below is actually (close enough) support for that IC:
#elif defined(__AVR_ATmega16U4__) || defined(__AVR_ATmega32U4__)
 #define __AVR_ATmegaXU4__

That means you should be able to upload the code (or a similar one) on that 'frontend' IC, so it acts as a HID device, and connects to the main 328 for any I/O you might need.
To do the upload on that other chip, you can use an ISP programmer on the 6pins header close to USB, or you can use the DFU programmation mode over USB.
I'm sorry for not giving external references or code, but I'm answering from my phone!
Edit: after a short browse over the code, it's definitely possible to implement that using an uno, but you'll need to split the code between the two chips: the USB interface to behave like ah HID device and the main I/O chip to talk midi, and implement comms between both.
Edit #2:
Here's a few resources that might help to work out USB and Midi using Arduino, but it looks like none is a cooked in USB on atmegaXu2 to Midi on atmega328:

http://unojoy.tumblr.com/
http://forum.arduino.cc/index.php/topic,111.0.html
http://hunt.net.nz/users/darran/weblog/15f92/Arduino_UNO_Big_Joystick_HID_firmware.html
https://stackoverflow.com/questions/16710701/joystick-usb-definition-for-use-with-arduino
http://hackaday.com/2011/03/28/hiduino-the-only-limit-is-yourself/
http://arduino.cc/en/Hacking/DFUProgramming8U2
http://arduino.cc/en/tutorial/midi
https://sites.google.com/site/bharatbhushankonka/home/diy-midi-over-usb-using-arduino-uno
http://www.instructables.com/id/Turn-your-Arduino-Uno-into-an-USB-HID-Mididevice/

And if you're not at ease with AVR development, it's gonna be HARD. You'd better get a teensy2 or a leonardo where that code should compile and work with little effort.
HTH

It's actually a '16U2, not a 4.

I have no problem with working with DFU as I have played around with UnoJoy before (like I said to someone elses post I tried converting the signal coming out of my RC Receiver to something I can use over UnoJoy, but was having issues with that) However I'm not nearly skilled enough to go through the entire code to split everything up and recode as needed. I might just have to go ahead and get the teensy2.

That's a sensible choice, you might otherwise take a leonardo (based on the atmega32u4) that should be compatible (maybe with very minor changes, like for the pins) with the code.

That program will make the arduino board act like a keyboard to the PC it's plugged in. This can't be done on the Uno, since it doesn't have USB support.

It actually can, given you change the atmega16u2 firmware for one that makes it behave like a keyboard.

@zmo you are correct. It's however quit involved, so I chose not to mention it.

@Gerben Its not that involved, as I've played around with UnoJoy which makes everything quite simple. I tried messing around with it to convert PWM from my RC Receiver so I can use it in games, but that's a whole other issue I'm having.

Generally, the differences between the different chips are mostly: amount of memory (sram, eeprom), number of pins (analog, digital, pwm), numbering of pins, and hardware support for protocols (serial, SPI, 2 wire etc)
In this case, you would have to go through the code wherever you find #IFDEF __AVR_AT90USBX2__ or #IFNDEF __AVR_AT90USBX2__ and the others - you would need to work out what it is doing differently for each, and work out how you would do the same thing on the Arduino Uno (which runs on an Atmega328).

I believe it defines what each pin is, what they do, and how they will be bound to the device. Which I would have to go through everything for the Uno's chips.


text:
Pro Mini 5v with Adafruit motor shield v1 power sharing problems
I am trying to convert a RC car into autonomous car using Arduino Pro Mini 5v 16 Mhz. I have done this with UNO and Adafruit motor shield 1.0 with 4 gear motors and one micro servo for mounting range finder sensor. That worked fine.
Need to mention here that originally the RC car was using 5 AA cells for 2 motors and its RC reciever which looks like a customized motor shield as well.
I tried to move everything to Arduino Pro Mini 5v, and motor shield v1 to reduce space. Now how I wired everything.

Uses 8 AA cells to power the motor shield on EXT-PWR input.
From EXT-PWR in motor shield one wire goes to RAW in Pro mini.
From Pro Mini, VCC connected to +5v on motor shield.
One micro servo having range sensor getting its current from motor shield.
Motor shield has to run two motors, 1 for rear wheels and 1 for turning front wheels. (they are small motors look like 3v)

Now when I turn on the power the motor sometimes run and sometimes sound like bee and no movement. That also cause the L293d chip on motor shield becomes very hot and I think I have burnt one yesterday and replaced it from another motor shield. Same for servo it sometimes move or not move but sounds like hmmmmmmmm. The Arduino power light on and red. But sometimes it flickers and other light is also on and off.
At this point I have no idea whats wrong here. I changed the input voltage to lower but no progress. Tried to disconnect the 5v input from Pro Mini to motor shield and give 9v input to motor shield but nothing works. Please suggest best or correct power distribution in this case.
Thanks
Qazi

You mention all the power connections, but no mention of the ground...  Is the ground connected between the motor shield and the Arduino?

There are many ground pins on Arduino and motor shield, does it mean I have to connect every ground pin on both boards? I remember I connected some. Will check it again. Is there any specific ground pin to specific ground pin?

I would check each motor without the motor shield to see if the motors are ok. Check the motor shield motor supply, should be around 12 volts with 8 AA cells. You might run a simple test program to see if the motors run full power forward and full power backward with the motor shield. Check the servo with a simple program like the Arduino Knob program. I suspect the Pro Mini 5 volt regulator is overloaded, causing the buzzing sound, but you have to find out why. One possible reason is that you are dropping from 12 volts to 5 volts via the pro mini linear regulator, creating all kinds of heat. The additional load of even a small servo might push the power dissipation spec over the edge.

After lot of research, I found 5v regulator on pro mini is not good enough to power any outside circuit. It is running my motor shield v1 but when I want to run 9g servo from shield, servo shakes and stops in the middle. Waiting for my 5v regulator transister to make my own 5v supply.

Sounds good, a more capable linear regulator with heat sink. Another possibility is to get a DC to DC converter (buck regulator from 12 volts to 5 volts), that way is more energy efficient than a linear regulator. They cost just slightly more than a linear regulator on ebay, and don't need a heat sink.

I am talking about 7805 which is also dc to dc from 12v to 5v supply. Are we on the same page?


text:
Motor shield power from Arduino pro mini 5v RAW Pin 150mAh cannot run servo
linked to my old question, Pro Mini 5v with Adafruit motor shield v1 power sharing problems

I figured out and use one 7.2v battery (6 AA cells), and link it with RAW pin to Pro mini and join its 5v pin to motor shield 5v. It works but as I have a servo on this shield, 2 distance sensors so servo does not work well all the times. Stops or does not move as directed, shaking etc. I figured out that pro mini output 5v but only 150mAh which is not sufficient to run a servo which while sharing same 5v for motor shield. I need to know if I want to supply 5v 2000mAh from AA cells or 5v regulator, should I use these pins on motor shield (5v, Gnd, 9v)? I tried but it did not work. I did not find it anywhere on net.

How can I use these pins shown in the picture.
What is the min/max mAh value of current I can provide at these pins?
If supplying input current at these pins, should I connect/disconnect power jumper?
I am totally stuck. Need help. And here is the quick diagram how things are attached. All other pins are attached at shield connects to UNO when stack on it.

How well does it work in the following situation? : Jumper off;  motor-power battery  connected to Ext_Pwr;  separate Arduino-power battery connected to pro-mini RAW  (or 5V power supply connected to pro-mini Vcc); a ground pin on the shield wired to a ground pin on the  pro-mini

It worked but servo is not getting enough power so it gets lost many times and does not move at right time so left-right-center readings from u-sonic sensor not correct and car hits wall or stops in the middle.

What are the rated voltages of the servos and the sensor? How do you know the servo is not getting enough power? To hold down electrical noise, power the sensor from pro-mini Vcc instead of from motor battery if sensor is rated at 5V.  Minimizing electrical noise is one reason to use two separate power supplies.  The motor driver and the pro-mini need to have a common ground but don't have to have common Vcc

You can't, or at least you can't do it the way you want to. Each pin can give you a maximum of 40mA. You may try using more than one pin but that possibly wont work for you. I suggest you supply additional power from a separate source and control On/Off from Arduino. It would be like a relay. Or simply buy a relay to do this.

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


text:
Feasibility of project with 50 leds working independently
I don't have much knowledge in Arduino and I'm about to start a new project which I believe can be done with it.
There will be 50 boxes with a led in top of each one. The user will type a number in a keyboard (1 to 5 for example), and then based on a table, the leds according to that number should light up.
It will have some overlaps, for example, Number 1 would light led 1, 2 and 3, while Number 2 would light leds 1, 2, 3 and 4.
Could I build such a project with arduino? Or are there too many inputs/outputs (keyboard, 50 leds)? I was thinking to buy an Arduino Uno to start learning, but first I'd like to know if it's feasible.
Thanks already

Look up "Charlieplexing" as used in the "LOL shield" - it isn't without tradeoffs, but an ordinary Arduino can drive at least 64 LEDs this way.

depending on how you want to control your LED's there are several options.
firstly to be clear you could not feasibly connect that many LEDs to an arduino that could all be turned on at once (if that was needed) without damaging the arduino.
if all you need is on/off level of control then you could look at shift registers or if you have pre built arrays of LEDS in a grid type layout you could look at the MAX7219/MAX7221
if you also wanted to be able to control the brightness individually then you could look at the TLC5940
if we look at the pros and cons of each approach:
74HC595
pros:

cheap to buy
simple to use

cons:

each LED needs its own resistor
cannot vary brightness
if not using the hardware SPI pins can be slow for large numbers of outputs

MAX7219/MAX7221
pros:

lower current draw than 74HC595
only needs one resistor per IC which can drive 64 LEDs

cons:

actually flashes LED's really fast to look like they are always on
costs more than 74HC595

TLC5940
pros:

can vary brightness with a high number of steps (4096 steps from fully off to fully on)

cons:

uses more output pins than either of the above methods
requires resistor per LED
costs more for the IC than 74HC595

so to sum up, each method has its merits. if you are driving individual LEDs the the 74HC595 is probably the best/simplest route, if you are driving an array then the MAX7219/MAX7221 is best, and if you need variable brightness then the TLC5940 is probably best.

just as a side note, i currently have a project that controls some RGB LED strips that each consist of 3 RGB LEDs per strip (red, green and blue LEDs in a single housing) and a total of 16 strips individually controlled for a total of 48 individually controled outputs with PWM brightness control using three of the TLC5940 ICs. so what you are asking for can definately be done, although my project may be more complicated than you are after.

If you need many resistors, you also can use resistor arrays.

@MichelKeijzers true, just depends on how the circuit is being made/wired up.

Thanks for your answer @JamesKent I have a pre-built array of leds for each number, it can change with time though. I should be able to change the leds that will light up just by changing my code. Is it possible with 74HC595 or MAX7219/7221? Or would I need to set up all my wires again when I want to change the leds that will light up?

chances are if you have a pre made array they it will be wired in a grid pattern rather than giving an individual pin for each LED plus a power pin, instead they will be arranged in rows of shared positive pins and columns of shared negative pins (or the other way round) in which case the 74HC595 cannot be made to work without a lot of hard work. if your led array is something like this: http://www.circuitstoday.com/wp-content/uploads/2016/04/8X8-Matrix-Pinout.png then use one of the MAX chips. the 7219 is usually cheaper and should do what you need

any of the methods i put in my answer are aimed at letting you control which LEDs are lit up purely in code rather than having to re wire any of your circuit.

Do I need a proto shield or something like that for that project? Is it feasible for longer distances (from the arduino to the leds, I'm talking about a couple meters here)?

as for needing a proto shield, it depends how comfortable you are with soldering. and for the distance that depends on a number of factors, the faster you want to send the data the less distance you can send it. if you are aiming to have all the electronics in one place and run wires to LEDs then thats not a problem. if you wanted to keep the amount of wire to a minimum then you'll want to spread the ICs further apart, at which point you may need to slow the data rate down. i think you should be ok, but it depends how electromagnetically noisy the environment is.


text:
Establishing an MQTT connection using Arduino Mega and ESP8266
As the title says, I want to send MQTT messages to a server using ESP8266 with an Arduino Mega as controller, but so far, every library that I have found is based on Ethernet. I don't want Ethernet, I want WiFi, so those solutions don't work for me.
I have tried using PubSubClient library, but the problem is that to create an instance (PubSubClient client(?????)), I have to set a client. What should I put in there? Is there another library I must use?

You require an ESP8266 library that implements the Arduino standard Client & Server classes (or at minimum the Client class).
Personally I'd program the ESP8266 directly to make it perform the MQTT request itself (using the libraries bundled with the ESP8266 core). Have the Arduino tell it what to send through some protocol you make yourself over UART.

you have the AT firmware in the esp8266?
use WiFiEsp library
or if you can change the esp8266 firmware, you could try JeeLabs esp-link


text:
How can I pass a long as parameter and get a char array in return?
I kind of new to C++, so I'm not sure how to perform such casting.
Example:
long myLong = 12345L;
convertToCharArray(myLong); //returns an array with the digits of myLong

BTW I'm working with Arduino IDE.

As with many things in C there are many ways of skinning this particular cat.
All of them rely on you first having made a character array to store the result in - you can't "return" an array from a function.
The simplest, though non-standard, way is to use ltoa(), which is an avr-libc specific function (not part of the standard libc functions):
long myLong = 12345L;
char myCharArray[10]; // Enough room for the answer + 1 NULL char

ltoa(myLong, myCharArray, 10);

The 10 in that function call defines the base to represent the number in - base 10 in this case: decimal.
Another way, which is more portable, is to format the string using snprintf():
snprintf(myCharArray, 10, "%dl", myLong);

In this case the 10 is the maximum length of string to prevent it overrunning the 10-character array we made.
A pure Arduino way of doing it would be to use the dreaded String class:
String myString = String(myLong);
myString.toCharArray(myString, 10);

Again in this example the 10 is the length of the buffer we are copying in to.
And there are more. You could do it manually, character by character using division and modulus operators, for example.

You might be looking for a function that returns the textual representation of a long number. In that case there is actually an AVR standard library function (avr-libc:stdlib.h ltoa):
const size_t BUF_MAX = 32;
char buf[BUF_MAX];
const int RADIX = 10;

long myLong = 12345L;
ltoa(myLong, buf, RADIX);

The buffer, buf, will contain the textual representation of the number, myLong, in the given RADIX.
Cheers!

ltoa isn't standard. It's pretty unique to avr-libc.

Let me fix that for your :)

This is a job for pointers.
long myLong = 12345;
char* myCharArray = (char*)&myLong;

Now pointers and arrays work the same. So you can now use myCharArray[0] to refer to the first byte and myCharArray[1] for the second etc.

My phone won't let me edit that to fix the code proper. If someone wouldn't mind editing that for me I would greatly appreciate it.

I think he means he wants an ASCII representation of the number, not the raw bytes.

You're right. ASCII representation.

Well he referred to "casting" in the question so I told him how to cast it.  If you just want ascii use atol.

I really meant ltoa.

Well for such situations I did found a solution.
To convert Float or Long or int into character array format, we could use dtostrf().
Syntax:
dtostrf(Source_var, StringLength, numVarsAfterDecimal,destinaton_var)

Source_var = the variable you want to convert (float/int/long)
StringLength = Length of the string (for your case just keep it 1)
numVarsAfterDecimal = required number of values after decimal point(keep it zero for now)
destination_var = the char variable to where the value must be stored(do not use square brackets).
For converting Long to array follow the below code
long myLong=12345L;
char var[5];
dtostrf(myLong,1,0,var);

If all goes well
Result will be like var[]={'1','2','3','4','5'}

I found this function very useful and it had been working great for me. Hope it does the same for you.
For more info on dtostrf() : Link

By using dtostrf(), you are implicitly converting the number to float. This is expensive, unneeded, and looses precision if the number is larger than 2^24.

I kind of new to C++, so I'm not sure how to perform such casting.

to recast it, just make a char pointer and pointer it to the variable. Fairly simple.
if you want to convert ti ascii, there are numerous ways, each with their own pros and cons.
I wrote a set of conversion routines here: https://dannyelectronics.wordpress.com/2017/07/04/a-very-fast-numeric-to-ascii-conversion-routine/
they are designed to convert 8 digit unsigned long to ascii but can be easily rewrite to convert 5 digit.


text:
Why does my Arduino seem to reboot every time that I open Serial Monitor?
Every time that I open the Serial Monitor, my Arduino Uno, seems to go back to void setup(). Is it a normal thing?

That is a normal feature of Arduinos, not an error. I find it mildly annoying sometimes, but it's nice for interactive programs that want some kind of menu message to be the first thing you see in the terminal.
If you want help disabling the auto reset, your options are detailed in Disabling Auto Reset On Serial Connection.


text:
Arduino serial port programming
I bought an Arduino-on-breadboard kit. I have several PCs with serial ports, and now I'm being told I need a USB-to-serial converter. I thought I was ready to start uploading sketches, so how can I do this?
I'm able to understand serial communications and am capable of wiring a MAX232 chip into a breaduino if necessary, but I'm not sure it will work, so to save some time I'm asking, mostly because I was unable to figure it out with Google searches alone.
PS: I also have a stk500, but then I would be out of the easiness of using Arduino sketches and the programming language. I need the fastest route to prototyping/testing my sketches.

The arduino IDE supports the stk500: http://arduino.cc/en/Hacking/Programmer

I would highly suggest you also buy an arduino Uno. The breadboard version is great but the uno board will help you verify the rest of your tools and software is setup correctly

thanks for the help guys, will post pics as soon as I have some working prototypes!

@PeterMorensen - please don't make trivial edits to four year old questions, it serves no purpose but to create noise on the overview page.

An RS232 port wired via a level converter (as you mentioned max232) and a 1uF capacitor between RTS and "Arduino reset pin" Getting started with Arduino.
The capacitor is to trigger a reset on the Arduino so the bootloader kicks in and awaits a "Arduino sketch" via the serial port.
Your setup is AKA "Arduino Bare bone".

If your PCs have real RS-232 serial ports (rare these days), you can use those directly.  Otherwise, you will need a USB<->RS-232 serial adaptor cable.
Correction:  I thought my Arduino did have an RS-232 port, but I was thinking of another board.  If your board only has a TTL-level serial port (ie. direct from the ATMega328), then you need either an RS-232 level translator, or a USB<->TTL serial cable.  A suitable cable is available from Adafruit (and no doubt, others).

Can you really connect a RS232 (either real or fake 0-5V ones) directly to a ATmega328 UART port? I thought one had to put a level converter in between them (ie. MAX232).

The original Arduino models did have RS232 serial ports and connectors, rather than the USB connector and on-board USB-serial converter of today's boards.

You cannot connect RS232 to an ATmega328 port (successfully anyway) because the polarity is inverted. With RS232 a 1-bit is -12 V (or thereabouts) and 0-bit is +12 V (or thereabouts). See https://en.wikipedia.org/wiki/RS-232. In other words, a one bit is a lower voltage than a zero bit. Even the 0-5V ones are still going to have inverted logic. SoftwareSerial does have an "inverse_logic" argument on the constructor which might help if you had the 0-5V serial input.


text:
Default value of global variables is not set
I am tracking a bug in the Marlin source code.
Background
Just for those who is not familiar with Reprap 3D printer and G-code: Marlin is firmware that controls a RepRap 3D printer. It receives G-code from a host computer (or read from SD card). Here the important thing is that if you send the "M114" command, it would report information about axis positions. Here, I extended this command to make it print some internal variable as well.
The Problem
In Marlin.ino file there is a line that says:
volatile int extrudemultiply=100; //100->1 200->2

However my RepRap keeps extruding (and worse, ejecting back) a huge amount of filament. So I added some debug output for M114 command to output this value. It turns out this value is not the default value, 100, but something like 12374.
I thought somewhere inside the setup() function this value might be changed. So I defined another variable,
volatile int orig_extrudemultiply = 100;

And then at the first line of setup() function, I added the following line.
orig_extrudemultiply = extrudemultiply;

Finally, I output this value for the M114 command. Still, it is not 100. So it looks like the default value is not effective.
The Question
Although I have experience in C programming, I am new to Arduino development. How is a global variable being initialized in Arduino? In my case, what is the proper way to initialize this value?
Versioning
I originally posted the official Marlin link for the reference. However,
the version I actually use is this fork from the RepRap Pro team. I was just following the Melzi entry of the RepRap wiki, because my board is Melzi. I am not sure whether the latest version of Marlin works for my board.
Further details
As the commenter said, the first thing I thought of was memory corruption. So I wanted to narrow the problem down. Since that value is configurable through M302 SXXX command, I tested this command, and it works without difficulty. This means there is nothing in the loop function or the ISRs can affect this value when it is running stably. So I consider the problem must be in the setup function or earlier.
Further tests shows that setting this value at the end of setup or even at the beginning of setup still works fine. This means the setup function may not be the problematic one. The test in "The Problem" session was the last step, which, in my opinion, means the course of the problem must being run before entering setup.
UPDATE
Further examination shows that although it looks like it works when I set the default value in the first line of setup(), but that it is just luckily being 100. So once I add more padding variables it stops working until I move the default setting after the following line in setup():
EEPROM_RetrieveSettings(); // Loads data from EEPROM if available

However, since I greped for extrudemultiply before any test, and I didn't figure out this function, this function should not change this value. I guess there is some data overflow inside this function, so the value was changed expectationally.
I got to figure out what is wrong in this function.

Problems like this are almost always the variable being corrupted by other code rather than not being initialized properly.

Initial values of global variables like that are typically setup by toolchain provided initializers, and it actually is possible for toolchain usage mistakes to leave them out, but you'd probably notice other problems as well.  Ignacio's corruption hunch is a good one - it can be interesting to try declaring a dummy variable before or after the subject one, and see if the nature of the problem changes by thus steering the mistaken writes differently - though that should not be mistaken for a fix!

It seems you use a pretty old version of Marlin, as this declaration of extrudemultiply has changed Dec 3rd 2012! I suggest you update to a more recent version.

This variable is declared volatile which is generally meaning that it can be modified by an Interrupt Service Routine (ISR).
So it is perfectly possible that this ISR gets called before your setup() function gets called and then it may modify this variable.
In C and C++, variables defined as type variable = xxx; are guaranteed to be initialized before any of your code starts to run.
So this means you must look for the root of the problem somewhere else.
Don't forget that it is perfectly possible that some code gets run before setup() is called.
You may try to search for the code that runs before setup(); unfortunately it can be hard to find out this code:
Indeed, in C++, there are a lot of possibilities for code to execute even before the main() function gets called; for instance, declaring an instance of a class as a global variable, will call the class constructor before main().
So you would have to find out all class instances declared as global variables in all source files, and then check the class constructor that gets called for each instance.
Another way could be to check the assembly produced for your program and find all calls occurring be fore main(), but it can be harder if you can't read assembly.

Thanks your advise. I have updated the question to include some of my observations and opinions. Can you please have a look. Most importantly, where can I find the code that get run before setup() being called?

I've updated my answer to include hints on finding out that code. Even though you have already found the real source of the issue (I'm glad you found it!), I think it was useful to edit my answer anyway.

I accept this answer because although my own answer solves the problem, this answer actual answers the question. The new knowledge I learn from this answer is that Arduino IDE just another C IDE. Except the fact it is to be compiled as Arduino machine code there is not much different with other C/C++ environment. So my common sense about C/C++ is still good.

Thanks for this, @Earth-Engine, I'm glad my answer could bring you useful knowledge. However, considering people having a similar issue as yours in the future, I would suggest you accept your own answer as it is the right answer to your question. Cheers.

My theory is that here is the place to ask about Arduino, not ask about software/firmware bug. So people get to this page because they want to know how global variables being set in Arduino, not because they have problem with Marlin. If people wanted to find solution about bugs in Marlin, they should look at the Reprap pro github page for issues (I have created a pull request for this so people will find it).

The problem of this version of Marlin can be shown in the following piece of code (which is inside EEPROM_RetrieveSettings function):
  for (short i=0;i<4;i++)
  {
    axis_steps_per_unit[i]=tmp1[i];
    max_feedrate[i]=tmp2[i];
    max_acceleration_units_per_sq_second[i]=tmp3[i];
    max_length[i]=tmp4[i];
  }

Here max_length is an array of 3 elements, not 4 (the X,Y and Z axes have a max length to avoid hitting the edge, but the extrude axis does not have such a limit - you should be able to extrude as many filament as you can supply), so the last statement in the loop overrides other variable(s).
The solution is
  for (short i=0;i<4;i++)
  {
    axis_steps_per_unit[i]=tmp1[i];
    max_feedrate[i]=tmp2[i];
    max_acceleration_units_per_sq_second[i]=tmp3[i];
    if(i<3)
        max_length[i]=tmp4[i];
  }

Or
  for (short i=0;i<4;i++)
  {
    axis_steps_per_unit[i]=tmp1[i];
    max_feedrate[i]=tmp2[i];
    max_acceleration_units_per_sq_second[i]=tmp3[i];
    if(i < sizeof(tmp4)/sizeof(tmp4[0]))
        max_length[i]=tmp4[i];
  }

Greate thanks to the answer writer and commenter. Without your help I couldn't follow the right track.

Buffer Overrun strikes again. Make sure you don't need that fourth element though.


text:
Arduino Uno vs Arduino Micro timers → pins
Where do I find the pins relative to timers of each individual Arduino microcontroller?
As I like Arduino's I already have various samples of them. The one I mostly use is the Uno and Micro for now... I'm planning to also get a Mega and others. Most simple things work on all devices, but if you start with complex code to fasten up things, every device is a little different.
A problem I could not solve for days now is the relation between pins and timers.
I cannot find any information about the Arduino Micro. I also don't know exactly what the proper keywords are that I need to find the relation between timers and pins.
Example:
A PWM driver multiplexing
As I for now just got some stuff from my local dealer I have no access to shift registers, PWM drivers and other proper integrated circuits.
So I used the Arduino as a PWM driver for 8 RGB or 24 (3*8) white LEDs.
The code works on Arduino Uno. But as the Arduino Micro has no Timer2, TCCR2B, I cannot use the same code on the Arduino Micro.
Even if I understand the code (I wrote a lot in other languages...), some of the Atmel chip specific parameters are not clear.
This function sets the prescaler of the timer:
void setPwmFrequency(int pin, int divisor){

  byte mode;
  if(pin==5||pin==6||pin==9||pin==10){
    switch(divisor){
      case 1:mode=0x01;break;
      case 8:mode=0x02;break;
      case 64:mode=0x03;break;
      case 256:mode=0x04;break;
      case 1024:mode=0x05;break;
      default:return;
    }
    if(pin==5||pin==6){
      TCCR0B=TCCR0B&0b11111000|mode;
    } else{
      TCCR1B=TCCR1B&0b11111000|mode;
    }
  }else if(pin==3||pin==11){
    switch(divisor){
      case 1:mode=0x01;break;
      case 8:mode=0x02;break;
      case 32:mode=0x03;break;
      case 64:mode=0x04;break;
      case 128:mode=0x05;break;
      case 256:mode=0x06;break;
      case 1024:mode=0x7;break;
      default:return;
    }
    TCCR2B=TCCR2B&0b11111000|mode;
  }
}

First of all, I probably don't even need this function as soon I know what frequency I want, and so I probably need only two lines to set my three (RGB) pins.
//Arduino Uno timer setup for pin 9, 10, and 11
TCCR1B=TCCR1B&0b11111000|0x01; // Pin 9,10
TCCR2B=TCCR2B&0b11111000|0x01; // Pin 11

Correct, I need to set TCCR1B only one time?
What does the 0b11111000 refer to?

In the setup function there is also this line:
TIMSK2 = 1<<TOIE2;

What does this do?

While the above three questions are not so important until it works, I need to understand how I can convert those timers to work with Arduino Micro, but also later with other Arduino boards.

On Arduino Micro
There is no timer 2
Do pin 9, 10, and 12 have the same timer?
??????=??????&0b11111000|0x01;

Also if I understand correctly the Arduino Micro has:

A higher PWM range 1024 vs 255 (UNO)??
A much higher frequency available in on Timer4 only for pin 13

So is there somewhere a table describing the differences between all Arduino timers?
Full working (on Arduino Uno) code.
unsigned char Prescaler=0;
unsigned char CurrentLED=0;
unsigned char LEDValues[8][3];
unsigned char ports[8]={
  0b00000100,
  0b00001000,
  0b00010000,
  0b00100000,
  0b01000000,
  0b10000000,
  0b00000001,
  0b00010000
};//PINS 2,3,4,5,6,7,8,12

#define PrescalerOverflowValue 4

ISR(TIMER2_OVF_vect){
  if(Prescaler<PrescalerOverflowValue){
    Prescaler++;
  }else {
    Prescaler=0;
    Multiplex();
  }
}

void Multiplex(void){
  PORTD&=0b00000011;
  PORTB&=0b11101110;
  analogWrite(9,255-LEDValues[CurrentLED][0]);
  analogWrite(10,255-LEDValues[CurrentLED][1]);
  analogWrite(11,255-LEDValues[CurrentLED][2]);
  CurrentLED<6?(PORTD|=ports[CurrentLED]):(PORTB|=ports[CurrentLED]);
  CurrentLED++;
  if(CurrentLED>7)CurrentLED=0;
}
void setPwmFrequency(int pin, int divisor){
  byte mode;
  if(pin==5||pin==6||pin==9||pin==10){
    switch(divisor){
      case 1:mode=0x01;break;
      case 8:mode=0x02;break;
      case 64:mode=0x03;break;
      case 256:mode=0x04;break;
      case 1024:mode=0x05;break;
      default:return;
    }
    if(pin==5||pin==6){
      TCCR0B=TCCR0B&0b11111000|mode;
    }else{
      TCCR1B=TCCR1B&0b11111000|mode;
    }
  }else if(pin==3||pin==11){
    switch(divisor){
      case 1:mode=0x01;break;
      case 8:mode=0x02;break;
      case 32:mode=0x03;break;
      case 64:mode=0x04;break;
      case 128:mode=0x05;break;
      case 256:mode=0x06;break;
      case 1024:mode=0x7;break;
      default:return;
    }
    TCCR2B=TCCR2B&0b11111000|mode;
  }
}

void setup(void){

  pinMode(2,OUTPUT);//1
  pinMode(3,OUTPUT);//2
  pinMode(4,OUTPUT);//3
  pinMode(5,OUTPUT);//4
  pinMode(6,OUTPUT);//5
  pinMode(7,OUTPUT);//6
  pinMode(8,OUTPUT);//7
  pinMode(12,OUTPUT);//8
  pinMode(9,OUTPUT);//red
  pinMode(10,OUTPUT);//green
  pinMode(11,OUTPUT);//blue
  setPwmFrequency(9,8);
  setPwmFrequency(10,8);
  setPwmFrequency(11,8);
  TIMSK2=1<<TOIE2;
}

void loop(void){
  for(int i=0;i<8;i++){
    //LEDValues[i][0]; // Red
    //LEDValues[i][1]; // Green
    //LEDValues[i][2]; // Blue
  }
}

I cannot find any information about the arduino micro. I also don't know exactly what the proper keywords are that i need to find the relation between timers and pins.

Go to the products page for the Micro on the Arduino web site. You will find that the processor is the ATmega32U4.
Download the datasheet for the ATmega32U4 - it's on that page.
Download the reference schematic for the Micro - also on that page.

Now we know the processor, the datasheet tells you about the timers, and the schematic tells you which ATmega32U4 pins are connected to which pins on the Micro board.

But as the Arduino Micro has no Timer2 TCCR2B i cannot use the same code on the Arduino micro.

True. But it has Timer 1, Timer 3 and Timer 4. You just need to adjust the registers a bit.

Correct, I need to set TCCR1B only one time?

Yes you can do that. Personally I normally stop the timer and then set the parameters in case setting them when it is running has a different effect. eg
TCCR1A = 0;  // stop timer 1
TCCR1B = 0;
TCCR1C = 0;

   TCCR1B=TCCR1B&0b11111000|0x01; //pin 9,10

What do the 0b1111000 refer to?

In this case the first part TCCR1B & 0b11111000 clears the low-order 3 bits (the rest are ANDed in with 1 so they stay the same as before).
Then it sets the lower-order bit. In this particular case you are setting up a prescaler of 1 times the clock rate.

   TIMSK2=1<<TOIE2;

what does this ?

TIMSK2 is a timer register.

By shifting 1 left "TOIE2" bits it sets that bit (ie., TOIE2 in TIMSK2).
In other words, it enables the overflow interrupt for Timer 2.

On Arduino Micro
  There is no timer 2
  Pin 9,10,12 have the same timer ?

Look at the reference schematic. Yes it looks like it.

As you can see from that pin 30 (on the chip) is labelled OC4B which means it is the "output compare timer 4: B output". That pin has the net name "IO10*" which I presume means it is connected to board pin 10 (pin 30 on the chip).

Also if I understand correctly the Arduino micro has:

a higher PWM range 1024 vs 255 (UNO)??
a much higher frequency available in on timer4 only for pin 13

No, the Uno has Timer 1 which is 16 bits (up to 65536). The Micro has Timer 4 which is 10 bits and therefore can count up to 1024.
Anyway, the frequency is a function of the clock speed. On either chip, by using a prescaler of 1, and counting up to 1, you can get an 8 MHz frequency (one up, one down from 16 MHz).
The higher number of bits in the timer, the finer the resolution - that is you can adjust the frequency in finer steps, and you can adjust the PWM duty cycle in finer steps.
However with Timer 4 on the Micro you can, apparently, clock it with 6 times the clock rate (96 MHz) which is used for the USB part of the chip. Setting appropriate bits (I haven't done this personally) you could get that higher frequency.
You can apparently get 96 MHz, 64 MHz or 48 MHz clock frequencies on Timer 4 (as well as the normal ones).

Added in response to comments

Pin 12 on the chip has 2 timers, OC0A & OC1C??

Yes, from the datasheet:

The Output Compare unit 1C and Output Compare unit 2 shares the PB7 port pin for output. The outputs of the Output Compare units (OC1C and OC0A) overrides the normal PORTB7 Register when one of them is enabled (i.e., when COMnx1:0 is not equal to zero). When both OC1C and OC0A are enabled at the same time, the modulator is automatically enabled.

What timer do i need to use for let's say pin 9,10,12 on arduino micro?

Looks like Timer 4.

in arduino ide i can only write analogWrite(255)

That is changing the PWM duty cycle for the timers configured in their default way.
Have a look in wiring.c:
// timers 1 and 2 are used for phase-correct hardware pwm
// this is better for motors as it ensures an even waveform
// note, however, that fast pwm mode can achieve a frequency of up
// 8 MHz (with a 16 MHz clock) at 50% duty cycle

analogWrite changes the duty cycle, not the frequency.

You can apparently get 96 MHz... so at the end arduino micro can go faster on timer 4

I'm not sure what you mean by "go faster" here.

but I actually did not solve the problem. I hope you give me a hint to how to make it work.

It isn't clear really what you want to happen.

What devices are you driving?
Why do you need high frequencies?
What is the underlying problem?

Reference

Timers and counters - mainly about the Atmega328P, however a lot of it applies to the other chips as well.

Comments are not for extended discussion; this conversation has been moved to chat.

You can check pins_arduino.h file as well.
// ATMEL ATMEGA32U4 / ARDUINO LEONARDO
//
// D0               PD2                 RXD1/INT2
// D1               PD3                 TXD1/INT3
// D2               PD1     SDA         SDA/INT1
// D3#              PD0     PWM8/SCL    OC0B/SCL/INT0
// D4       A6      PD4                 ADC8
// D5#              PC6     ???         OC3A/#OC4A
// D6#      A7      PD7     FastPWM     #OC4D/ADC10
// D7               PE6                 INT6/AIN0
//
// D8       A8      PB4                 ADC11/PCINT4
// D9#      A9      PB5     PWM16       OC1A/#OC4B/ADC12/PCINT5
// D10#     A10     PB6     PWM16       OC1B/0c4B/ADC13/PCINT6
// D11#             PB7     PWM8/16     0C0A/OC1C/#RTS/PCINT7
// D12      A11     PD6                 T1/#OC4D/ADC9
// D13#             PC7     PWM10       CLK0/OC4A
//
// A0       D18     PF7                 ADC7
// A1       D19     PF6                 ADC6
// A2       D20     PF5                 ADC5
// A3       D21     PF4                 ADC4
// A4       D22     PF1                 ADC1
// A5       D23     PF0                 ADC0
//
// New pins D14..D17 to map SPI port to digital pins
//
// MISO     D14     PB3                 MISO,PCINT3
// SCK      D15     PB1                 SCK,PCINT1
// MOSI     D16     PB2                 MOSI,PCINT2
// SS       D17     PB0                 RXLED,SS/PCINT0
//
// TXLED    D30     PD5                 XCK1
// RXLED    D17     PB0
// HWB              PE2                 HWB

There is an array inside the same file with name  digital_pin_to_timer_PGM that list the timers also.
const uint8_t PROGMEM digital_pin_to_timer_PGM[] = {
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    TIMER0B,        /* 3 */
    NOT_ON_TIMER,
    TIMER4A,        /* 5 */
    TIMER4D,        /* 6 */
    NOT_ON_TIMER,

    NOT_ON_TIMER,
    TIMER1A,        /* 9 */
    TIMER1B,        /* 10 */
    TIMER0A,        /* 11 */

    NOT_ON_TIMER,
    TIMER4A,        /* 13 */

    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,

    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
    NOT_ON_TIMER,
};


text:
Can I charge a 4.2 V battery with a 5 V adapter?
Can I charge a 4.2 V battery with a 5 V adapter without damaging the battery?

What type of battery is it, this will help you get a better answer.

Welcome to Arduino SE. I'm going to close this as off-topic because the question doesn't seem to involve Arduino at all. If it's supposed to be about Arduino then feel free to edit the question and we can re-open it.

This question would be a better match to the Stack Exchange Electrical Engineering group.
A 4.2V battery is very likely a LiIon or LiPo battery. I'll call it LiPO below as it's easier to type.
Most cellphones and many small electronic device use a single LiPo battery and use a 5V input to charge them. To do this they have internal control circuitry that ensures the battery's specifications are met. You can obtain suitable control electronics (in many cases as a single IC requiring maybe a few external resistors to configure it) and it makes great sense to use such a control circuit.
In an emergency you can use a 5V source to charge a 4.2V battery IF you know what you are doing and are able to ensure the battery specifications are adhered to. Failing to stay "in spec" may lead to the traditional LiPo "vent with flame" response, and even if there is no apparent damage the battery life can be greatly or very greatly reduced by out of spec treatment.
Key requirements are:

NEVER exceed 4.2V at battery terminals.
NEVER exceed Ichg_max = manufacturers max charging current.
This is usually the same value in mA as the battery capacity in mAh.
ie 1000 mA for a 1000 mAh battery
3300 mA for a 3300 mAh battery etc
When charging, EITHER stop charging when battery potential reaches 4.2V OR if you are able to hold the battery AT 4.2V, then stop charging when Ichg falls (under battery control) to say Ichgmax/4.
If Vbattery is under 3.0 V (which it NEVER should be) charge at no more than C/10 (eg  for a 1000 mAh cell) until Vbattery rises to >= 3.0V. If the battery will not rise to 3.0V under C/10 charge it is dead.

IF you can satisfy ALL these requirements at all times you can charge a LiPo or LiIon battery from 5V without a special charger.

No. You must use a charger properly designed for the battery; attempting to connect a Li-ion battery directly to a USB charger will damage the battery, possibly catastrophically.

https://www.youtube.com/watch?v=KWo4aDNnZT8

@Magic-Mouse The video is lots of fun, but does not address the issues involved. See my answer for details.

It does not address the issues, but it proves that LIPO is not a toy. And should be treated as if not.


text:
Yun as a Conventional Wireless Access Point
I want my YUN to act as a server in a client/server architecture so students can control their wifi robots via their desktops. I can plug the YUN directly into an ethernet port on our network and want to have robots communicate with it through a client/server architecture. Can somebody steer me in the right direction?

Check out this project, made by @Vadorequest the early days of the Yun: he hacked a car to control it via his smartphone. There's a nice video on youtube.

The video wasn't very informative, but it did provide proof of concept. If you have a link to the process this French gentleman used to make the car run, I would appreciate it. I understand the phone part, at least through Bluetooth. I am looking for an interface to Node.js to allow users to control the car. More detail would help.

I apologize. You did provide a link to the project. Thanks!


text:
Powering Arduino with Solar Panels
Clearly, an Arduino can be powered with solar panels.

What is the most optimal configuration?
Can you recharge and discharge at the same time?
Is LiPO the best battery cache technology, or is there something more durable out there, for fielded deployment?
What are the most economic, and reliable ways to do this?

Helpful pages: http://playground.arduino.cc/Main/IntWithHW-PwrSup, http://www.voltaicsystems.com/solar-arduino-guide.shtml

First of all you want to buy some solar panels or cells. Although they can be found on eBay for very cheap, but they not be as efficient as they say. I would say try to buy from a reputable dealer to see reviews on the product or trust that they work efficiently. Sparkfun datasheets are generally accurate and can be trusted.

Most optimal configuration: Do not use a regulator and some sort of step-up booster. Try the TPS61200 or TPS61202 chips. They will not regulate the voltage, they boost the voltage dynamically. This is much more efficient and therefore generates less heat. They work like a reverse voltage regulator, taking .3V to 5.5V and turning it into anywhere from 1.8V to 5V (xxx0) or 5V exactly (xxx2). Hack a USB B end and just connect the power lines to the Arduino.
Discharge/charge simultaneously: Yes, however I'm not sure how to. I believe that if you hook up a charger IC and a load, the voltage won't go through the battery, it will go through the path of least resistance. However, your battery wouldn't get charged then. This is outside the scope of the question, so I would recommend EE on how exactly to do this.
Is LiPO the best: Try a Lithium-Ion Battery. (A.K.A. Li-ion) According to this site:

Although the lithium-polymer battery is sleeker and thinner, lithium-ion batteries have a higher energy density and cost less to manufacture.

Therefore, it seems like Li-ion is the best choice for you. Note: Since you are dealing with very dense batteries that if overvolted can go up into flames [Note: please mute your speakers!], make sure to go with Sparkfun/Adafruit/etc...
Economic way: If you don't mind a big "homemade" solar panel, go this way. Buy through eBay or a similar site solar cells. They are small plates that are connected to create a solar panel. Try looking for "grade B" or similar solar cells that work fine, they just may have minor imperfections. It won't be as pretty, but you'll save some cash.

See this EE.SE post for more information. One cool thing that I saw was:

This is really cool. You can connect the Li-Ion voltage through an op-amp to generate a pulse wave, which can be picked up by your MPU to tell your bot to go charge –  Raaj Oct 18 '13 at 18:44

I'm not exactly sure how to do this, but it might be useful. I couldn't find anything online about it.

"Is LiPO the best: Try a Lithium-Ion Battery. (A.K.A. Li-ion) According to this site:" well my english not perfect But if I don't get it wrong, this site says the opposite. "Overall, lithium-polymer is slowly replacing lithium-ion in the smartphone industry due to its superior safety, form factor versatility, and weight attributes in high-end and mid-tier devices."

I would actually suggest LiFePo4 for anything DIY. Not only is it safer so one false move won't cause an inferno, but it will last two to four times as long at the CONST of a little extra size and weight.
Since you are just running an arduino, I would use only 1 single cell, and avoid cell balance woes.
I would use a boost regulator to step up the voltage from the cell to the required 5v.
To actually charge the cell, I would probably use a cheap ebay CC-CV charger board, and set the voltage for about 0.15V below the max for your lifepo(you only lose 10% of the energy but You make the battery last much longer), and set the current as appropriate for your panel and battery.
If your circuit is drawing power while the charger is charging, your circuit will take what it needs and any extra the charger puts out will go into the battery.
You might need a diode, to make the battery not discharge back through the charger.
Use a protection pcb like you can get from batteryspace, or better yet a protected lifepo with the pcb built it.
Remember to size your solar panel so that there is enough energy to keep the circuit running. Even with the protected cells overdischarge kills.
What I'd really like to do is design a lifepo4 charge control board that had all this in one unit since everyone seems to want it...


text:
How can I see if volume buttons of Apple earphones are pressed?
I need to be able to see if the volume controls and the middle button of Apple earphones are pressed.
I am using an Arduino Uno. I was thinking about using the analogRead function.
I tried connecting the ground of the audio jack to the ground of the Arduino, the micro of the audio jack to the analogPin 0 on the left and right of the audio jack to the 3.3 volt output of the Arduino, but the results of the analogRead are not really useful. They are constantly changing.

So guys i have this code that constantly gives a bunch of numbers. They are never constant.
int analogPin = 0;
int ledPinBlue = 8;
int ledPinRed = 9;

int val = 0;
int times = 0;
int clickTimes = 0;

void setup()
{
  pinMode(ledPinBlue, OUTPUT);
  pinMode(ledPinRed, OUTPUT);
  times = 0;
  Serial.begin(9600);
}

void loop()
{
  val = analogRead(analogPin);
  if (val == 0) {
times = times + 1;
  }
  else if (!val == 0) {
times = 0;
  }
  if (times == 500) {
times = 0;
digitalWrite(ledPinBlue, HIGH);   // sets the LED on
delay (500);
digitalWrite(ledPinBlue, LOW);    // sets the LED off
Serial.println("Click");
  }
}

When I press the button of the microphone (the middle button) of the apple earphones, the numbers change to a constant 0.
But when I press the volume buttons, nothing seems to change. Any ideas?

If you can't work out how the Apple ones work, would using Android ones be an option? They are much simpler and the information is public domain.

@MarkSmith android ones are good for me, i did not really know there is a differance between them. But how should I do it with android earphones?

MAYBE the buttons change greatly the voltage on the mic input.. try to map them; maybe (just a dumb example) the values you read when the button is not pressed vary between 0 and 300, while the button pressed is around 600... or maybe try with an oscilloscope: if the voltage can go below zero maybe you are just losing some data when sampling only positive values..

Here is an update. I did some test and i will soon set up a version of something I found while testing. It works with the middle button but not with the volume buttons.

Here is an article that explains the inner working of the Apple headphones:
http://tinymicros.com/wiki/Apple_iPod_Remote_Protocol

Since you say that an Android headset would be an alternative....
Google have published the specs for how headset controls work on Android: in short, (up to) four different values of resistor connected between mic and gnd represent the four buttons.
If you just need to read the controls, use a potential divider between Vcc and ground, and read the mid point with an analogue input to tell you which (if any) key is being pressed.

simulate this circuit – Schematic created using CircuitLab
(Wow, that's big... Dunno how to make it smaller :-) )

Could you give me a picture of how to connect the pins to the arduino? Sorry, i dont really have much knowledge of electronix. I just know the basics.

If that schematic doesn't get you started, i I think you're going to struggle to be honest. Is there something in particular about that picture which doesn't make sense which I can explain?

Have you tried searching Apple Earphones Schematic or something similar? You probably won't find a schematic, at least not from Apple, but I did find this discussion of someone's attempt to figure out what the buttons do, on some kind of Apple earphones or other (you didn't say which ones you have). There must be others who have also experimented with this.

I am looking for so long now. I really cant find anything usefull

But i must be possible i think, smartphones and such can detect when the buttons are pressed so why shouldnt it work with a arduino ;)

Wasn't the article I linked to a good starting point?

Its helpful but they want a button to simulate the controls. I just need to be able to see when the buttons are pressed with an arduino...

Can you check my answer?

Post #5 in the thread I linked has some ideas about detecting the way those buttons affect the circuit characteristics as measured from the phone plug. It will probably take a little bit of support circuitry and some software to assist the detection. Since Apple doesn't publish specs for things like this, it will be a small R&D project to confirm the speculation about the buttons and design a simple circuit or two to do the detection. Measuring a voltage or resistance change might get you one button; getting all three will be a little more work.