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 :)

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.

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.


text:
C Serial Communication Code is unreliable
This going to be a difficult to debug problem but I hope some ppl here have C knowledge and idea what's going on. Given an arduino nano which is controlled by a C program from WRT54G.
Here is the relevant part of the arduino code:
void setup() {
  Serial.begin(9600);
}

 int integerValue=0;

                              // Max value is 65535
char incomingByte;

void loop() {
  if (Serial.available() > 0) {   // something came across serial
    integerValue = 0;         // throw away previous integerValue
    while(1) {            // force into a loop until 'n' is received
      incomingByte = Serial.read();
      if (incomingByte == '\n') break;   // exit the while(1), we're done receiving
      if (incomingByte == -1) continue;  // if no characters are in the buffer read() returns -1
      integerValue *= 10;  // shift left 1 decimal place
      // convert ASCII to integer, add, and shift left 1 decimal place
      integerValue = ((incomingByte - 48) + integerValue);

    }
   Serial.print("Command: ");
   Serial.println(integerValue);

  }
}

Pretty straight forward (it converts serial received ascii chars to numeric format), arduino receives a simple integer and it runs a function. For example 1-> turn on relay1. This work's reliably for sure because I can just do:
echo "1" > /dev/tts/1

from the terminal.
Now here is the relevant part of the C code:
    int serialport_read_until(int fd, char* buf, char until, int buf_max, int timeout)
    {
        char b[1];  // read expects an array, so we give it a 1-byte array
        int i=0;
        do {
            int n = read(fd, b, 1);  // read a char at a time
            if( n==-1) return -1;    // couldn't read
            if( n==0 ) {
                usleep( 1 * 1000 );  // wait 1 msec try again
                timeout--;
                continue;
            }
    #ifdef SERIALPORTDEBUG
            printf("serialport_read_until: i=%d, n=%d b='%c'\n",i,n,b[0]); // debug
    #endif
            buf[i] = b[0];
            i++;
        } while( b[0] != until && i < buf_max && timeout>0 );

        buf[i] = 0;  // null terminate the string
        return 0;
    }

    /* Only use integer commands */
    int serialport_write(int fd, int comm_no)
    {
        char command[6];

        sprintf(command,"%d\n",comm_no);
        printf("Sending Command:%s",command);

        int len = strlen(command);
        int n = write(fd, command, len);
        if( n!=len )
            return -1;
        return 0;
    }

void *ardu_handler(void *fdfd)
{
  int fd = *(int*)fdfd;
  char buf[256];
  char getback[10];

  while (1)
   {
     memset(buf, 0, sizeof(buf));
     serialport_read_until(fd, buf, '\n', 256, 5);
     fprintf(stderr, "Received: %s\n", buf);
   }
}

Then a C thread will be started with the ardu_handler which in this case doesn't do anything else just print's back the response from the ardu.
What's happening is when I send a command I start getting back infinite amount of commands (up until I close the C app and start it again) and to make it worse it is even inconsistent.
For example:
Command: 62143
Command: 7891
Command: 3216
Command: 11287
...
runs forever.

What I asking myself is whether these responses coming out from the arduino or they are just coming out from the bogous C program...
It's not possible to connect to see what's coming out on the serial port unfortunately until this program holds the port open.
Although I run the C code on mips this was doing the same thing back on x86 PC with an arduino uno (sometimes it is stable but then it falls into this unstable state and floods the serial port). It was unreliable and I would like to make it reliable.

Change the type of incomingByte to int. See https://www.arduino.cc/en/Serial/read

Reading on, the 2nd code block contains a buffer overflow where char b[1]; is defined, but you're trying to null-terminate a string. Where is buf_max defined?

I assume the results you posted above are the stderr output, though I can't see the Received:  part of it.

// Max value is 65535 - that isn't true.

I recommend you change the type of incomingByte to int, like was advised in the comments. Also, your null-termination is occurring past the end of buf; change the condition in the while statement to i < buf_max - 1, so that one byte is left for the null. Also use parentheses to separate those conditions, in the unlikely event there's some issue of precedence.

source: Stack Exchange

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

sort: votes


text:
Cannot find crtatmega328p
I have just installed the arduino IDE on my gentoo laptop. I then installed the toolchain with the following command:
crossdev -s4 avr

This does a stage 4 install of the toolchain, with all its dependecies etc.
I am following a tutorial, with my arduino uno, which I am assuming is using the Amtel ATmega328 chipset. This tutorial is simply going to turn an led on and off.
I click the verify button and I get the following errors:
/usr/libexec/gcc/avr/ld: cannot find crtatmega328p.o: No such file or directory

/usr/libexec/gcc/avr/ld: cannot find -latmega328p

collect2: error: ld returned 1 exit status

I downloaded the source files "avr-libc" compiled them and noticed inside the directory
/avr-libc-1.8.1/avr/lib/avr5/atmega328p

That the compiled module is named crtm328p.o which is available on my pc under the directory:
/usr/avr/lib/

I dont understand what is wrong and why this is not working. The only posts relating to missing files are over 5 years old and those solutions are not working.

The IDE should already have the toolchain in it - no need to compile and install anything else.

@Majenko this is not the case when you install it on gentoo.

It's in the tar file - that has nothing to do with the OS you are using it on. How are you trying to install it?!

I installed it with "emerge -av arduino" This installs the package "dev-embedded/arduino-1.0.5-r1::gentoo" which is the java version. Arduino IDE. It then tells me during the install that avr is missing and i have to install it by entering crossdev -s4 avr on the command line

1.0.5 is ancient. You want 1.6.7 from https://www.arduino.cc/en/Main/Software

mmm... let me update it.. i know it install avr-libc version 1.8.1

Just download the tar,xz file, extract it, then run the arduino program from within it - that will give you everything you need without any more installation needed.

I do not use Gentoo, but I can tell you how things work on Ubuntu 14.04,
which also installs Arduino 1.0.5. I assume Gentoo should not be that
different... The dependency tree is like this:

The package named "arduino", version 1.0.5, contains the IDE. It
depends on Java and on arduino-core.
arduino-core, version 1.0.5 also, has the Arduino core libraries. It
depends on gcc-avr, avrdude and avr-libc.
gcc-avr comes as version 4.8, avr-libc is version 1.8.0.

When you compile a program for an Uno, on the link stage avr-g++ gets
called, and it is asked to link your object files with libcore.a (the
Arduino core) and -lm (the math library). avr-g++ in turn calls the
linker (collect2) and asks it to link together
/usr/lib/avr/lib/avr5/crtm328p.o (the C runtime), your object files,
libcore.a, -lgcc (the GCC support libraries), -lm and -lc (avr-libc).
Notice that there is no crtatmega328p.o, it's called crtm328p.o instead.
And there is no -latmega328p.
For diagnosing your problem, you can set an IDE preference so that it
shows you the exact command lines it runs for compiling your program.
You can then copy and paste the last command (link stage) on a terminal.
If you add the -v option (meaning “verbose”), you will see what gcc is
asking the linker to put together.
You may be able to fix your problem with a simple symlink from
crtm328p.o to crtm328p.o. If you are using vanilla Gentoo packages, you
should then file a bug to the packager. On Ubuntu, you type
sudo apt-get install arduino and it just works.

FYI: Using sudo apt-get install arduino gets you an ancient version of Arduino IDE, it is much better idea to download the latest from Arduino's site.

@Avamander: I tried that, but the install is a mess: it completely ignores all the standard conventions of a Linux file system. I am a lot happier with an ancient core (I do not use the IDE) that is at least cleanly installed.

What do you mean by standard conventions of a Linux file system? The install is fairly clean, it keeps it's stuff where the IDE was unpacked and only uses the Sketchbook what you've set. It's similar to Steam, not the most elegant but it works and you don't have to compile anything yourself and the developers have a standard set of libraries.

I mean mostly the Filesystem Hierarchy Standard. After unpacking the IDE, I did a regular install of the AVR development toolchain, and ended up with lots of duplicates. This is the Arduino package completely ignoring good practices of putting stuff in the right place and correctly identifying its dependencies.

Uhh, the toolchains are bundled with the IDE so that there would be no need to install dependencies, plus many things are not redistributable through a repository due to licence issues. It ain't ignoring, it can't do what you hope. There are issues related to updating the package open on Github.

@Avamander: arduino-core is just the Arduino libraries, doc and examples. The toolchain is not bundled, it's listed as dependencies.

My mistake. I fixed it.

But still, it's the best currently possible.

I had the same error, but I did everything as says in arduino wiki: https://wiki.gentoo.org/wiki/Arduino#Install_the_toolchain_using_crossdev
and solved it, after read this discussion: https://wiki.gentoo.org/wiki/Talk:Arduino
helped: build the avr toolchain without '--stable' part of crossdev command line :
USE="-openmp -hardened -sanitize -vtv" crossdev -s4 --portage --verbose --target avr

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


text:
Amplification of microphone circuit
I am getting constant values and I need to know the amplification of the circuit. I believe that amplification = R8/R6 though I am not sure.

You are mostly correct Diana.  The gain of an OP-Amp would normally be R8 divided by R6.
However, what needs to be recognized is that in your circuit, the resistance of R3 and the microphone get entangled with your R6.
The resistance (impedance of your microphone) is in series with R6. R3 also comes into play, but I will ignore it here (subject of another question on amplifiers).
So, since R of microphone is in series with your R6, your gain (amplification) will be slightly less than you have calculated.
The old 741 Op-Amp won't work very well (probably not at all) with a single ended power supply of 5 volts.  Although you have done a good job of biasing the non-inverting input (+) at 2.5 volts.
The 741 output can't get near the +5 volts, nor can it get near ground.  Try a better Op-Amp such as MCP6002. Look at how the output of the MCP6002 can approach the rails (your power supply and ground).

Thank you ,altough this is not my circuit design entirely.I have assumed that the microphone has a high impedance so I  got the amplification as R8/(R6+R3).You are right the 741 does not behave properly.


text:
Why does my Arduino freezes when i turn a servo
I have a Servo Motor and an Arduino Uno.
I used the Arduino to run a servo motor. The code was very simple. It was to just Turn it 90 Deg Anti-Clockwise when a switch is pressed and Turn back to its original position (90 Deg Clockwise).
The servo had 3 pins.
 1. V+
 2. Ground
 3. Data
I connected the V+ to the Arduino's 5v Output. And the Ground to the Arduino's GND pin. I connected the Data to Digital Pin 3.
When ever this script runs, The servo turns a little and then stops. It stops because the arduino froze and It wont do anything. I pressed the Reset button and it does nothing. I plugged off the Servo and the Power Supply and replugged the Power and it works.
The power source was a battery pack with 4x 1.5 Volts batteries in it. Maybe there was a problem with this?
Do anyone know what might be the problem here? Any Answer will be Appriciated. Thanks.

Can we get a schematic and your code? Might be something in the code.

Also, does this occur every time you run it? Is the problem reoccurring?

Servo maybe gets at start too high current, which causes a drop in voltage at 5V and freezing microcontroller?

Which servo motor are you using? Do you have the spec, or at least an exact model name?

@JoshJobin It does happen everytime I tested it (about 5 times)

@DmitryGrigoryev It has been awhile. I will try and post it

1.5V battery cells have little current capacity; try running off the same code and arrangement using a bench supply.

Possible duplicate of Why does connecting a high-current device to my digital circuit cause weird behavior?

You said that you were using 4x 1.5v batteries. That would make a total of 6 volts. The current that those batteries can supply is also little.
The Recommended Input Range is 7-12 volts. And the Limit is 6-20 volts.
You were supplying it with 6 Volts which is at the very limit of the Input Voltage Range. When the motor runs, the Voltage might have dropped and made the arduino freeze.
The fix is to supply the arduino with another source such as a benchtop supply that can supply more than 8 volts.

Not necessarily wrong, but 99% likely only part of the issue.

Connect your servo V+ to your battery stack and the servo data input to your Arduino. I suspect that the servo is causing the Arduino to reset when the servo draws too much current through the Arduino's voltage supply circuitry.

My first response would be a brown out reset. Because of the load the voltage will sag and drop below a certain voltage so the microcontroller will reset. Try to put a big buffer capacitor on the power supply.
Other possible cause could be inductive spiking, but I dont expect this to be the cause of your problem.


text:
Arduino thermometer and humidity display with 7 segment LED display
I want to use an Arduino Uno, a seven segment LED display (four digits) and the SevSeg library, to see temperature and humidity (alternatively).
First of all I try this code:
  #define COMMON_ANODE 1
  #define COMMON_CATODE 0
  #include "DHT.h"
  #define DHTPIN A5     // pin analogico che legge i dati
  #define DHTTYPE DHT22   // DHT 22  (AM2302)
  #include "SevSeg.h"

  // Crea un'istanza dell'oggetto
  SevSeg sevseg;
  DHT dht(DHTPIN, DHTTYPE);
  unsigned long timer; // the timer
  unsigned long INTERVAL = 5000; // the repeat interval (30 seconds)

  int segA = 6;   // Undicesimo PIN del display 7Segment x 4
  int segB = 2;   // Settimo PIN del display 7Segment x 4
  int segC = 10;  // Quarto PIN del display 7Segment x 4
  int segD = 12;  // Secondo PIN del display 7Segment x 4
  int segE = 13;  // Primo PIN del display 7Segment x 4
  int segF = 5;   // Decimo PIN del display 7Segment x 4
  int segG = 9;   // Quinto PIN del display 7Segment x 4
  int segDP = 11; // Terzo PIN del display 7Segment x 4

  int digit1 = 7; // Dodicesimo PIN - PWM che Accende il primo digit
  int digit2 = 4; // Nono PIN - PWM che Accende il secondo digit
  int digit3 = 3; // Ottavo PIN - PWM che Accende il terzo digit
  int digit4 = 8; // Sesto PIN - PWM che Accende il quarto digit

  void setup()
  {
    dht.begin();
    int numberOfDigits = 4; //Numero di cifre del display

    // Inizializzo i PIN
    sevseg.Begin(COMMON_CATODE,digit1,digit2,digit3,digit4,segA,segB,segC,segD,segE,segF,segG,segDP);
    // Imposto la luminosità (valore da 0 a 100)
    sevseg.Brightness(90);
    timer = millis(); // start timer
  }

  void loop()
  {
    if ((millis()-timer) > INTERVAL) {
      // Reset the timer and get/display the current temperature
      timer += INTERVAL;
      // Leggo dal sensore la temperatura
      float t = dht.readTemperature();
      float h = dht.readHumidity();
      //La converto in un numero intero a 4 cifre
      int a=t*100;
      sevseg.NewNum(a,2);
    }
        sevseg.PrintOutput();
  }

And it works very well!
But I cant see temperature (first) AND humidity (after) and again temperature (first) AND humidity (after)...
I have tried many ways but... nothing!! Can you help me?

You need to maintain a state which tells your program whether you are displaying the temperature or the humidity.  Every time the timer expires you need to change from one state to the other, and then display the relevant value depending on what the state is.
Something like:
bool displaying = false; // false = temperature, true = humidity

void loop() {
    if ((millis()-timer) >= INTERVAL) {
        timer = millis();
        display = !display; // Switch between display values

        if (display) {
            float h = dht.readHumidity();
            sevseg.NewNum(h * 100, 2);
        } else {
            float t = dht.readTemperature();
            sevseg.NewNum(t * 100, 2);
        }
    }
    sevseg.PrintOutput();
}

A very interesting way! After work , about at 8 PM :-) i try your suggest!

All you are implementing is a very very simple Finite State Machine (one with just two states). You might find this interesting reading: http://hacking.majenko.co.uk/finite-state-machine

Hi! thx for your suggestion! I try it five minutes ago and it's work. A nice and simple way to solve the problem, but if I want use this way for 3 value, ie temperature in celsius degree, humidity and temperature in kelvin degree, can I use the "booelan" way or i must use the "switch-case" costruct (like in the article)?

The boolean can only store two states - true or false - and so it can only be used to select between two items. For more you need to change the boolean into a different type that can store more values and then select between them. Say an "int" and use the values 0, 1 and 2. So yes, like the article.

@MicheleBorsaro If this answer solved your problem you should accept it. That is expected behavior on this site. (Accept the first/best answer that solves your problem. Once you have the reputation, you should also think about up-voting helpful answers, although that is optional.)


text:
Print to console
I am trying to get the string ("Enter an Integer : ") to print to the serial, then have the user enter a string of numbers which is then converted to an array of chars then ints.
The problem is the string will not display on the serial monitor when opened, and when the numbers are entered by the user, and  the conversion is done I need the string to be displayed again. So when the user inputs a number and presses enter it should be the end of that conversion, and prompt a new one.
Code below:
int convert(void) {
  while (Serial.available() > 0) {
    char ch = Serial.read();
    if (ch >= '0' && ch <= '9' || ch == '-') {
      // Collect digits, only works if minus is first.
      strValue[index] = ch;
      index++;
    } else {
      strValue[index] = '\0';
      blinkRate = atoi(strValue);
      Serial.println(blinkRate);
      Serial.print("Enter integer : ");
      index = 0;
    }
  }
}

What does the serial monitor display when you run this code and type a number?

The number does not register until I enter a letter, which is one problem. I would like the number to register when the user presses enter.

Why are you checking for '\0' instead of '\n'?

The biggest problem I see is that when your convert() function is called, if the user hasn't already typed something, then Serial.available() is going to return 0 (zero) and the while statement will never get executed.
Second, your print statement that prints the prompt to the console will only get called after you have already read a string from the user.
Third, you're trying to reinvent the wheel by writing your own function to read a string from the serial input. I suggest you use ReadStringUntil().

The problem is, the Arduino serial monitor is way too crude to understand what you're trying to do.  Using a real terminal emulator (Teraterm for example) will probably give you better results (but you will also need to echo back the characters typed so you can see what you're typing) - either that or don't try and do things "in-line" like a prompt, instead print a message including the line feed (i.e., use println() instead of print()) so that the serial monitor can output a new line with the message text in it.

It seems likely to me that you have not configured your serial monitor to send a newline. See the bottom line of the Serial Monitor.

If it is set to "no line ending" then when you send the line, you get the line only and no newline.


text:
Field Programming a Arduino with another Arduino with SD card over RX/TX lines
I am not sure if this question has been asked before but here's what I wanted to do.
I have a Arduino Nano, which I need to update with a new sketch. The plan is to be able to use another Arduino (maybe a Nano again), with an SD card reader and a sketch loaded as HEX file on it. Then connect both using a 4 pin RX/TX/5V/GND and upload the sketch from the transmitter to the receiver. Is it possible?
I am not sure how to do this; I know I can use one Arduino as an ISP to update other, but I am thinking of streaming the hex file to the other. Has anyone done this, any hints would be extremely helpful.

You can find some great info here: http://forum.arduino.cc/index.php?topic=351358.0 and http://www.gammon.com.au/forum/?id=11638

There's actually a library for that as well! See here and here.

See What happens when code is uploaded using the bootloader?
There is a graphic on that page (reproduced below) which shows the general idea of what happens when you program using Tx/Rx after reset.

You could delve into the specs for the STK500 protocol (see linked page) and make your second Arduino follow that, to program from the SD card file.


text:
Store String using F() Macro
I'm new to the Arduino and do not quite understand the F() macro yet.
In my code, I have a String, and as I want to transfer it via WebServer, I need to write it to the answer.
Somehow I need to convert the String, to fit it into the fastrprintln() function.
String weather_json = getWeatherData();
char weather[2048];
weather_json.toCharArray(weather,2048);
client.fastrprintln(F(weather));

Do you have any idea for me?

What do you mean by "I need to write it to the answer."? Is that a typo?

The F() macro is for literals (eg. F("foo") ) not variables.

“I need to convert the String, to fit it into the fastrprintln() function.” No, you don't: client.println(getWeatherData());

The Arduino core macro F() takes a string literal and forces the compiler to put it in program memory. This reduces the amount of SRAM needed as the string is not copied to a data memory buffer. Special functions are required to access the data stored in program memory. The Arduino core hides a lot of the typical usages such as:
Serial.println(F("Hello world"));

Further details of the low level access program memory access may be found in the AVR GCC libc documentation. The F() macro is defined as:
class __FlashStringHelper;
#define F(string_literal) (reinterpret_cast<const __FlashStringHelper*>(PSTR(string_literal)))

The FlashStringHelper class is used to help the compiler recognize this type of string literal when passed to Arduino functions. Below are some examples:
// String constructor with program memory string literal
String::String(const __FlashStringHelper *str);

// Print (Serial, etc) of program memory string literal
size_t Print::print(const __FlashStringHelper *);
size_t Print::println(const __FlashStringHelper *);

You should not use the Arduino core F() macro with anything other than a string literal.

I was having an issue with my program locking up so after reading your answer I added the F() macro to my string literals and that was literally all it took to resolve this issue. I must be lower on memory than I had previously imagined.. Anyway, thanks for introducing me to this lock-up saving macro.


text:
What is the Maximum Current an Arduino can Supply?
I was wondering how much my Arduino I/O pin can output when it is set at Output and is at High.
I am using an Arduino Uno R3.
Thanks in Advanced.

@brhans Alright, Gonna move it there

@brhans but it seems to have an answer already. So i think im just gonna keep it here

Possible duplicate of How much current can I draw from the Arduino's pins?

40.0mA.
The Arduino UNO Digital IO pins are connected directly to the IO pins on the ATMEGA328P processor.
From page 299 of the data sheet for that processor...

Note that there is also a total current limit for all output pins combined, and that the voltage starts to drop as the current goes up.

You should probably note that it's never a good idea to go anywhere near the "Absolute Maximum Ratings". Perhaps include the notice that's referred to by the asterisk on that page in the datasheet.


text:
Why can't the new Arduino IDE 1.6.7 compile extern "C"?
Consider:

I having a problem in compiling in extern "C" code in the Arduino IDE 1.6.7 which I don't have on version 1.6.5.
The error is:

error: conflicts with new declaration with 'C' linkage

It is complaining about the lines containing loop() and start_timer(void);.
This is my code:
#ifdef __cplusplus
extern "C" {
#endif

void start_timer(void);

#ifdef __cplusplus
}
#endif

void start_timer(void)
{
    Serial.println("2");
    Serial.begin(9600);
    delay(2000);
}

void setup()
{
    start_timer();
    Serial.println("4");
}

void loop()
{
    Serial.println("1");
    delay(2000);
}

Please edit the code and provide the error/warning from the compiler.

I can't reproduce that. Please post your full code as Mikael Patel suggested, and the error message. That is: a Minimal, Complete, and Verifiable example

I already updated my previous post

Why do you need to declare C linkage for a symbol directly in your script?

I can't reproduce your problem still. See this:

However if you are having problems (and frankly I expected you to) then you should read this:
How to avoid the quirks of the IDE sketch file pre-preprocessing
How the IDE organizes things

I can reproduce your problem in IDE 1.6.5 (not 1.6.7). The code generated by the IDE preprocessor is this:
#line 1 "sketch_jan11a.ino"
#ifdef __cplusplus
#include "Arduino.h"
void start_timer(void);
void setup();
void loop();
#line 2
extern "C" {
#endif

void start_timer(void);

#ifdef __cplusplus
}
#endif

void start_timer(void)
{
    Serial.println("2");
    Serial.begin(9600);
    delay(2000);
}

void setup()
{
    start_timer();
    Serial.println("4");
}

void loop()
{
    Serial.println("1");
    delay(2000);
}

You can see that in the automatic function prototype generation that the IDE "helpfully" generates for you, it puts the prototype for start_timer outside the extern "C" declaration. Thus one function prototype has a declaration in C++ format, and the other in C format.
Why are you even doing this? I presume this is a small example of a larger problem.
If you follow the suggestions in my link How to avoid the quirks of the IDE sketch file pre-preprocessing - did you read that? - the problem goes away, because .cpp files in IDE tabs are not subjected to this extra processing.

Please refer to the about image that i just attached for the issue that i'm facing. If i put the whole "start_timer()" function into the extern "C" then i will be working fine.

Which operating system are you using?

See amended reply for more info.

The compiler is telling you that there is a conflict between the two definitions of start_timer().
The normal usage of extern "C" is in a header file for functions that are accessed from both C and C++. This actually has to do with how C++ handles names and overloading. Using extern "C" will use normal C name handling and C++ name mangling is turned off (together with overloading, etc).
Please see https://stackoverflow.com/questions/31349865/compiler-error-for-conflicting-variable-declarations-conflicts-with-new-declar.


text:
Modbus master arduino code is throwing weird errors on upload
I am using the following https://code.google.com/p/simple-modbus/ arduino master library code. In order to communicate with my industrial drive.
All seems right but I am getting some weird errors. I am using the arduino master code as it is. With just the difference in modbus_construct.
Here is the error I am getting
 This report would have more information with
 "Show verbose output during compilation"

enabled in File > Preferences.
Arduino: 1.0.6 (Windows 7), Board: "Arduino Uno"
In file included from SimpleModbusMasterArduino.ino:29:

C:\Program Files\Arduino\hardware\arduino\cores\arduino/Arduino.h:131: error: expected ',' or '...' before numeric constant
In file included from C:\Program Files\Arduino\hardware\arduino\cores\arduino/HardwareSerial.h:28,
                 from C:\Program Files\Arduino\hardware\arduino\cores\arduino/Arduino.h:215,
                 from SimpleModbusMasterArduino.ino:29:
C:\Program Files\Arduino\hardware\arduino\cores\arduino/Stream.h:57: error: expected ',' or '...' before numeric constant
In file included from SimpleModbusMasterArduino.ino:29:
C:\Program Files\Arduino\hardware\arduino\cores\arduino/Arduino.h:222: error: expected ',' or '...' before numeric constant
SimpleModbusMasterArduino:37: error: 'Packet' does not name a type
SimpleModbusMasterArduino.ino: In function 'void setup()':
SimpleModbusMasterArduino:45: error: 'packets' was not declared in this scope
SimpleModbusMasterArduino:45: error: 'READ_HOLDING_REGISTERS' was not declared in this scope
SimpleModbusMasterArduino:45: error: 'modbus_construct' was not declared in this scope

SimpleModbusMasterArduino:49: error: 'modbus_configure' was not declared in this scope SimpleModbusMasterArduino.ino: In function 'void loop()': SimpleModbusMasterArduino:56: error: 'modbus_update' was not declared in this scope
Here is my code:
#include <SimpleModbusMaster.h>

/*
   The example will use packet1 to read a register from address 0 (the adc ch0 value)
   from the arduino slave (id=1). It will then use this value to adjust the brightness
   of an led on pin 9 using PWM.
   It will then use packet2 to write a register (its own adc ch0 value) to address 1
   on the arduino slave (id=1) adjusting the brightness of an led on pin 9 using PWM.
*/

//////////////////// Port information ///////////////////
#define baud 115200
#define timeout 1000
#define polling 200 // the scan rate
#define retry_count 10

// used to toggle the receive/transmit pin on the driver
#define TxEnablePin 2
#define LED 13

// The total amount of available memory on the master to store data
#define TOTAL_NO_OF_REGISTERS 8
#define TOTAL_NO_OF_CONSTANTS 1

// This is the easiest way to create new packets
// Add as many as you want. TOTAL_NO_OF_PACKETS
// is automatically updated.
enum
{
  PACKET1,
  //PACKET2,
  TOTAL_NO_OF_PACKETS // leave this last entry
};

// Create an array of Packets to be configured
Packet packets[TOTAL_NO_OF_PACKETS];

// Masters register array
unsigned int regs[TOTAL_NO_OF_REGISTERS];

void setup()
{
  // Initialize each packet
  modbus_construct(&packets[PACKET1], 1, READ_HOLDING_REGISTERS, 0x3000, 8, 0);
  //modbus_construct(&packets[PACKET2], 2, READ_HOLDING_REGISTERS, 0x3000, 8, 16);

  // Initialize the Modbus Finite State Machine
  modbus_configure(&Serial, baud, SERIAL_8N2, timeout, polling, retry_count, TxEnablePin, packets, TOTAL_NO_OF_PACKETS, regs);

  pinMode(LED, OUTPUT);
}

void loop()
{
  modbus_update();
  Serial.println(regs[0]);
  //regs[0] = analogRead(0); // update data to be written to arduino slave

  //analogWrite(LED, regs[0]>>2); // constrain adc value from the arduino slave to 255
}

Your issue is that you define constants, such as timeout, which are widely used in Arduino library as parameter names. After preprocessing your definitions, correct code in "Arduino.h" such as
unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout);

becomes
unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long 1000);

No wonder the latter line fails to compile.
You will need to find unique names for your defines, or use constant variables instead.


text:
W5100 Ethernet shield DHCP fails with a Switch
we are using Arduino W5100 Ethernet shield. The code is to try DHCP first and if that fails, then try the static IP. we do the Ethernet Initialization and stop every time.  The library is Arduino Ethernet library.

when we try with a wireless router, everything works and we are able to contact our web server.
Now the wireless router is connected to a switch.
switch <======> router <=====> W5100

if we try to send data using the switch directly, DHCP fails, whereas a laptop using the same cable works.
Question is, even Arduino Library has DHCP functionality, why should a laptop work where the shield is failing? The network and topology and rules should be same for both the laptop and W5100 shield. Anything we can do to debug this issue more?
Edit1 : -  Switch which we are using is L3 in nature.
Below is the code which we are using at present.
    while(1) {

        KDEBUG("wait 10 seconds...\r\n");
        // wait 10 seconds
        for(loop = 10; loop > 0 ; loop--) {
            wait_millis(1000);
        }

        KDEBUG("Try transmitting data on ethernet...\r\n");
        transmit_data();

    }

    return 0 ;

}

void wait_millis(uint16_t num) {

    for(; num > 0 ; num-- ) {
        _delay_ms(1) ;
    }

}

// transmit data using Ethernet
static uint8_t transmit_data() {

    char request[256];
    uint8_t status = 0  ;

    // reset counter
    counter = (counter > 254) ? 0 : counter ;

    memset(&request[0], 0 , sizeof(request));
    memset(&bencode[0], 0 , sizeof(bencode));

    wait_millis(5000);
    // try DHCP
    if (Ethernet.begin(mac_address) == 0) {
        KDEBUG("Failed to configure Ethernet using DHCP \r\n");
        // use static IP. no return code.
        Ethernet.begin(mac_address, ip_address);

    } else {
        KDEBUG(" Got lease from DHCP \r\n");
    }

    // wait for ethernet to initialize:
    wait_millis(5000);

    // we got a connection?
    status = client.connect(server, port) ;
    KDEBUGF("ethernet client  status= %d \r\n", status);
    if(!status) {
        goto quit ;
    }

        KDEBUG("connected \n");
    // create an HTTP request
    strcat(request, "GET /api/gl868.php?data=");
    strcat(request,bencode);
    // 12 chars
    strcat(request," HTTP/1.1 \r\n");
    // 25 chars
    strcat(request,"Host: ");
    strcat(request,server);
    strcat(request," \r\n");

    // send GET request
    client.println(request);
    _delay_ms(1);
    client.println() ;

    wait_millis(1000);
    client.stop();
    wait_millis(1000);

    if(client.connected()) {
        client.stop();
    }

    return 1 ;

quit:

    wait_millis(100);
    if(client.connected()) {
        client.stop();
    }

    return 0 ;

}

What Arduino board?

@MikaelPatel - We are using Arduino Mega.

I have exactly the same problem with an arduino uno - it works fine plugged in to the router but not when plugged in via a switch (in fairness, a chain of switches) Fixed IP is fine and laptop DHCP is fine, it's just DHCP on the ethercard that is an issue.  I suspect that the ethercard.h library has a bug but I'm not good enough to find it. srj0408 did you ever find a solution?

A certain way to debug this is to use tcpdump to capture network packets from both Arduino and your laptop and check the differences. I would start by looking for DHCPDISCOVER packet that Arduino should be sending.
A simpler way would be to check DHCP server logs to see how the communication looks like from server's perspective. Here, you should be looking for lines which have the MAC address of your Arduino shield. The success of this approach will depend of the verbosity of the DHCP server you're using.

If I understand your connection...

Device over wifi to router works.
Wired, via a switch to router does not?

DHCP is clearly switched on for WLAN, is it switched on for LAN?
Personally I always use fixed IP for such projects, with a default value that can be reset so that I can always find my device. I change the IP (and/or MAC) via a serial monitor.

The poster specifically says that a laptop connected via the same cable  works (which I assume means "gets a configuration via DHCP").

Even though i am using a static or fix IP for my ethernet shield, it is unable to send data to server. Of that, our switch is L3 in nature.


text:
Power Supply Problem with Arduino Yún: Using a long USB cable
I want to use an Arduino Yún as a kind of outdoor weather station. I want to supply the power for the Yún with a 5V USB-Charger. Using a normal USB cable everything works fine. But as the weather station shall be far from the next power socket, I made the USB cable about 10 meters longer. Now the Yún does not power up any more.
Has anybody an idea why?
Should I use a 12 V power supply and a 7805 power converter instead?

Dmitry's answer is generally correct but I disagree with the notion that “voltage drop” is the problem, unless you used extremely thin wire in the extension.   You don't say how you made the USB cable longer.  If your experience with building cables is limited, it's more likely that one or more of the connections is open or wrong than that too much voltage drop is occurring.

After failing with a rather thin cable (a former telephone cable soldered into a normal USB cable) I tried a much thicker cable, but the Yun would not start either. As I think I am rather experienced with soldering, I do not think the connections are the problem.
Does it make sense to measure the resistance of the cable?
So I will try the power converter solution within the next days.

The USB specification limits the length of a cable between two devices to 5 meters. When you make a longer cable, you're going out of spec, which means it is not guaranteed to work anymore.
Since you're only supplying power, the issue is (as you have guessed) the voltage drop in the cable. However, the voltage drop will depend on how much current Arduino is consuming at any given moment. Supplying it with a higher voltage without a converter is dangerous, because it will lead to overvoltage you won't be able to control.
I'd suggest trying better cables first: thicker and stiffer cables have thicker wires, and may have less voltage drop. You can also make your own cable (provided you can solder) using only two thick wires for power.
The ultimate solution, like you said yourself, is to deliver higher voltage over the wire (12V would do) and install a power converted (12V to 5V) near your Arduino. That way, the voltage drop in 5V line will be small, and the voltage drop in 10m 12V line will be compensated by the converter. Actually, the intermediate voltage may be higher: you can simply drop a mains line (220V or whatever you have) to your weather station and place the same USB charger near the Arduino.

It works now. I replaced a 12 V power supply and added a 12V / 5V DC converter just before the Arduino Yun.  The first try with a change of the cables with a higher diameter had no effect.

@bhneuner I'm glad it worked out, and thanks for taking time to report back!

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


text:
Module and library for self healing large sensor network
I have to build a wireless sensor network with arduinos on my project. It does not need to be a mesh network, but it needs to have self healing capabilities.
I would like to use something cheaper than XBees. I tried the NRF24L01 with maniacbug's, TMRh20's and MySensors' libraries. However they aren't solving the problem and I'm wasting a ton of time trying to figure out how to make them work.
Another thing, I need a lot of repeater nodes between the base and the sensors because the office is 2 km far from the monitoring area and some of these libraries have a limitation of 5 level deep network, so I'd have max 4 repeaters between the base and sensor, which is bad.
And the last, my project is going to be fine with 15 sensors for now, but it'll have 500-1000 nodes in a couple of months and most of these libraries assign 8 bit addresses (256 nodes), which does not cover that amount of nodes.
What do you suggest?

FYI Maniacbug did not write RF24Mesh, TMRh20 did.

A few thoughts:

For ~$20 per unit, the 1mW Digimesh modules will take care of reliable mesh networking plus provide a high degree of configurability and scalability. Depending on the budget for your sensor nodes this might be better than "wasting a ton of time" messing with bare-bones hardware and third party code.
Constrain the mesh network within the "monitoring area" and set up dedicated point-to-point links (with higher power and directional antennae) between it and your office. Set up two or three if you want redundancy.
If you can't afford better hardware but have time to spare, consider reading up on mesh protocols and implementing one you think best fits your project. Many of them are reasonably simple if you are not pushing for maximum efficiency or performance.


text:
Can an Arduino act as a GATT Server (Bluetooth LE)
I know it's pretty standard to set up an Arduino system as a BLE client, and use something like an app running on a smartphone as the GATT server, which receives the data and does something with it.
In my scenario I have a BLE sensor that is not connected directly to the Arduino system, and I want the Arduino to be able to respond to the sensor output (a wearable accelerometer) and, for example, initiate various lighting sequences depending on the data being received.
I would prefer not to introduce a third component (ie: mobile device as GATT server) into the equation. I'd like for the Arduino to listen to the remote device's services and characteristics, analyze the incoming data and then make some decisions about what LEDs to illuminate based on that analysis.
Can an Arduino run as a GATT server?

You have it precisely backward. The GATT server is the peripheral device. The client is typically a mobile device. That said, I'm looking into this exact thing right now. The Arduino 101's Nordic module is capable of running in Central mode, but I'm unable to find any info on loading the S120 Soft Device. I have read that the Arduino lib doesn't have an API for it though. Theoretically possible, but I haven't figured out how to do it yet.

Does it have to be an Arduino or can it be Arduino IDE compatible? - e.g. something like the Adafruit Feather Bluefruit LE module?

Sure, I think @Simon

@Tom Auger There is an Adafruit Feather 32u4 Bluefruite LE module, you can interact with the BLE part using AT commands, it's pretty basic and can only act as a Server/Peripheral device. It doesn't support notifications or indications, but you can define a custom service with it's own characteristics.

@ Tom Auger The ESP32 modules also support BLE, but I haven't played with that aspect of the module. Looking at the examples available for the ESP32, that can be both a GATT Client and a GATT Server.

@SimonPeverett I'm a big fan of the ESP32, but I haven't played with one recently. This could be a good idea. The project is a gesture-driven bicycle signal. I don't want to have to use a phone as an intermediary.

An ESP32 module (Arduino IDE compatible) can act as both a GATT Client and Server, and there are module examples for each of these, as well as github projects.

I'll be checking that out soon. To make your answer more complete, you might post some example code or at the minimum some links, for the benefit of others that Google this question.

I got this link here that could be helpful - link at the bottom. It is a tutorial that shows you how to control your Arduino with a custom app on an Android. It uses the MIT app creator, an app that lets you create an app. You program it with there IDE in some Java I believe. You can add button to your app so that is sends a message to your Arduino then program the Arduino to do something when it receives that message. For the Arduino side, you could buy an HC-05 Bluetooth module. It is both an transmitter and receiver. It is quite cheap and very popular so there is many libraries out there. I think this is a good module you should get and I recommend to get them in pairs so you can connect them together with 2 Arduinos.
https://www.youtube.com/watch?v=E-1w7dL3Cps

Not applicable to the question asked.  An HC-05 is a classic bluetooth device.  This question is about BLE aka BTLE which is a very different standard, arguably having little more than the word "bluetooth" in common with one another.

authors: Урош Петровић

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


text:
How can I load fonts into Adafruit GFX for TFT display (ILI9341)
I get a compile error when I try to set a different font in Adafruit GFX on a TFT display on my Arduino Uno.
I'm testing a new TFT shield for Arduino equipped with an ILI9341 by using the Adafuit GFX libraries and examples. The test program supplied with the library works fine out of the box displaying text and all kind of drawings on the screen.
However, the standard font built into the Adafruit GFX library is "blocky" to save memory space. They do provide other fonts, but I get an error when I try to invoke them.
The segment of code that throws the compile error is this one:
unsigned long testText1() {
  tft.setFont();    // When I remove this line the sketch compiles OK
  tft.fillScreen(BLACK);
  tft.setCursor(0, 50);
  tft.setTextColor(RED);
  tft.setTextSize(13);
  tft.println("1234");
}

When compiling I get this error:

"error: ‘class Adafruit_ILI9341_8bit_AS’ has no member named ‘setFont’"

According to Adafruit's GFX manual, the setFont() procedure allows to define a new font or revert to the standard one.
I examined the libraries and nowhere could I find a procedure to select a font, yet the example has declarations like these below, so changing fonts should be possible:
#include <Adafruit_GFX_AS.h>
#include <Adafruit_ILI9341_8bit_AS.h>
#include <Font16.h>
// #include <Font32.h>
// #include <Font64.h>
// #include <Font72.h>
#include <Font7s.h>
#include <Load_fonts.h>

I would like to load the 7segment font with:
tft.setFont(&Font7s);

Does anybody have experience to share loading these fonts?

Newer versions of the library CAN use fonts.
#include <Fonts/FreeSerifBold12pt7b.h>

and then...
matrix.setFont(&FreeSerifBold12pt7b);

Whether they work or not, I dunno. Case closed, lol!

Tested on Windows, with newest libraries Adafruit-GFX and  Adafruit_PCD8544 (Nokia5110 LCD connected to Arduino Nano).
#include <Fonts/FreeSerifBold12pt7b.h>

and then
matrix.setFont(&FreeSerifBold12pt7b);

Then there is one very important difference how to use function drawChar(...). Coordinates of character (x,y) begins in left-bottom corner of character instead of top-left corner so this will not work (you will see only about 1 px of character):
matrix.drawChar(0,0,'1', 1, 0, 6),

Use this to show all pixels of character:
matrix.drawChar(20,20,'1', 1, 0, 6),

Full manual for using fonts here: Adafruit GFX Graphics Library - Using Fonts

Looking further into documentation on the Adafruit website they indicate that indeed, their GFX library published on GitHub does not handle different fornts.
Case closed :-)

Cosa, https://github.com/mikaelpatel/Cosa, supports both this display and has multiple fonts. Fonts example sketch: https://github.com/mikaelpatel/Cosa/blob/master/libraries/Canvas/examples/CosaCanvasFonts/CosaCanvasFonts.ino


text:
Arduino recieving binary
I was wondering if Arduino digital pin can receive binary data. For example, I might want one Arduino to send another Arduino a binary code. If the code is 01 it would turn a red led on, if it was 11 it would turn green on, etc. I would like to do this so that I don't have to use a lot of digital pins. Is this possible with Arduino or not?

Pretty much anything is possible.
There is a method known as bit banging which toggles a generic IO pin to create a protocol, and read changes on another generic IO pin to read in the data of a protocol.
The trick is in creating a protocol.
Fortunately that has all been done for you - the SoftwareSerial library. It will create a bit banged version of the RS232 serial protocol using any combination of IO pins to transfer data between devices.

As Majenko says, it is easily possible to implement using bit banging.  Assuming that you want to write your own protocol, you need to distinguish between the end of one data packet and the start of another.  This could be done by having all of the packets the same length (as in your example with length 2) or using a form of Huffman coding where only the external nodes of the state tree are results so you know when a full packet has been received.
Using a standard serial or I2C protocol would also work.  With serial you would be able to communicate via a serial emulator on a USB port so you could test with a computer.


text:
UART error can not compile on Arduino Yun (ATmega32u4)
This code is used for communication between the Glediator interface and a NeoPixel Matrix, but I receive an error saying 'UCSR0A' is not defined within the scope.
UCSR0A |= (1<<U2X0);
UCSR0B |= (1<<RXEN0)  | (1<<TXEN0) | (1<<RXCIE0);
UCSR0C |= (1<<UCSZ01) | (1<<UCSZ00)             ;
UBRR0H = 0;
UBRR0L = 1; //Baud Rate 1 MBit (at F_CPU = 16MHz)

Any feedback is appreciated.

Those register names are for a different chip (maybe the ATMega328P of the Uno).
Instead you need to use the right register names.  Start by reading the datasheet for the ATMega32U4.  You might find that the register names are UCSR1A etc, or UCSRA or something like that instead of UCSR0A.

You should be able to use Serial1 to access the USART. But...

Note that on the Yún, the Serial class refers to USB (CDC)
  communication; for TTL serial on pins 0 and 1, use the Serial1 class.
  The hardware serials of the ATmega32U4 and the AR9331 on the Yún are
  connected together and are used to communicate between the two
  processors. As is common in Linux systems, on the serial port of the
  AR9331 is exposed the console for access to the system, this means
  that you can access to the programs and tools offered by Linux from
  your sketch[1].

Please see below references for further details:

https://www.arduino.cc/en/Main/ArduinoBoardYun
https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/variants/yun/pins_arduino.h#L40
https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/variants/leonardo/pins_arduino.h#L363

Thanks Mikael, I think you just helped me find the problem with the serial communication. I am trying to communicate with an interface called Glediator which is a program that controls LED's of matrices. I have an 16x16 matrix connected to the Yun and It works when upload a sketch to it from ADI itself, but for Glediator i have to upload a Communication Interface script but I think something is edited wrong. As soon as I Open Serial in Glediator, the program freezes. Would you have the time to look at my code, I posted it on this page underneath your comment. Thank you in advance!

So what I did was changing the codes by replacing the '0' from the other chipset to the '1' on the Atmega32u4
UCSR1A |= (1<<U2X1);
UCSR1B |= (1<<RXEN1)  | (1<<TXEN1) | (1<<RXCIE1);
UCSR1C |= (1<<UCSZ11) | (1<<UCSZ10)             ;
UBRR1H = 0;
UBRR1L = 1; //Baud Rate 1 MBit (at F_CPU = 16MHz)

ISR(USART_RX_vect)
{
  unsigned char b;
  b=UDR1;
...

I think that this is the problem that causes freeze when I Open Serial.
Any advice? Thanks In advance


text:
Automatic/manual door lock with servo
I'm building an automatic door lock, which is moved by a servo ( this one ). However, I want to still make it possible to open the lock manually, but it's not possible if the servo is attached to the lock mechanism.
Do you have ideas on how to go around this problem?
Here's a diagram of the lock mechanism

Can you give some more detail about how the lock is intended to function? We may be able to come up with some hitherto un-thought of solution, but we need to know how the whole mechanism will function to be able to visualise it better.

@Majenko I've edited the question with a diagram of the lock mechanism

Excellent, that's exactly what we need to see.

I'm voting to close this question as off-topic because This question belongs on another site in the Stack Exchange network -- eg
Robotics Stackexchange

Ok my bad, but will it still be visible? Other people could find this thread useful.

Jonathan, I doubt the question will get closed; it takes 5 such votes (or a moderator) to close a question.  But it might get migrated to  Robotics Stackexchange, which is as visible as but less popular than Arduino SE.  Note, closed questions remain visible, but are not eligible for new answers.

Robotics Stack Exchange declined the migration.

So it's actually the worm gear that is causing your problem, since that can't be reverse driven by the cogs.
The simplest option, I think, would be to have the middle cog normally separated from the worm gear and only re-engage it when you need to drive the mechanism with the servo.  You could maybe use a second servo to move it into the right place, or maybe a solenoid, or something along those lines. Have it slide along a short track or slot with a spring to ensure it disengages when the solenoid is released.

Do you think it would be simpler/better to change the servo with a DC motor?

If you still have the worm gear in there you'll still be in the same boat. Most electronic locks work by releasing the other end of the tennon from the mortice instead of retracting it - it's simpler that way.

but with a DC motor rather than a servo, you can rotate it manually without problem. The only thing to manage is the current generated by this free rotation.
But, if we stay with the servo, which of the 2nd servo or a sollenoid do you think will be best (if you have an opinion) ? In terms of complexity to implement and also constancy.

A solenoid is the normal preferred option. You sometimes see clutch gears that allow the outer teeth to rotate independently of the central axis, which would be in place of the lock spindle cog - but those are expensive and generally custom designed. You see them in laser printers quite often for the paper feed.

You sometimes see ratchet clutch cogs too, where if you rotate the teeth in one direction the turn the central spindle, but in the other direction they don't engage with the spindle - and the spindle can rotate separately too. Again complex and expensive...

Thanks a lot for all your insights. I'd vote up your answer but I don't have the privilege on the Arduino exchange!

@Jonathan That will come with time :)


text:
Compute yaw from magnetometer and accelerometer
I use an Arduino and a 9 DOF sensor (gyroscope, accelerometer and magnetometer) and I'm trying to use the pitch, roll and yaw that the sensor gives me to rotate an object in unity.
I managed to correctly compute pitch and roll (the z and x axis in unity) from the accelerometer but it seems that I can't get the Yaw right. By that I mean that when I rotate my sensor pitch or roll it rotates my yaw too, in a weird way.

Code in the arduino to get the heading
void getHeading(void)
{
  heading=180*atan2(Mxyz[0],Mxyz[1])/PI;
  if(heading <0) heading +=360;
}

void getTiltHeading(void)
{
  //float pitch = asin(-Axyz[0]);
  //float roll = asin(Axyz[1]/cos(pitch));
  float pitch = atan( Axyz[0] / sqrt( Axyz[1] * Axyz[1] + Axyz[2] * Axyz[2] ) );
  float roll = atan( Axyz[1] / sqrt(Axyz[0] * Axyz[0] + Axyz[2] * Axyz[2]));

  float xh = Mxyz[0] * cos(pitch) + Mxyz[2] * sin(pitch);
  float yh = Mxyz[0] * sin(roll) * sin(pitch) + Mxyz[1] * cos(roll) - Mxyz[2] * sin(roll) * cos(pitch);
  float zh = -Mxyz[0] * cos(roll) * sin(pitch) + Mxyz[1] * sin(roll) + Mxyz[2] * cos(roll) * cos(pitch);
  tiltheading = 180 * atan2(yh, xh)/PI;
  if(yh<0)    tiltheading +=360;
}

Pitch and roll
    float _Pitch  = (float)(180 / Math.PI * Math.Atan( m_ResultX / Math.Sqrt( m_ResultY * m_ResultY + m_ResultZ * m_ResultZ ) ) );
    float _Roll = (float)(180 / Math.PI * Math.Atan(m_ResultY / Math.Sqrt(m_ResultX * m_ResultX + m_ResultZ * m_ResultZ)));
    float _Yaw = (float)(m_TiltHeadingResult);

Don't hesitate to ask for details.

did u figure out why your yaw changes if you pitch/roll the sensor? and how was it addressed? any information would help me too.

I don't know how all your sensor's axis are lined up, but it looks like you should level the magnetometer readings by rotating them by -pitch and -roll to get back to the global reference frame, instead of rotating the magnetometer readings by the positive angles.
However, The pitch and roll angles in the code are both relative the horizon, not a set of euler angles that define a rotation between two states; because of this, they do not compose to rotate the magnetometer back into the global xy frame like I assume the equations are trying to do. The code is also only using atan for pitch and roll instead of atan2, so their range is only 180 degrees.
You need to make sure the rotation matrix you multiply your magnetometer reading by is based on the same conventions as the equations you use to get pitch and roll from the accelerometer, and that it cancels the observed rotation.
To do this correctly, I recommend you read into euler angles. You might also try searching around for a good library that handles 9-DOF sensor fusion for you.

I've read a bit about the euler angles but my math isn't that great nor had I time to investigate further but I managed to find a very good 9-DOF sensor fusion. Everything is ok now.

Would you provide a link to the sensor fusion you used?


text:
Arduino IR remote control hold value
I am trying to make a remote controlled robot with Arduino and the IR remote control is kinda weird. When I press a button, sometimes I get the right hex value, other time I get the hold value FFFFFF.
How can I implement some code so that I can, for example, run the motors as long as I hold the button or detect which button it was since the hold code is the same for all codes?
Since I know that the hold value is 0xFFFFFFFF, is there a function that:
(any hex not 0xffff) func(OR?) (0xffffffff) = (any hex ...)

and
( 0xfffff)           func (0xffffff)   != (0xffffff)

Or do I need to implement some kind of state machine? It is kinda difficult with the delay() as well.
By the way, I'm using Keyes KY 022. What are the signal length times? (I don't have an oscilloscope).
Maybe would be useful to set the press value to other? Or to ignore it?
LE: And some code to test: one single key:
Maybe other libraries are interrupting the timer...
    #include <IRremote.h>
    #define IR_PIN 11
    IRrecv irrecv(IR_PIN);
    decode_results results;
    long int Key;
    const unsigned long int UP = 0x00FF629D;
    const unsigned long int DOWN = 0x00FFA857;
    const unsigned long int LEFT = 0x00FF22DD;
    const unsigned long int RIGHT = 0x00FFC23D;
    const unsigned long int OK = 0x00FF02FD;
    const unsigned long int k1 = 0x00FF6897;// C101E57B
    const unsigned long int k2 = 0x00FF9867;// 97483BFB
    const unsigned long int k3 = 0x00FFB04F;// F0C41643
    const unsigned long int k4 = 0x00FF30CF;
    const unsigned long int k5 = 0x00FF18E7;
    const unsigned long int k6 = 0x00FF7A85;
    const unsigned long int k7 = 0x00FF10EF;
    const unsigned long int k8 = 0x00FF38C7;
    const unsigned long int k9 = 0x00FF5AA5;
    const unsigned long int STAR = 0x00FF42BD;
    const unsigned long int k0 = 0x00FF4AB5;
    const unsigned long int HASH = 0x00FF52AD;
    const unsigned long int HOLD = 0xFFFFFFFF;

   void setup(){
   // put your setup code here, to run once:
      Serial.begin(9600);
      delay(2000); while (!Serial);
      irrecv.enableIRIn();
  //irrecv.blink13(true);
  //setup1(); From IRremoteInfo TAB
   }
char buff[1000];
unsigned long int msg;
void processIR(unsigned long int msg)
{
  sprintf(buff, "READ IR %x \n", results.value);
  Serial.print(buff);
  switch (msg)
  {
    case UP:
      Serial.println("UP");
      break;
    case DOWN:
      Serial.println("DOWN");
      break;
    case LEFT:
      Serial.println("LEFT");
      break;
    case RIGHT:
      Serial.println("RIGHT");
      break;
    case k1:
      Serial.println("k1");
      break;
    case k2:
      Serial.println("k2");
      break;
    case k3:
      Serial.println("k3");
      break;
    case k4:
      Serial.println("k4");
      break;
    case k5:
      Serial.println("k5");
      break;
    case k6:
      Serial.println("k6");
      break;
    case k7:
      Serial.println("k7");
      break;
    case k8:
      Serial.println("k8");
      break;
    case k9:
      Serial.println("k9");
      break;
    case STAR:
      Serial.println("STAR");
      break;
    case k0:
      Serial.println("k0");
      break;
    case HASH:
      Serial.println("HASH");
      break;
    case HOLD:
      Serial.println("HOLD");
      break;
      //case default:
      //    delay(500);
      //       irrecv.decode(&results);
      //       msg = results.value;
      //       processIR(msg);
  }
}

void loop() {
  // put your main code here, to run repeatedly:
  if (irrecv.decode(&results))
  {
    irrecv.resume();
    char buff[255];
    sprintf(buff, "Val %010x \n " , results.value );
    Serial.print(buff);
    //results.decode();
    //results.DumpResults();
    //      msg = results.value;
    //      Serial.println(msg, HEX);
    //      Serial.println(results.decode_type);
    //      processIR(msg);

  }

}

And values, of course:
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x000002fd
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x000022dd
 Val 0x0000ffff
 Val 0x0000c23d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000ffff
 Val 0x0000ffff
 Val 0x0000ffff
 Val 0x0000ffff
 Val 0x0000ffff
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x00005282
 Val 0x000038d6
 Val 0x0000ffff
 Val 0x0000efb5
 Val 0x00006897
 Val 0x00006897
 Val 0x00006897
 Val 0x0000ffff
 Val 0x00006897
 Val 0x00006897
 Val 0x0000ffff
 Val 0x00006897
 Val 0x00009867
 Val 0x00009867
 Val 0x0000b04f
 Val 0x0000ffff
 Val 0x00004794
 Val 0x00009424
 Val 0x0000ffff
 Val 0x000042bd
 Val 0x0000ffff
 Val 0x00004ab5
 Val 0x0000ffff
 Val 0x000052ad
 Val 0x0000ffff
 Val 0x00004ab5
 Val 0x00005aa5
 Val 0x0000ffff
 Val 0x000038c7
 Val 0x000010ef
 Val 0x0000ffff
 Val 0x000030cf
 Val 0x0000ffff
 Val 0x000018e7
 Val 0x0000ffff
 Val 0x00007a85
 Val 0x0000ffff
 Val 0x00004ec5
 Val 0x00007a2a
 Val 0x00007d4f
 Val 0x0000a33f
 Val 0x00007a28
 Val 0x00008dd8
 Val 0x00004b78
 Val 0x0000144b
 Val 0x00006781
 Val 0x0000040a
 Val 0x0000ffbf
 Val 0x00007d4f
 Val 0x0000ee7c
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff
 Val 0x0000629d
 Val 0x0000ffff

So each press of a key gives 2 values.

char buff[1000]; - what Arduino is this? You know Arduinos generally don't have a lot of RAM? Using 1000 bytes to hold READ IR abcd \n seems a little excessive.

Yes, I know. Was just testing ... Maybe the real question when I changed the size was if "sprintf() overflows" Maybe it is, but it just overflowed, but didn't had any shellcode.

If I understand your question correctly, a button press will first generate a distinct hex code, and then after a while a series of 0xFFFFFF?
In that case, why don't you simply store the last distinct code you received, and replace occurrences of 0xFFFFFF with the stored code?

I found out that by adding this while loop to an IRremote use, the code after it won't run until the button is released.
while(irrecv.decode(&results)){
    irrecv.resume();
    delay(150);
}

This will keep the buttons pressed if the code at the end on loop() ends the input.

Man you are a genius! it works :)


text:
Controlling a DC motor with an external power source
I'm trying to use an Arduino to release a single drop of water using a solenoid valve.  This article describes how to create this circuit with a Raspberry Pi using a DC powered solenoid that opens and closes very quickly and they use this for photographing water drops.  Exactly what I need, if I could only get it to work with the starter kit items first.
The design for the solenoid circuit from that site looks like:

I don't have a solenoid yet, but I've been experimenting with the cheap motor that comes with the Arduino and a 9 V battery.  I've burned out several transistors in my attempts to get this working.  My schematic looks like:

Relays won't work.  They are too slow.  Also, I need to use an external battery.  I can't use the power from the Arduino because I will eventually be moving up to a 12 V battery and the Arduino won't be able to handle that.

A motor is a quite different load than a solenoid. Before it starts rotating it takes a lot of current. A solenoid has no inrush current when you apply power.

Are you sure about the inrush current? Seems to me there would be.

Seeing as you want to use a 12V battery, you should try an external motor controller. You would essentially connect the Arduino to the controller, then the external battery and motor to the controller. Dimension Engineering makes several high quality motor controllers that are compatible with Arduino and can handle the voltage (like this controller). The site also includes Arduino libraries, documentation, and all the specifications on every product. I have used several of their products with my Arduino Uno and have had no problems.

I can think of a couple of things that you might consider.
The motor looks like a good surrogate for the solenoid.
If you're burning out transistors, look at the following 3 most probable causes:
a) Voltage spike when you cut the current to the coil (motor or solenoid). If the fly-back diode is still intact, this should not be your case.
b) Current spike exceeding Icmax. This is the maximum current your BJT can sustain without damage. An inductor like your solenoid or motor will reach in DC a maximum value dictated by Ohm's law. So measure the motor's resistance with a multimeter and calculate the Imax.
It should be Imax = (VDC - Vcesat)/Rcoil, where Vcesat is the saturation voltage of your BJT, somewhere around 0.3V.
Measuring the current of the motor connected to the battery also works if you measure it while you block the rotor.
Check that your transistor can handle the current.
Small signal transistors usually are rated at around 150mA, so this might be too little for your coil. So maybe you would need to buy/build a Darlington transistor that will have the amplification factor and current capacity to handle the load.
c) If a and b are OK, then maybe the transistor is overheating? Your fingers will tell you :-)
Once this works with the motor, you might need to recalculate to accommodate the (eventual) higher current of the solenoid.

You will also need a ceramic capacitor connecting the wires of the motor. also the diode should be at least 1amp and the transistor have the specs to take the loadd.


text:
How would I use Arduino microcontroller separately?
I'm learning Arduino. I use Arduino Uno board with ATMEGA328-PU. I tried basic codes like LED blink, control of DC motor etc. Arduino board is used only when we program microcontroller, right? I mean, when we finish programming it, we can use microcontroller separately? If it can be used separately, we must have some "external" circuit as replacement for Arduino board, which allow us to use microcontroller in specific application. What type of circuit is used? I'm new in this field so don't blame me because of amateur questions.

Assuming you are going to upload the program into the ATmega328 on the Arduino, then take the ATmega328 out of the socket, and use it in your circuit, then a simple answer is to search for "minimal Arduino circuit"
An example returned by that search is "From Arduino to a Microcontroller on a Breadboard".
It lists:

a 16 MHz crystal,
a 10k resistor, and
two 18 to 22 picofarad (ceramic) capacitors

That is enough to run the chip at the same speed as the Arduino, and the code used on the Arduino to initialise its clock will work unchanged.
This should run okay directly from a battery supply of about 4.5V or 4.8V, or a good 5V power supply.
A better circuit, which runs at the same 16MHz speed as the Arduino is 'Shrimp It'. That shows a similar minimal circuit and a better 'protected' circuit which has a more reliable approach for its power supply. This is all you need to run off a 4.5V (e.g. 3 1.5V) battery power supply.
However, if you don't care about running at 16MHz, you could ditch the crystal and capacitors, and use the internal 8MHz oscillator, that will need the code to be slightly different. For example, the 8MHz clock is 1/2 the speed of the Arduino's standard 16MHz, so code like delay() will take 2ms instead of 1ms.
Further, the RESET button can be set up so it doesn't need the 10k pullup.
So, with some software changes (search the web for details), an ATmega328 could be used with no external components.
Alternatively, you might want to use a better power supply, for example a voltage regulator with the circuit of the protected 'Shrimp It', and be able to load the program onto the ATmega while on its board.
There are products which bundle that 'standard' set of parts (voltage regulator, plugs and sockets and protected 'Shrimp It' running exactly like an Arduino at 16MHz) with a very compact PCB. They are able to plug directly into a breadboard, and so can be used with veroboard/stripboard (or a PCB) to make the rest of the circuit.
One is a kit called 'Boarduino'from adafruit. That web site gives some details to sow how to do this yourself. It is a convenient-to-use version of the 'Shrimp It', on a compact PCB.
An alternative kit is the "Really Bare Bones Board (RBBB) kit". However it is available as the PCB only, which is the "Really Bare Bones board (RBBB)", though the same supplier as the RRRB kit.
Neither Boarduino nor RRRB has on-board USB upload circuit. However, you can use your Arduino to do that, for example "Using an Arduino as an AVR ISP (In-System Programmer)". Or you could buy a USB to UART cable.

Without some capacitor(s) between Vcc an GND the ATMega can sometimes behaving erratic.

Look at the schematics and see which bits you don't need. Leave those out and what's left is what your require. You then would need to design a circuit board for these parts.

Now, who should we blame for your amateur questions? ;^)

Thanks a lot for answer! I mean I don't have experience with this so understand me :) English is not my first language and language barrier makes difficulties often :) Best regards

Your English isn't too bad! For one or two projects the ready-made Arduino boards are good value because everything is tested. Building your own circuits is good fun but is expensive and difficult if using surface mount components. If you are going to make, maybe, 20 + of the same device then making your own board might be a good idea. I don't think you are ready for that yet.

If you want to buy a cheap almost bare minimum Atmega breadboard, consider a chinese clone of Arduino pro mini. Difficult to fabricate one cheaper yourself.

There are two approaches to this.  One is to simply use the Arduino Uno board in your final product!  However, if you're making a large number of boards, it may be more cost efficient to develop a custom board with only the features you need.  It may be nothing more than a few GPIO pins and a power regulator!
Another thing which can be important in these final products, no matter what board you are using, is that you can permanently burn your program into memory so that it always starts up when power is applied.

Arduino board is used only when we program microcontroller, right?

Not necessarily. The Arduino board is useful not only for programming, but because it provides required peripheral circuitry such as power regulation, USB-serial interface, convenient headers, and a crystal.
However, it is perfectly fine to use the Arduino board to program your ATmega328 and then take it out and use it in another circuit.

If it can be used separately, we must have some "external" circuit as replacement for Arduino board, which allow us to use microcontroller in specific application. What type of circuit is used?

All the ATmega328 really needs is a stable power supply. If you're alright running it at 8MHz, you don't need an crystal. If you don't need in-circuit programming, you don't need an ISP connection or any USB-serial stuff.
For more powerful microcontrollers, you might require clock generation circuitry, multiple power rails, debug/programming connections, etc.

See this page on how to put an ATMega329 chip on a breadboard and have it run. I think this will explain things: https://www.arduino.cc/en/Main/Standalone


text:
Why I cannot change array values even if a statement is successfully called? TFT Touch Screen
#include <Adafruit_GFX.h>    // Core graphics library
#include "LGDP4535.h" // Hardware-specific library
#include <zTouchScreen.h>
#define BOXSIZE   40
// Assign human-readable names to some common 16-bit color values:
#define BLACK   0x0000
#define BLUE    0x001F
#define RED     0xF800
#define GREEN   0x07E0
#define CYAN    0x07FF
#define MAGENTA 0xF81F
#define YELLOW  0xFFE0
#define WHITE   0xFFFF

LGDP4535 tft; // Using the shield, all control and data lines are fixed

#define YP A3  // must be an analog pin, use "An" notation!
#define XM A2  // must be an analog pin, use "An" notation!
#define YM 9   // can be a digital pin
#define XP 8   // can be a digital pin

// You need to calibrate to fit your LCD
#define TS_MINX 930
#define TS_MINY 903
#define TS_MAXX 142
#define TS_MAXY 117

#define PENRADIUS 3
#define MINPRESSURE 10
#define MAXPRESSURE 1000

int matrix[2][3]; // Initial Declaration
int array[3]

TouchScreen ts = TouchScreen(XP, YP, XM, YM, 300);

// array = start with 1 but the variable read start with 0
String ButtonAction[9]={"a", "b", "c", "d", "e", "f", "g", "h", "i"};
boolean ActiveMenu=true;

void setup(void) {
   Serial.begin(9600);
   tft.reset();
   tft.begin();
   ts.InitVariable(3, 240, 320, TS_MINX, TS_MAXX, TS_MINY, TS_MAXY, MINPRESSURE, MAXPRESSURE);
   tft.fillScreen(BLACK);
   DrawIt(CYAN, "draw");
   DrawIt(BLACK, "text");
}

void loop() {//SOME OTHER STUFF}

unsigned long DrawIt(uint16_t color, String CurrentAction) {

  int timedcycle=0;

  if (CurrentAction == "text") {
     int matrix[2][3]={{25,150,265},{45,100,155}};
     int array[3]={3,3,3};

     tft.setRotation(3);
     tft.setTextColor(BLACK);
     tft.setTextSize(1);

     Serial.println("Text Columns");
  }

  else if (CurrentAction == "draw") {
    int matrix[2][3]={{260,140,20},{40,150,95}};
    int array[3]={3,3,3};
  }

  Serial.println(CurrentAction);

  for(int j=0; j<3; j++) {
     for(int i=0; i<array[j]; i++) {

       if (CurrentAction == "draw") {

         if (timedcycle == 7) {
           tft.fillCircle(100, 160, 15, WHITE);
         }
         else {
           tft.fillRect(matrix[1][j], matrix[0][i], 20,40, color);
         }

       }
       else if (CurrentAction == "text") {
         if (timedcycle == 4) {
           true;
           //tft.fillCircle(100, 160, 15, WHITE);
         }
         else {
           tft.setCursor(matrix[0][j], matrix[1][i]);
           tft.println(ButtonAction[timedcycle]);
         }

       }
     timedcycle++;
     }
  }
}

So as you can see I'm trying to draw some things in a TFT Touch Screen. Everything seems to be working but no matter what I do I can't change the array value.
If I initialize the array variable with a predetermined value it won't change even if the statement is called correctly. I can see that it runs over serial but the array still doesn't change.
I suppose there's something wrong but I can't pinpoint what it is! Thanks in advance!

You have defined three matrix/array; one in the global context and one per block in the local context in DrawIt. The definitions in the local context are removed by the compiler as they are not used (drop out of context). What you need to do is assign the global matrix/array instead.

So my mistake is involved with variable declaration as my values are discarded by natural behaviour of the compiler. I didn't think of that but it's the same on other languages as well but I didn't took the "loop" and "setup" functions into account. Thanks for the quick explanation

It's because you are defining a new array every time, not modifying the existing one.
int matrix[2][3]={{25,150,265},{45,100,155}};

That line doesn't assign new values to the existing matrix array, instead it creates a new array called matrix which only exists within the current scope - that is, within the {...} defined by the if that it is within.
Instead you either need to assign values directly to the existing matrix array on a slice-by-slice basis (you cannot use {...} to assign them in bulk):
matrix[0][0] = 25;
matrix[0][1] = 150;
... etc ...

Alternatively, since the values are static, you can pre-define the different matrices in the global scope and then switch between them.  This can be done with the right kind of pointer. For instance:
int textMatrix[2][3] = {{260,140,20},{40,150,95}};
int (*matrix)[3];

void whateverTheFunctionIs() {
    if (whatever...) {
        matrix = textMatrix;
    }
}

In that example matrix is a pointer to an array of pointers, which is basically what a 2D array is internally.  It starts off by not being assigned to anything at all - it's just "dangling in the breeze".  When the if in your function is triggered the address that the matrix pointer points to is changed to that of the textMatrix 2D array, so any access to matrix[x][y] will be identical to accesses to textMatrix[x][y].

Can you provide an example on how can I accomplish that?

Instead if using int matrix... you just assign new values to the individual slices. Note that you cannot use the {...} notation for that but must assign each value individually. matrix[2][1] = 43

So the best option is to create another array with fixed values? Thanks for your answer and I'll check on this to accept your answer

I am at my desk now, so I can give a much fuller answer... check back in a mo for my edit.

I got an error with the global variable part: 182:13: error: cannot convert ‘int [2][3]’ to ‘int**’ in assignment. I'll try the first solution then

TBH I didn't actually try the code out - I may have made a mistake with it ;)

Appologies - the definition of matrix should have been: int (*matrix)[3];

Don't worry I'll rewrite my code again to include your edit for a later feedback. Thanks for your time and consideration


text:
Arduino does not work
When I try to upload a sketch to my Arduino Uno R3 then sometimes I get the following issue:
At the beginning the RX LED flashes three times and then I get errors:
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xd1
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xd1
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xd1
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xd1
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xd1
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xd1
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xd1
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xd1
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xd1
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xd1

Sometimes I get this:
    avrdude: ser_open(): can't open device "\\.\COM3": Odmowa dostępu.

And sometimes Windows does not see the Arduino.
At this site Have I bricked my Arduino Uno? Problems with uploading to board I read that to check the programmer I must to connect RX with TX and GND with RESET pins and then plug Arduino to my computer, open Serial Monitor and write anything and if you receive the same characters from the Arduino, then the programmer and USB cable are OK. It worked for me.
And I have got one more info. When I plug Arduino with USB to my laptop the L led lights. When I press Reset on Arduino nothing happens, it still lights.
I recently bought a new USB cable, and it worked one day and then I could not upload sketches again. I uninstalled and installed drivers, but nothing changed.
This is a short video with my Arduino https://drive.google.com/file/d/0ByeWvrEgy2gRbWdHQ3d5RWU3Mmc/view?usp=sharing

I will buy USBasp programator is it a good idea?

I am not sure about that particular error. But, have you set the right board and port on the arduino IDE?

Yes i checked it and I have right board and com port, but thanks for comment.

Restart your PC, "Access denied" is because something/some program is using your COM port. Or might have not been closed correctly by another upload or program.

It's normal that the L-LED is steady on after the USB connection is established. However, after pressing and releasing Reset it should flicker for a second, then go back to on again.
Check https://www.arduino.cc/en/Guide/Troubleshooting#toc1 for reasons why you can't upload.
On http://www.arduino.org/products/boards/4-arduino-boards/arduino-uno I've found:

The Arduino Uno has a resettable polyfuse that protects your computer's USB ports from shorts and overcurrent. Although most computers provide their own internal protection, the fuse provides an extra layer of protection. If more than 500 mA is applied to the USB port, the fuse will automatically break the connection until the short or overload is removed.

I haven't found out so far, how to read the current values of the fuses.

I will buy USBasp programator is it a good idea?

But when I click reset the l-led is not flicker

From the first link: Make sure there's a bootloader burned on your Arduino board. To check, reset the board. The built-in L LED (which is connected to pin 13) should blink. If it doesn't, there may not be a bootloader on your board.

@JanOkoński If you have no other Arduinos then yes, it's always a good idea to have a USBasp programmer. Make sure you get the one with 3.3V/5V mode, USBasp itself programming jumper and the right cable to program regular Arduinos. (http://g01.a.alicdn.com/kf/HTB1PB8pKpXXXXc3XVXXq6xXFXXXz/AVR-USBASP-Programmer-ATMEGA-ATMEL-downloader.jpg) Should cost just as much, but has much more features.

Serial could be flooded if you were spamming it in ur last program you uploaded.
Ur arduino is broken
Try reflashing ur bootloader which is a common problem when you see data sync errors.

I will buy USBasp programator is it a good idea?

Yes, buy the USBasp programmer, reflash the bootloader with it, and try uploading code again. A corrupted bootloader very well may be the problem.

authors: Дмитрий Шевчук


text:
Why can't I upload GRBL but I can upload other sketches
I had GRBL running on an Arduino UNO (China Copy).
When I tried to update to the newest GRBL Version I was not able to upload the sketch:

avrdude: stk500_recv(): programmer is not responding)

I was unable to reprogram a bootloader via another ARDUINO (Arduino ISP) but I was able to update the firmware (dfu-programmer)
The funny thing is that I was only able to program the DFU as AT90USB82 not as ATmega8U2 while the chip has an ATmega8U2 printing.
I can upload any example sketch from Arduino IDE but not GRBL.
Any suggestions?