text:
How to decrease delay for String concatenation + Arduino Due
In my project I need to add a delimiter between integer numbers. In the following code. I add a "," between integer numbers obtained from inputsig matrix. The problem is that concatenation of these numbers with concat() command for a Matrix with 100 rows and 9 columns takes 10 ms.  Is there any efficient way to decrease this delay?
#include <CStringBuilder.h>

int Max_pack_size = 100;

void setup() {
  SerialUSB.begin(115200);

  while (!SerialUSB) ;

}

void loop() {

  String  datas1;
  String  inputsig[Max_pack_size][9];
  char buff[((8+1)*Max_pack_size+1)*9];
  CStringBuilder sb(buff, ((8+1)*Max_pack_size+1)*9);

  for (int i = 0; i < Max_pack_size; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      inputsig[i][j] = 16777215;

    }
  }

  int t0 = micros();

  for (int i = 0; i < Max_pack_size; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      //datas1.concat(inputsig[i][j]);
      //datas1.concat(",");
  sb.print(inputsig[i][j]);
  sb.print(F(","));
    }
  }

 SerialUSB.println(float(micros() - t0));
 delay(1000);

 SerialUSB.println(buff);

}

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

I don't have Arduino Due but I have an Arduino Uno so I had to adjust the code to run with much smaller RAM and use the standard Serial.
This is the original code as you can see i can use only Max_pack_size of 5
#include <CStringBuilder.h>

int Max_pack_size = 5;

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

void loop() {

  String inputsig[Max_pack_size][9];
  char buff[((8 + 1)*Max_pack_size + 1) * 9];
  CStringBuilder sb(buff, ((8 + 1)*Max_pack_size + 1) * 9);

  for (int i = 0; i < Max_pack_size; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      inputsig[i][j] = 16777215;
    }
  }

  int t0 = micros();

  for (int i = 0; i < Max_pack_size; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      sb.print(inputsig[i][j]);
      sb.print(',');
    }
  }

  int t1 = micros();

  Serial.println(float(t1 - t0) / 1000.0);
  delay(1000);

  Serial.println(buff);
}

The timer displays values around 2.08 milliseconds for the code above.
First optimization attempts is to stop using StringBuilder. Everything that's written to be universal and easy to use is usually slow.
Note that when we generate String from long the implicit cast allocates char buf[2 + 3 * sizeof(long)]; so the max length of such string is 14 characters. String is of course terminated by null character '\0'
#include <CStringBuilder.h>

int Max_pack_size = 5;

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

void loop() {

  String inputsig[Max_pack_size][9];
  char buff[((8 + 1)*Max_pack_size + 1) * 9];

  for (int i = 0; i < Max_pack_size; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      inputsig[i][j] = 16777215;
    }
  }

  int t0 = micros();

  int p = 0;
  for (int i = 0; i < Max_pack_size; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      for (int k = 0 ; k < 14; k++)
      {
        char c = inputsig[i][j][k];

        if (c == 0)
          break;
        else
          buff[p++] = c;
      }

      buff[p++] = ',';
    }
  }

  int t1 = micros();

  Serial.println(float(t1 - t0) / 1000.0);
  delay(1000);

  Serial.println(buff);
}
}

Now the timer displays 0.86 milliseconds. Much better, but we can improve even more!
Let's drop the String. It's just an over complicated wrapper for a char array anyway.
#include <CStringBuilder.h>

int Max_pack_size = 5;

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

void loop() {

  char inputsig[Max_pack_size][9][14];
  char buff[((8 + 1)*Max_pack_size + 1) * 9];

  for (int i = 0; i < Max_pack_size; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      ltoa(16777215, inputsig[i][j], 10);
    }
  }

  int t0 = micros();

  int p = 0;
  for (int i = 0; i < Max_pack_size; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      for (int k = 0 ; k < 14; k++)
      {
        char c = inputsig[i][j][k];

        if (c == 0)
          break;
        else
          buff[p++] = c;
      }

      buff[p++] = ',';
    }
  }

  int t1 = micros();

  Serial.println(float(t1 - t0) / 1000.0);
  delay(1000);

  Serial.println(buff);
}

Now the timer shows 0.50 milliseconds. So we optimized the code to the point it runs 4 times as fast.

Deat Filip. Thanks for your help. I tested this and could decrease the delay to 2ms.


text:
How to display float variables on oled display (0.96'')
I have a similar problem than the discussed here : How to display variables on 0.96" OLED with u8glib library?
I'd like to know how can I show float variables in place of int variables. What should i modify in this part of my code ?
char buf[9];
sprintf (buf, "%d", a);
u8g.drawStr(18, 3, buf);

} while( u8g.nextPage() );

delay(200);

}

Thanks in advance =D

Is this code working for you? If not, what happens wrong?

yes, it's working, but just with int variables =/. when i try float ones it do not work.

What means "does not work"? Please describe what actually happens

The printf group of functions in the Arduino library don't implement float and double conversions. For those, you need the function
char *dtostrf(double dval, int8_t width, uint8_t prec, char *buf);
  Convert the double value passed in dval into an ASCII string stored in
  buf. Conversion is done as "[-]d.ddd". The minimum field width of the output
  string (including the '.' and the possible sign for negative values) is given
  in width, and prec determines the number of digits after the decimal. width
  is signed, negative for left adjustment.
  Returns buf.

, which you'll need to call for each float you want to convert.
Note that you could convert several floats into strings, upfront, each into its own character buffer, then use sprintf to format the final buffer - remembering that in sprintf's format string, those buffers contain character strings, which you'll need to specify with '%s' format-specs.

The u8glib library provides the Arduino's standard print()
method. You can the write:
u8g.setPrintPos(18, 3);
u8g.print(a);

and it should work for mostly any type of a.

source: Stack Exchange

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

sort: votes


text:
L1 is not declared in this scope error
I have a project where I have to control a DC motor.
In this code the purpose is that every time you press a button the direction of the motor changes.
I only get the error that L1 (and L2,R1 and R2) are not declared in this scope. the place in the loop.
How do I define the variables so that the code works?
int Motorforward = 10;   // MotorDirectionPin set to pin10
int Motorbackward = 11;   // MotorDirectionPin set to pin11
const int button1Pin = 2; //button control set to pin 2

int state = L1;
int state = L2;
int state = R1;
int state = R2;

int button1State;  // current reading from the input pin
int previous = LOW; //the previous reading from the input pin

char input;

void setup(){
pinMode(button1Pin, INPUT); //set pin as input
Serial.begin(9600);

pinMode(Motorforward, OUTPUT); // sets the pin as output
pinMode(Motorbackward, OUTPUT);
 }

  void loop(){
button1State = digitalRead(button1Pin);
input = button1State;

switch(state){
  case L1:
    if (state == L1){
    if (button1State == HIGH){
        state == L2;
    }
  }
  break;

case L2:
  if (state == L2){
    if (button1State == LOW){
      state == R1;
    }
  }
  break;

case R1:
  if (state == R1){
    if (button1State == HIGH){
      state == R2;
    }
   }
  break;

case R2:
  if (state == R2){
    if (button1State == LOW){
      state == L1;
    }
  }
  break;
}

How many state variables do you want?!  And it is quite correct. At no point do you ever declare those symbols.

Do you mean the different states the motor can be in?
in that case 4 states in which case 1 and 2 and case 3 and 4 give the same result.

No, I mean how many state variables do you want? You define the same variable 4 times, each time with a different assignment, and an assignment to a variable or macro that you haven't defined at that.

I have the feeling you need only one state which can have 4 values: L1, L2, R1 or R2.
For this, use an enum:
enum EState { L1, L2, R1, R2 };

Now create one state variable of that type and give it an initial value.
EState state = L1;

Some other problems I see at first sight:
case L1:
  if (state == L1){
  if (button1State == HIGH){
      state == L2;
  }
}
break;

In this statement, when there is case L1, it means the code following ( until the break) is only handled when the state (because of switch(state) is L1, so you can remove the check if (state == L1). What is left is:
case L1:
  if (button1State == HIGH)
  {
    state == L2;
  }
  break;

Than you use state == L2 to set a new state. However, the == only compares two values, if you want to assign it, you have to use a single =, thus the code should be:
case L1:
  if (button1State == HIGH)
  {
    state = L2;
  }
  break;

Of course you have to do this also for the other case statements.
Tip: align your code (make the { and } aligned under each other; this will make your code readability much better.

You have not defined L1, L2, R1, or R2.  You're also redefining the int variable 'state' four times.
Try replacing:
int state = L1;
int state = L2;
int state = R1;
int state = R2;

With something like:
#define L1  1
#define L2  2
#define R1  3
#define R2  4
int state = R2;

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


text:
Im trying to get a 3 button password sequence working
I'm trying get a password system working that when you click 3 buttons in a certain order (1, 2, 3, 3, 1) then an LED will light up. But as I'm going to implement this into a larger code I can't just have the void loop() going forever to wait for it.
I think my issue is in the while loops and making it wait for one of the buttons to be pressed but I don't know how to get it to work.
thanks
#define greenLED A0
#define redLED A1

int button1 = 5;
int button2 = 4;
int button3 = 3;

void setup() {
  // put your setup code here, to run once:
  pinMode(A0, OUTPUT);
  pinMode(A1, OUTPUT);
  pinMode(button1, INPUT_PULLUP);
  pinMode(button2, INPUT_PULLUP);
  pinMode(button3, INPUT_PULLUP);
}

void loop() {
  // put your main code here, to run repeatedly:
  int total = 0;
  while(digitalRead(button1) == LOW && digitalRead(button2) == LOW && digitalRead(button3) == LOW){
    while(digitalRead(button1) == LOW && digitalRead(button2) == LOW && digitalRead(button3) == LOW){
      while(digitalRead(button1) == LOW && digitalRead(button2) == LOW && digitalRead(button3) == LOW){
        while(digitalRead(button1) == LOW && digitalRead(button2) == LOW && digitalRead(button3) == LOW){
          while(digitalRead(button1) == LOW && digitalRead(button2) == LOW && digitalRead(button3) == LOW){
            if(digitalRead(button1) == HIGH){
              total = total + 1;
            }
          }
          if(digitalRead(button2)==HIGH){
            total = total+1;
          }
        }
        if(digitalRead(button3)==HIGH){
          total = total + 1;
        }
      }
      if(digitalRead(button3)==HIGH){
        total = total+1;
      }
    }
    if(digitalRead(button1) == HIGH){
      total = total+1;
    }
  }
  if(total == 5){
    digitalWrite(A0, HIGH);
    delay(2000);
    digitalWrite(A0, LOW);
  }else{
    digitalWrite(A1, HIGH);
    delay(2000);
    digitalWrite(A1, LOW);
  }
}

you need each button pressed to push something to a stack, then examine the stack for patterns; no waiting, no blocking, no nesting, no complexity. a String could work as a stack, and it's got built-in tools to find patterns.

Without programming everything out, use something like this:

Initialization:

Create a (global) variable of string ("12331") which is the code
Create a (global) variable of int that shows the number of correct numbers so far (initially 0)

In the while loop:

Check which button is pressed
If it is the correct button
increase the int variable
If that variable is 5 (meaning all numbers ok), light up the LED
Delay
Make the variable 0 again
Clear the LED
If the wrong button is pressed
If it is equal to the first value ('1')

Set the variable to 1 (since the wrong number is the first correct number)

Else

Set the variable to 0

You can split this into two different problems, and I suggest you track
them one at a time.
The first problem is to detect the button presses. This is not as
trivial as it sounds. For once, digitalRead() tells you whether the
button is pressed, but that's not quite what you want. You want to
detect the discrete press “events”. In other words, you have to remember
the previous state of the button, and record a press event only when the
state changes from HIGH to LOW. This is called “edge detection”.
When doing this on mechanical buttons, you absolutely must do some
kind of debouncing.
I will not elaborate on this topic, as there are a few Arduino libraries
available for debouncing buttons that also do edge detection. Once you
have sorted this out, each of your buttons will have a .fell() method
that tells you whether that button has just been pressed. Then, inside
loop(), you can do something like
char key = 0;  // key pressed by the user, 0 = none
if (button1.fell()) key = '1';
else if (button2.fell()) key = '2';
else if (button3.fell()) key = '3';
if (key) {  // some key has been pressed
    // process key...
}

The “process key...” part should initially be a simple
Serial.write(c);. This way you can use the serial monitor to check
that this part of the program is working properly. Only when this is the
case you can move to the second part.
The second problem is to process the key presses in order to detect
whether the correct code has been entered. There are various possible
approaches. One of them is to store in an array the 5 last keys
entered by the user, and compare that array with the correct code to
know whether the entry was correct. This is not very elegant, as it will
require storing more information than necessary, and shifting the array
each time a new key is typed.
A more elegant solution is given by Michel Keijzers. Let me paraphrase
it in C++. Inside loop():
if (key) {  // some key has been pressed
    if (check_code(key)) {  // correct code typed
        digitalWrite(LED, HIGH);
        delay(1000);
        digitalWrite(LED, LOW);
    }
}

where the logic for checking the correctness of the typed code is:
bool check_code(char key)
{
    const char code[] = "12331";
    const uint8_t length = sizeof code - 1;
    static uint8_t i = 0;  // number of correct characters so far

    if (key == code[i]) {  // correct key
        ++i;               // one more correct character
        if (i == length) {
            i = 0;         // reset
            return true;   // report entry is correct
        }
    } else {               // wrong key
        if (key == '1')
            i = 1;
        else
            i = 0;
    }
    return false;
}

Note that the part that handles a wrong key press is specific to that
particular code. If you want the program to be generic, so that you can
change the secret code just by changing the string code, it can get
more complicated. For example, if the correct code is “12313” and the
user has so far typed “1231”, he has so far 4 correct keys. Then,

if he types 1, he now has 1 correct key press
if he types 2, he has 2 correct keys (namely “12”)
if he types 3, he completed the code.

Handling this generically requires walking back the code string and
searching for the longest possible match. Here is my take at it: replace
the else part in the function above with:
// ...
} else {               // wrong key
    for (int j = i-1; j >= 0; j--) {
        if (key == code[j]) {
            int k;
            for (k = 0; k < j; k++) {
                if (code[k] != code[i-j+k])
                    break;
            }
            if (k == j) {  // found a partial match
                i = j + 1;
                return false;
            }
        }
    }
    i = 0;  // no partial match
}
// ...

Here j is the position, within the code string, where the key typed by
the user may match.

As Edgar Bonet mentions in his answer, button debouncing is a critical component, and there are libraries available to simplify this part of the requirement. I used the Bounce2 library with three N.O. push button switches. The following sketch works, but it still needs one or two improvements.
One issue occurs if the user enters 4 button presses, then leaves and comes back in 1 hour. All they have to do press the last correct button in the sequence, then they are authenticated. This could easily be fixed by introducing a millis() based timer that starts on the first button press, and stops after 5 seconds, for example. This timer would reset the counter variable and the buttonsPressed[] byte array.
Perhaps a "enter" code button and/or a "cancel" button would be useful.
#include <Bounce2.h>

const byte sequenceLength = 5;
byte sequence[sequenceLength] = {1, 2, 3, 3, 1};

byte buttonsPressed[sequenceLength];
byte counter = 0;
const byte ledPinCodeAccepted = 2;
const byte ledPinCodeDenied = 3;
const byte button1Pin = 10;
const byte button2Pin = 11;
const byte button3Pin = 12;
const unsigned long debouncerInterval = 50;

Bounce button1 = Bounce();
Bounce button2 = Bounce();
Bounce button3 = Bounce();

void setup(){
  pinMode(ledPinCodeAccepted, OUTPUT);
  pinMode(ledPinCodeDenied, OUTPUT);
  button1.attach(button1Pin, INPUT_PULLUP);
  button1.interval(debouncerInterval);
  button2.attach(button2Pin, INPUT_PULLUP);
  button2.interval(debouncerInterval);
  button3.attach(button3Pin, INPUT_PULLUP);
  button3.interval(debouncerInterval);
}

void loop(){

  if(button1.update()){
    if(button1.read() == 0){
      buttonsPressed[counter] = 1;
      counter++;
    }
  }

  if(button2.update()){
    if(button2.read() == 0){
      buttonsPressed[counter] = 2;
      counter++;
    }
  }

  if(button3.update()){
    if(button3.read() == 0){
      buttonsPressed[counter] = 3;
      counter++;
    }
  }

  if(counter == sequenceLength){
    counter = 0;
    digitalWrite(ledPinCodeAccepted, LOW);
    digitalWrite(ledPinCodeDenied, LOW);
    for(byte i = 0; i < sequenceLength; i++){
      if(sequence[i] == buttonsPressed[i]){counter++;}
      else{break;}
    }
    if(counter == sequenceLength){
      digitalWrite(ledPinCodeAccepted, HIGH);
    }
    else{
      digitalWrite(ledPinCodeDenied, HIGH);
    }
    counter = 0;
  }
}

There is a small issue here: if the user types “1231” oops! Then “12331”, this program will not accept his input as valid. The expected behavior for any kind of keypad lock is to accept it.

Perhaps a "enter" code button and/or a "cancel" button would be useful.

Keypad locks are a very common form of user interface. This ubiquity creates user expectations, including simplicity and ease of use. If you require the user to press a “cancel” button when he oops, you are violating this expectation and thus making a poor user experience.

The OP says they are making a "password system" in the question. Is that the same as a Keypad Lock? I don't know. I don't even know what a "password system" is :) The enter/cancel buttons are very common here in Canada. Look at bank "cash" machines for example. The user is forced to press an enter button when they have completed entering their password. There is also a cancel button, and a "timeout" period where keypad inactivity causes your bank card to be ejected from the machine.

I don't know if the bank cash machine forces you to press the cancel button, then enter your passcode again, or whether you can just enter your passcode after incorrect digits and press enter.


text:
Log vs linear pots and the arduino
I have noticed that when I used a log pot from a guitar amp I found, it gives janky results when using it in a motor PWM sketch, but if I use it in a fade sketch, it works. why does log pots give sketchy results when using them in a PWM control sketch, like when using the map() function?

what does janky mean? .... please define sketchy results  .... what is the difference between linear taper and log taper pots?

not quite for sure, except that I suspect the log outputs in log increments and the linear is more direct

janky is slang for like twist the pot, then the motor goes from 0 to 255 with no increments, non linear

http://www.resistorguide.com/potentiometer-taper/

Are you asking why it seems to work better when controlling an LED rather than a motor?

well no actually in my motor pwm sketch, I have a fade like function with step and speed and there is not jumpy action with this function but with a map() pwm only, the log pot is real messy, linear no issue

linear pot no issue

thanks for the link, that might explain why with a small turn, the log pot is non linear and jumps to the high end

@Jim Print out the values ranging from 0 to 255 coming from your pot and copy it into the question so that we can see better what you mean...

There are two associated issues here that underly your problem.
Firstly, with a log pot, you get a period of very small changes in resistance followed by a period of massive changes:

(* a "commercial" log pot is how log pots are usually manufactured - two linear traces of different resistances back to back).
So when turning you get "not much ... not much ... not much ... lots ... even more ... full".
Now couple that with how a motor works. A motor has a "stall current", which is higher than the "run current" (especially the "unloaded" run current).  This is the minimum amount of current required to overcome the inertia of the motor and start it spinning. This is, in effect, a lower threshold on the PWM value that you need to exceed before the motor will begin moving (once it's started moving you can go a little below that threshold and it will still move).
With a linear pot it's easy to get to that threshold and stay around it, increasing slowly above it, etc.  However, as you can imagine looking at the curve of the log pot above, if the "flatter" area of the pot is below the stall current threshold of the motor, the motor will do nothing until you are well into the sharper up-turn of the curve.  The effect of this is you will go from "stopped" to "quite fast" in one jump. It's very very hard to get even close to the stall current threshold.
For instance, if your motor needs a minimum of 30% duty cycle to start it running, that's about a 160 degree turn on the log pot above, compared to just 70 degrees of a linear pot, and the rest of the log pot's PWM range is compressed into a tight space.

"Firstly, with a log pot, you get a period of very small changes in resistance followed by a period of massive changes:" yeah, that exactly what was happening, problem solved with a linear pot. forgot about the log study from my electronics

with the linear, even with the stall current, seems responsive throughout the range

There's a chance you may have an "antilog" pot (the pink line in the graph), which compresses most of the big changes to the left, then gives you not much after that. So you get a big jump at the beginning of the turn, then you see nothing else much for the rest of the turn.

the motor is very responive with a linear pot, and the serial monitor shows a clean transistion 0 - 255 using the analogWrite and map()

That is what I would expect.  Do a little experiment. See how far you have to turn the linear pot before the motor starts spinning, and look to see what the PWM value would be at that point. Try and do the same with the log pot.

the log sucks and I have ditched it. small turn gets a response with the linear, so changed the map() to compensate

Log pots are great for controlling things with a logarithmic response, such as audio volume, or LED brightness. And yes, they suck for anything (like a motor) that is more linear.

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


text:
Why does my Esplora only send serial data when the serial monitor is on?
I've noticed that when I'm sending serial data to my computer's serial monitor, the tx light only lights up when the serial monitor is open.  When I close the monitor, it seems to stop sending data.  Is this a normal thing?
The reason I ask is because I'm really trying to send data from my esplora to an uno, and I notice that despite (1) having the grounds of both arduinos connected and (2) connecting the esplora's tx pin (reset_lcd) to the uno's rx pin (pin 0) and the esplora's rx pin (dc_lcd) to the uno's tx pin (pin 1), the tx light on the esplora and the rx pin on the uno don't light up at all.
What could be the problem?

have you looked at the schematic of the Esplora board? .... What could be the problem? .... why do you think that there is a problem? .... you also said nothing about the actual data transfer between the Esplora and the Uno

I’m sending integers as characters from the esplora to the uno and trying to read them as integers on the uno.

that says what you are doing ..... it does not say what happens .... you really need to clarify what is happening

@jsotola: nothing happens.  The tx/rx pins don’t light up at all, indicating that no data is being transfered.  I can’t figure it out because i can’t communicate from the uno to the serial monitor while wiring the tx & rx pins.

Esplora is based on a MCU with native USB. The native USB reports connected only when it really connects. You have in setup() a while loop until the USB Serial is valid. The skech waits there for connection. Comment out the while (Serial) loop.
The TX and RX LEDs of Esplora are connected to the native USB port Serial interface. They will not light for the Serial1 interface.
You should disconnect the Uno from computer to not disturb the Serial interface with USB connection. Or use SoftwareSerial to communicate with Esplora and have debug prints to Serial Monitor.


text:
Servo make partial rotation and stop working automatically
I'm using this board in my robotic arm project:
Adafruit PCA9685 16-Channel Servo Driver (
https://learn.adafruit.com/16-channel-pwm-servo-driver/using-the-adafruit-library)
I've connected all of my servo and now I'm trying to calibrating each one.
This is my configuration:

Setup
pwm = Adafruit_PWMServoDriver(0x40);
pwm.begin();
pwm.setOscillatorFrequency(27000000);
pwm.setPWMFreq(50);

Movement
pwm.setPWM(pinPosition, 0, power);

The power is mapped using map and minPulse and maxPulse based on this data structure:
ServoSettings servo0 = ServoSettings{
   0,   // pinPosition
   125,  // minPulse
   400, // maxPulse
   125  // currentPWM
};

I'm using minPulse and maxPulse for calibration and currentPWM to store data for each servo.
Data is sended through iPhone via BLE.

My servo, start rotating from 125 to ~280 and returns to back and stopped working. I need to power off my board and move the servo from its 0 position just to make movements again.
I don't understand two things:

why the rotation is not 180° but about 45°?
why after 45° servo come back home and stop working?

I suppose that is due to a wrong Adafruit library configuration but of course I'm not sure.

Using a manual loop instead of BLE data, result is the same:
moveServo is a wrapper of pwm.setPWM(pinPosition, 0, power)
  delay(1500);
  servoMgr.moveServo(0, 90);
  Serial.println("0");
  delay(1500);
  servoMgr.moveServo(0, 125);
  Serial.println("A");
  delay(1500);
  servoMgr.moveServo(0, 145);
  Serial.println("B");
  delay(1500);
  servoMgr.moveServo(0, 190);
  Serial.println("C");
  delay(1500);
  servoMgr.moveServo(0, 220);
  Serial.println("D");
  delay(1500);
  servoMgr.moveServo(0, 250);
  Serial.println("E");
  delay(1500);
  servoMgr.moveServo(0, 280); // <<<--- here servo come back home and die.
  Serial.println("F");
  delay(1500);
  servoMgr.moveServo(0, 300);
  Serial.println("G");

The Adafruit board is powered with an external 9V battery.
Arduino is powered with USB cable.
Can be something related to voltage?
What's wrong with the library configuration?
The board now have only 1 servo attached, just for test.
These are the used servo: https://www.amazon.it/dp/B07KD6NVPM
thanks for your suggestions.

Just to check: You are not using the standard 9V block batteries?

Like this one: https://www.amazon.it/Duracell-Plus-Power-6LP3146-Transistor/dp/B004W7GYGQ/

These 9V block batteries are made for low power applications. They cannot provide much current. It might well be the problem. Please try a better power supply, for example a 9V wallwart (just to test this), or some AA batteries in series

Thanks @chrisl, I’ll try.


text:
Using Arduino audio to control an LED light
I am looking for a way to control an LED on a circuit board using audio input for learning purposes.
I have written my own speech recognition system using dynamic time warping in Python, but I would like to know if (and maybe what models if not all can do) Arduino can possibly handle the processing of a 70 by 70 O(n^2) matrix traversal with fft or dct operations on audio input divided into 10ms frames.
Any advice will be appreciated.

The Due or Tre may have enough power for this. The Yún may be able to offload it to the more powerful CPU. Every other Arduino will struggle with it.

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


text:
Funduino Joystick Shield with Bluetooth
I have a Funduino Joystick Shield (See here Funduino on Gearbeast store) which has some Bluetooth pins.
Does anyone know what pins they are connected to, and has anyone successfully connected to a BT HC-05 device using SoftwareSerial?

See Can I use a 6 pin Bluetooth module in a 4 pin socket?

Well, it turns out that the tx/rx for the board are connected to the standard pins 0 and 1 on the Arduino.
To use this, you can simply use Serial.write.
Of course, remember to take of the module when trying to upload your code.....

You don't need to remove the board when using a Atmel 32u4 based Arduino like the Leonardo.


text:
Having issue using Arduino IRQ handler in nRF51822
Could anyone please help me as I currently using nRF51822-Arduino library with a nRF51822 chip and I couldn't call the interrupt function, wakeUp().
Currently I connect the external interrupt pin to nRF51822 pin: P0_1 or arduino pin: A0 after pin transform in the nRF51822-Arduino library. Maybe I know what value should I put for the variable pin for the function below:
attachInterrupt(pin, wakeUp, CHANGE);

so that when there is an interrupt change, it will call the wakeUp() function?

Have to managed to get the example, External_Interrupter.ino, running correctly?

Reading the source code for the attachInterrupt() shows that you should use the Arduino Pin number:
https://github.com/RedBearLab/nRF51822-Arduino/blob/S130/arduino-1.6.x/hardware/RBL/RBL_nRF51822/cores/RBL_nRF51822/wiring_interrupter.cpp#L70
The Arduino Pin number for A0 is 19 according to the pin transformation:
https://github.com/RedBearLab/nRF51822-Arduino/blob/S130/arduino-1.6.x/hardware/RBL/RBL_nRF51822/cores/RBL_nRF51822/pin_transform.cpp#L64
Cheers!

Hi Mikael, what you trying to say is to put value 19 for the pin variable? I have try it but it is not working as well.

I can setup the interrupt and trigger to check whether any interrupt is coming out from the Adxl345 chip. It change between 1 and 0 but it can't trigger the Interrupt handler.

As I understand in Arduino, for example Arduino Uno digital pin 2 and 3 is for interrupt and the "pin" variable should put to 0 when using D2 and 1 when using D3.


text:
Re-use smartphone/tablets parts like a camera
For learning and hacking purposes, I plan to study and use parts from smartphones and tablets like Galaxy or iPhone. They are really efficient and pretty cheap...
Did anybody do this before? If yes, can anybody tell me what kind of connector is this one on the galaxy camera, Galaxy Tab S 10.5 Front Facing Camera (Wi-Fi), and whether it can be found for attaching it to an Arduino project?
Edit: Someone else asked a similar question here, How to reuse quality camera from old / broken phone.

People might also be interested by these links :
http://www.chipworks.com/sites/default/files/Apple_iPhone_6s_A1688_Smartphone_Chipworks_Teardown_Report_BPT-1509-801_with_Commentary.pdf

https://raspberrypi.stackexchange.com/questions/22963/using-other-camera-modules-to-build-custom-webcams
http://pinouts.ru/forum/index.php?topic=5111.0

The connector on the flex circuit from that camera was made by Hirose (it has an HRS logo on it), and might be in the BM10, BM14, or BM20 series.  You can measure the pin spacing, stacking height, etc. to check which series it's in.  For example, the Hirose BM14 series of FPC to board connectors has pins at 0.4 mm Pitch and 0.8 stacking height.
Mouser.com carries a 24-pin BM14 connector that might mate or match with the pictured connector.  For other photos of Hirose FPC connectors, see google images for hirose fpc.
While you probably can find a matching connector (via careful measurement and perhaps some trial and error) and build an interface, it may be difficult to use the camera once it's hooked up.  Most Arduino models have too little RAM to support image processing.  A Yun might do it, a Tre, or some other micro entirely, eg Beagle or Raspberry.

As a side question, how do you know how much RAM such a camera requires ?

@Charaf, I don't know what protocol that camera uses.  On some, the readout rate is 40 MHz, ie too fast to process in realtime on most Arduino models, but if a camera has a readout the Arduino can clock, and if your image processing can go line by line or is concentrated on a small region of the whole image, you might get by with a few thousand bytes.   For whole-image processing, having a few megabytes of RAM is helpful.

The ballpark RAM required for video processing is a product of the size of the image. A camera which outputs a 30fps 640x480 image would take a minimum of 6404803 bytes = 920 kB per frame. This is already orders of magnitude more than the Atmel-based arduinos have. In addition, the CPU and buses must run faster than the data coming in, which is 6404803*30 bytes per second = 27.6 MB/s, i.e. greater than 27.6 MHz. So in summary, video processing requires closer to a "computer" than a "microcontroller", simply because of the size of video. FPGAs are a whole different story.

As a second side question, i found the iPhone 4S Rear-Facing Camera really really cheap here http://www.repairsuniverse.com/apple-iphone-4s-camera-replacement.html … But given that it's Apple featured, do you think there is a chance for the signal to be encrypted so that we could not reuse this part ?
@cortices : understood. Better use it in conjonction with a raspberry, may be.

@Charaf, the price is for a reason -- it gives you no help with decoding the signal from the camera. It's not that it's encrypted per se, just that the details of the output protocols of these proprietary camera chips are usually not public, and even if they are, it is infeasible to implement it yourself.

(summary of comment thread)
I strongly recommend against trying to use any of these smartphone camera replacement parts. While they are cheap, this is because the signal they output is nigh impossible for you to use, even if you knew its specifications, which is unlikely given proprietary parts often have proprietary, non-public protocols. Even if you did have it, you'd likely have to implement a linux kernel extension for Raspberry Pi yourself to support it. Far more work than it's worth.
If you actually want to do image processing, there is a clear recommendation: the Raspberry Pi camera interface. RasPis have a special flex socket on the board for a camera, and you can buy cameras which work with the raspivid etc. commands included in raspbian with no extra setup. This allows you to use OpenCV or similar image processing libraries, or write your own, without having to worry about bitbanging obscure camera protocols.
No-name camera boards can be bought from eBay or similar sites for less than US$20, and they support 30fps 5 MP image/video capture to the Raspberry Pi natively and easily. Just search for "Raspberry Pi camera".
However...
If you're really sure you're up to the challenge of hacking a proprietary camera module, you'll want to do thorough research finding the exact protocol specifications for these camera chips first, and try to find ones that are the most common, for the highest chance of compatibility, and likelihood of others having made progress on using them. Good luck!


text:
Delay function broken?
I noticed timing inconsistencies in my project, and further debugging pinpointed it to the problem below. The text should be updating every second, but the returned values are >> 1000ms.
To clarify, the text is not showing up every second.  The delays between texts vary according to fluctuating start and finish values.
I'm using a Teensy 3.2. Changing the baud rate doesn't help.
Is my timing crystal busted? Is there a serial buffering issue? I don't know how to fix either of these.

Any help would be appreciated!
Edit:
Here's the code if anyone wants to test.  I found that adding more delay functions screws the output up in completely unlinear ways.
unsigned long start, finished, elapsed;

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

void loop() {
  Serial.println("Start...");
  start = millis();
  Serial.println(start);
  delay(1000);
  finished = millis();
  Serial.println(finished);
  Serial.println("Finished");
  elapsed = finished - start;
  Serial.print(elapsed);
  Serial.println(" milliseconds elapsed");
  Serial.println();
}

Edit #2:
I thought it was worth showing everyone this screenshot.  It looks like delay(1000) just isn't functioning at all.

Edit #3:
I debugged it with an LED and it blinked at exactly 1s intervals.  It seems like delay(1000) works, so the problem must be related to the serial buffering.  I also updated my software but that didn't help.
Edit #4:
New developments from further debugging:

The problem is not reproducible on a different computer.  The Arduino serial monitor on other computers displays correctly.
Updating to the latest OSX, arduino IDE, and teensyduino did not help.
Terminal 'screen' command surprisingly prints correct serial communication.
Serial monitors from 3rd party apps, like CoolTerm and Arduino IDE do not work.

I don't know what the problem is but recommend you try grouping all the println statements together, and likewise the start=/delay/finished=/elapsed= statements, and see if that makes any difference.  If so, edit question and say so.  Also, it's a good idea to include in your question code that can be cut and pasted (so people can run tests) instead of just a picture of the code.

Yes, please edit your question and post the code into it. Indent it using Ctrl+K. I have trouble believing that 23005 - 11004 = 1000 - as shown in your screenshot.

@NickGammon, I'm having trouble believing it also.  I have no idea why this is happening.

Well, that is nothing to do with a crystal, right? 23005 - 11004 is not 1000, so that code couldn't have printed that.

In most languages statements that output data, such as print, tend to take a fair amount of time, so actually wouldn't expect finished - start = 1000. (sorry @NickGammon I know you have proved me wrong) but in general in this sort of experiment it might be better to write to variables and print at the end of the loop.  It is probably the serial buffer on your host being full causing you problems, Nick hasn't got this problem, different terminal program? Try recoding and see.

I'm not much of an expert on the Teensy internals, but on something like the Uno the serial output would be placed in a buffer, and (if not too long) would be output by an ISR during the delay(). Thus the serial printing shouldn't slow down the interval much. It would be better to get the start time, do the delay, get the end time, without any intervening serial prints, in case this wasn't true (re-order slightly).

Looks like delay just isn't functioning at all. - on what grounds? You print at the start and end of loop so you expect the end time twice, right? Which is what you get. The next time is sometimes 1000 ms later, and sometimes 2000 ms (and once 4000 ms) which is kind of weird.

What version of the IDE are you using?

Arduino 1.6.5
Teensyduino 1.25
thanks for helping :)

I don't have a 3.2 Teensy. If no-one else can help I suggest posting on the Teensy forum.

Have you tried with the code everyone is suggesting (i.e put the println all together)? If not, try with void loop() { start = millis(); delay(1000); finished = millis(); Serial.print("Start "); Serial.println(start); Serial.print("Finished "); Serial.println(finished); }

Yes, I have tried moving serials to the end.  This helps by lowering the amount of glitching serial prints, but the problem still remains.  Please look at 'Edit #4' for new info I found.

After correcting the syntax error (missing semicolon) I tried your code on my Teensy 3.0. The results look OK to me:
Start...
1250
2250
Finished
1000 milliseconds elapsed

Start...
2250
3250
Finished
1000 milliseconds elapsed

Start...
3250
4250
Finished
1000 milliseconds elapsed

Start...
4250
5250
Finished
1000 milliseconds elapsed

Start...
5250
6250
Finished
1000 milliseconds elapsed

Start...
6250
7250
Finished
1000 milliseconds elapsed

Start...
7250
8250
Finished
1000 milliseconds elapsed

Start...
8250
9250
Finished
1000 milliseconds elapsed

Since the code you posted doesn't compile, can you re-test please with your posted code, assuming you add in the semicolon, and put a space before "milliseconds elapsed".

Further down my test I see this:
Start...
153258
154258
Finished
1000 milliseconds elapsed

Start...
154259
155259
Finished
1000 milliseconds elapsed

Start...
155259
156259
Finished
1000 milliseconds elapsed

Now are you talking about the "creep" in the start time? That doesn't totally surprise me, because the rest of the code must take some time to execute.

I know this isn't an "answer" per se, but I can't post this much information into a comment.

I tested the posted code (w/ syntax correction), and got the same results.  I'm not worried about the creep, that's to be expected.

Since the subtraction's result (finished - start) displays alright, it means the right number is being stored in the variable, so it's Serial that is screwing up the task of printing it. Try reducing the baud rate to 9600 and try again.

Changing baud rates doesn't help :/

Oh, must have missed that in your post...have you tried just printing numbers (at least 6 digits) instead of millis() to see if this problem applies only to millis or to all arguments

It applies to all arguments.  I learned that the problem is independent of the hardware and must be computer related.  Check out edit #4 for more info.


text:
multiple graphs on serial plotter
I'm trying to  run an Arduino code that simultaneously:
1) blinks an led on-off every 3 seconds
2) gets a voltage input from an EMG sensor and positions a servo motor accordingly
While I run this program, I'd like to plot the following on the same graph
1) LED status on/off printed as 600 if on and 0 if off
2) EMG value being fed to the arduino
3) The angle the Arduino is sending to the servo motor
I wrote the following code which works to an extent but the problem I'm facing is, I only get two graphs on the plotter instead of 3, I think the EMG value and the angle have combined into a single line as seen in this picture:

However, if I remove the angle print statement, I get a proper graph for the other 2 as this:

How do I change my code so I can plot all three separately?
Thanks in advance.
#include <Servo.h>
Servo myservo;
const int ledPin =  LED_BUILTIN;
int ledState = LOW;
unsigned long previousMillis = 0;
const long interval = 3000;
int led=0;
int servovalue=0;
void setup() {
  Serial.begin(9600);
  myservo.attach(9);
  pinMode(ledPin, OUTPUT);
}

void loop() {
  int sensorValue = analogRead(A0);
int angle = map(sensorValue, 0, 1023, 0, 180);
myservo.write(angle);
Serial.print(sensorValue);
Serial.print(“ ”)
Serial.println(angle);
delay(15);
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;
    if (ledState == LOW) {
      ledState = HIGH;
      led = 600;
    } else {
      ledState = LOW;
      led = 0;
    }
    digitalWrite(ledPin, ledState);
  }
  Serial.print(" ");
    Serial.println(led);
}

Paste the code in a format that we can actually copy and test. And also embed the images instead of linking them. They will be removed from their current location some day, and this question will be useless to other people having similar issues as you have.

The part of your code that prints data to the serial looks like this:
void loop() {
    (...)
    Serial.print(sensorValue);
    Serial.print(“ ”)
    Serial.println(angle);
    (...)
    Serial.print(" ");
    Serial.println(led);
}

The bug is in the Serial.println(angle); line. The println method inserts a "newline" character at the end. Try changing it to Serial.print(angle); so there is only one "newline" character.
void loop() {
    (...)
    Serial.print(sensorValue);
    Serial.print(“ ”)
    Serial.print(angle);
    (...)
    Serial.print(" ");
    Serial.println(led);
}


text:
Removing CH340g chip from Arduino Nano clone.. any issues?
In trying to figure out how to solve another problem with Arduino Nano clone using CH340 chip, I was just now wondering, would there be any issues if I were to simply remove the CH340 chip? As it stands, I have the slight suspicion that the chip itself might be causing some problems with communicating using only the Tx Rx pins, could this be the case? More importantly, can I just remove the chip with no issues (other than the already lacking ability to use it as USB-Serial bridge)? In a working board, would removing the chip cause any other problems?

If you are not going to use the chip, can't you just ignore it?

@NickGammon, the reason is because I have a feeling it is actually defective and interfering with communication over the TxRx pins. See the linked question for a little background on that.

No problem whatsoever as long as you aren't powering the board over USB. You may still be able to do that though depending on what role the CH has in managing the power.
Personally I think all CH chip should be removed from all boards. They are horrible chips and cause no end of problems.
I assume you have an FT232 adapter board (or similar) to then use for the programming of your Arduino.

You could probably get away with just removing 3 legs - Tx, Rx, and DTR. The rest don't anything.
The pins are rather far apart, you could heat them one at a time gently pry/lify up with tweezers too. Better than a knife I would think.

Once I removed a burned ch340 from a dysfunctional uno, and it didn't brought it back to life, I couldn't program it by other means, because reset remained shorted to ground. It might have other problems, but I still recommend digging more into the problem (eg. Check the diagram for your board)

Looking at the datasheet, I see no problem with removing it.
I'd suggest using a sharp knife and cut all the pins, one at a time, right where they come out of the black epoxy. Make sure you don't accidentally stab into the PCB. Remove the main body of the chip. After that, remove the legs still attached to the PCB, one by one, using a soldering iron.


text:
Range of Offset Value in pH sensor module?
In finding the pH value of a liquid/Soil, what is the range of Offset voltage value that I can use in my code?
Using / calibrating pH sensor module
I considered the above link as a reference. But I didn't come to know the range of Offset Value...
Here is the logic below to find the value of pH right...
avgValue = 0;
for (int i=2;i<8;i++)       // take the average value of 6 center sample
avgValue+=buf[i];

float phValue = (float)avgValue*5.0/1024/6; // convert the analog into millivolt
phValue=3.5*phValue+Offset;

What is the range of Offset value can I use in the above/my code?
Thanks in Advance

I think you would need to test it by testing known value solutions with your sensor.  It is probably going to be different between different instances of the sensor so each will need calibrating in this way.

I tested it for water of pH 7.0. It's showing a value of 10.5 units. So, I considered -3.5v as an offset value..While considering offset value as -3.5v, I got a doubt that is there any limited range for an offset value to consider

It is doubtful any ADC / sensor combination is exactly linear, of the correct magnitude, slope and w/o noise.  How precise / accurate your application needs to be should dictate your efforts.  My next steps would be to plot know acid and bases to resolve these questions.

I don't think you mean -3.5v, because the voltage range you are measuring is 0-5v.   At the moment all you know is when the variable phValue = 10.5 then the pH of the liquid is 7.0.  Like st2000 says you now need to pad out your calibration table  what does pH 1 make your device read?  pH = 2 ? etc.  Then you will get a table that says when the sensor reads 3.9 it means pH = 1, when it read 5.2 it means pH=2, when it reads 4.9 it means about pH 1.8.

Something you may also want to consider is what happens if one reading is massively different to the other 5 readings.  It probably indicates a sensor fault for that reading, but it will move your answer towards pH=1.
I don't think you should be dividing by 1024.  This division will loose some precision in your reading and therefore it will make you calibration table less accurate.

After doing a lot of Calibrations, I used offset value as -4.0, For Solution of pH 7, its showing the value same as 7.0.. for pH solution of 4.0, its showing 5.2(4.0+1.2)... for pH solution 10, its showing 8.8(10-1.2).. To get correct values for pH solutions of 4 and 10, What I need to do?

When converting real world sensor measurements into usable data there are several issues to consider:

Noise from any number of sources such as (unavoidable?) long cables and power supplies to name two.  Consider using exponential averaging to minimize the effects of noise.  If the noise if predictable consider sampling only when the noise is absent.
Slope of the data is important when converting to known scales.  For example the slop of the resistance of a thermistor verses heat may not have the same slope as the temperature in Celsius verses heat.  Simply multiply by the appropriate constant to correct for slope error.
After you correct for slope the values may still not be correct.  When all values are equally less or more then the expected values an offset is required.  Simply add or subtract the appropriate constant to correct for offset error.
Linearity is often corrected using lookup tables.  Linearity is a measure of how closely the sensor tracks the physical value being measured.  For example, after slope and offset corrections, a thermistor measurement may appeared curved when compared to the actual temperature in Celsius.  For this final correction the sensor measured value is used to index into a lookup table which returns a correction value.  Interpolation is used to control the size of the lookup table when space is a consideration.


text:
In UART, what mechanism sets the "new data received" flag back to 0?
I was reading documentation on UART on AVR and it looks simple: when a flag (bit RXC0 of register UCSR0A) is set to 1, it means the micro controller has new data for you, and you read this from register UDR0.
But something boggles my mind: How does the micro controller know that we have read the data? Or, in other words, after it received the first byte on UART, the flag is set to 1, but when is it set back to 0?

can someone explain the -1 ?

I'm not sure I understand it either. He indicates that he's been reading the documentation and is puzzled by it. The learning curve here gets steep very fast in places.

What you read is not the documentation, it is a simplified tutorial. Maybe take a look at the datasheet... I would imagine that the UDR0 register is hardwired, so that when it is read (and the "READ" line goes active) then the "latch" on the RXC0 flag is cleared (by the same "READ" line going active). Have a look at some UART design documents, and/or "State Machines".

The ATmega328p data-sheet describes the setting of RXCn:
Bit 7 – RXCn: USART Receive Complete

This flag bit is set when there are unread data in the receive buffer and cleared when the receive buffer is empty (i.e., does not contain any unread data). If the Receiver is disabled, the receive buffer will be flushed and consequently the RXCn bit will become zero. The RXCn Flag can be used to generate a Receive Complete interrupt (see description of the RXCIEn bit).

The hardware seems to keep a register the size of the receive buffer. Incremented when received and decremented when read. It is only one level so the size is 0..1, i.e. one bit.
Actually there is two registers; one for possible incoming data and one for the latest data until read.
Cheers!
More details in ATmega328p data-sheet, chap. 19 USART0

So the micro controller actually tracks all myvariable = UDR0 or f(UDR0) ?! this doesn't seem uncanny ?

It is the implementation of reading UDR0 that is "special". There is no special instruction or tracking by the compiler. The hardware does this. Think of it as a hidden bit parallel with the data register.


text:
CLion + Arduino
Please, help me to set up Clion + Arduino.
Clion has an Arduino plugin which I've installed. Here is some instruction on Github but I'm fully noob about cmake and other things which are talking about in instruction. I have only used Arduino IDE before for my simple projects. Now in CLion I can create an Arduino projects but autocompletion doesn't work. Actually it works but does it on true C, not for Arduino code.
So if you can please explain like for complete idiot, what I should change to get working Arduino autocompletion.

What do you mean by Arduino autocompletion?

look here

It can't autocomplete what it doesn't know about. Have you installed all the libraries correctly according to what the plug in requires? (Try to compile the Blink example included with the Arduino IDE, do you get any errors?)

If u explain how to do, I will do it.

For anyone reading this now, Jetbrains has a very detailed blogpost on how to do this

Rather than using any plugin, I am using CLion with PlatformIO, which supports several IDEs. CLion then not only gives you code completion, but also full support for refactoring, Git, and much much more.
From its documentation:

[...] generate project via platformio init --ide command:
platformio init --ide clion --board %TYPE%

# For example, generate project for Arduino UNO
platformio init --ide clion --board uno

Then import the project in CLion and you're about done.
Some hints:

Make sure your code is in the src folder, and that the main file has a .cpp extension.

For other files: either rename all .ino files to use .cpp, or tell CLion to associate the .ino extension with C++ files. (Preferences, Editors, File Types.)

Whenever adding libraries to the lib folder (and using #include to refer to them), just run the above init command again.

If you're using ESP-boards and changed platform.txt for an alternative esptool, then note that PlatformIO needs a different hack.

Rather than using the CLion Serial Monitor plugin, I simply use a Terminal within CLion to upload and start the monitor as soon as possible:
pio run -t upload; pio device monitor -b 115200

If you always want to upload and monitor whenever using pio run, then add:
[env]
targets = upload, monitor
upload_protocol = esptool
upload_speed = 115200
monitor_speed = 115200

Nowadays, CLion has a PlatformIO plugin as well, including a menu Tools, PlatformIO with commands such as Re-init.

thanks for your informative answer. it helped me quite a bit. just one thing: could you further elaborate on the last bullet point? how do you open custom terminals? does that command work on all platforms or just linux? thanks in advance

@Neuron, in CLion on a Mac it's menu View, Tool Windows, Terminal. (On a Mac, the built-in bash shell is also called Terminal.) But there's no real difference with using a standalone terminal window, except for having all in one place, and it conveniently defaulting to the project's folder. As for the pio command: I only used it on a Mac, and it's exactly the same as platformio. (Both are installed when installing PlatformIO.)

you opened a whole new world to me! thanks ^_^

Thanks a lot, uploading code works for me! But not serilaports, it says:
> pio serialports monitor -b 115200
Error: No such command "serialports"

Okey, it is platformio device monitor now

But CLion don't see dependencies which I add with pio lib install --save {lib_name} Any ideas how to fix that?

@invis, doesn't the 3rd bullet point work for you?

@Arjan hmm, actually pio init with argumets helps. My lib directory is empty, thats why I was confused. pio adds dependencies to his own directory named .pio/libdeps

I know this was asked a long time ago, but maybe it will be useful for someone. I'm a beginner, regarding all this stuff, so if anybody knows a better way to do it, please correct me. here is how I set up CLion for Arduino (on Windows 10):
CLion 2016.1.3 + Arduino 1.6.9 + plugin

Download and install the official Arduino IDE (1.6.9).
Download and install MinGW to 'C:\MinGW'
In MinGW, install: 'mingw32-base' and 'mingw32-gcc-g++'
Download and install CLion.
Create an 'untitled' project, just to open CLion.
In CLion > Settings > Plugins > Browse Repositories > Search for and install: 'Arduino' (tools integration), and 'Serial Monitor' (misc).
In CLion > Settings > Search > type 'MinGW'
At the environment select 'Use MinGW home', and browse to MinGW folder ('C:\MinGW'). Press apply, and wait until CLion finds the environment.
In File > Close project.
Open any file manager and go to 'c:\Users\name\ClionProjects\' and delete the 'untitled' project you just created.
Open CLion, select 'New Arduino sketch project'
In the project directory > 'open cmakelists.txt' and configure lines:
6: set board version
7: set port (you can find out port# from the Arduino IDE)
8: set the path where you installed your Arduino libraries (Arduino sketch folder)

set(${CMAKE_PROJECT_NAME}_BOARD uno)
set(${CMAKE_PROJECT_NAME}_PORT COM3)
LINK_DIRECTORIES(c:\\ARDUINO\\libraries)

In the upper right corner in CLion, near the green 'Play' button, select 'Edit Configuration', on the left select 'Application' > 'Upload', and set:
-target: 'upload'
-configuration: 'debug'
-executable: the project name

then press ok.
In the project .ino file, write some really simple code (blink).
Connect an Arduino Uno via USB, and press the green 'play' button to upload the sketch.
To start serial monitor:

In CLion main window bottom left, click serial monitor tab (in 'the tool buttons')
Click the wrench icon to set up port and baud rate.
On the top of the wrench icon, click the blue 'connect' icon.
If values did not appear 'correctly', click the white 'switch to hex' icon (on the right of the wrench).
Before uploading sketch, disconnect the serial monitor.

For CLion to properly find the libraries, make sure to use the same name for the lib folder as for the '.h' file. example: for DallasTemperature.h use folder name DallasTemperature. After #inlcude-ing new libs, right click on 'External libraries folder' and select 'Reload cmake project'.
You may want to do further configuration in CLion settings like: theme, colours, text size, etc.
Also, you can configure some handy 'live templates', like: serialprintln, digitalwrite, pinmode, switch, etc. to enhance your productivity.

Its very nice tutorial dude, thx very much but unfortunately Im using linux (. Instead of mingw what should I install?

sorry, i don't use linux, have no idea about it.

@Kvach you will need to install cmake, gcc, git.

Thank you! This is the best way to do it for windows


text:
When using an Arduino as an ISP, is the capacitor required or not?
Looking at Arduino as ISP and Arduino Bootloaders, it is stated

The 10 µF electrolytic capacitor connected to RESET and
  GND of the programming board is needed only for the boards that have
  an interface between the microcontroller and the computer's USB, like
  Mega, Uno, Mini, Nano. Boards like Leonardo, Esplora and Micro, with
  the USB directly managed by the microcontroller, don't need the
  capacitor.

Some of the Fritzing diagrams show the electrolytic capacitor connected between the RESET and GND pins:

But it is not shown in all of the images on that page.
Nor it is shown in this image from Nick Gammon's Atmega bootloader programmer (see original image):

So, is the capacitor really needed, when using a Mega or Uno as an ISP, and if so, why exactly?

I was wondering after having written this answer to the question How to install new ATMEGA firmware via the ISP pins? for a 3D Printer control board.

The purpose of the capacitor is to prevent the "master" Arduino (the Mega in the first image above) from resetting when the serial port is opened.  If that board resets, then programming fails.
There are many ways of preventing that reset - some more permanent than others - but the capacitor trick is one of the simplest.
So yes, you do need the capacitor unless you have made other modifications to prevent the reset.
I think the purpose of the second image is more to illustrate how to use the ICSP headers and where to connect the target's reset pin on the master. It is to be seen as complementary to the first image.

Edit:
It seems what you are using is not Arduino As ISP, but instead something written by Nick Gammon that acts as a standalone programmer.  The rules for Arduino As ISP do not apply in this case. Since you are not programming via the master Arduino (as you would with Arduino As ISP) there is no need to prevent the master from resetting.

Here's a little history about the auto-reset system:
Originally, when the Arduino used the FT232, the DRT signal would reliably reset it automatically. The operating system (all operating systems) would automatically assert DTR when the port was opened, and all was well.
Then, out of the blue, and without telling anyone, Future Tech removed that auto-DTR asserting from the FT232 driver for Windows. Since Windows doesn't control DTR for you, but leaves it up to the driver or the software (and all other operating systems automatically control DTR for you - Windows has to do the opposite of everyone else - it's in their remit...!) all of a sudden the boards stopped resetting properly for programming.
So Arduino added specific reset code into the IDE to get around the problem (interestingly enough: if you watch the DTR pin on Linux you see it being asserted multiple times when programming - both the OS and the IDE are toggling it).
But then Arduino moved to the ATmega8U2 (and later the ATmega16U2) chip which uses the standard CDC/ACM instead of the custom FT232 driver. Now the auto DTR assertion was working again, but they kept the manual assertion in the IDE to cope with older boards in Windows.
I guess they didn't put the DTR assertion workaround in the bootloader programming code since you don't really want DTR asserted at that point anyway.
So if you have an FT232-based Arduino and are running Windows I guess there is no need for the capacitor, since DTR won't be asserted by the OS.
However in Linux and OS X, regardless of the USB chip, you will need the capacitor, since it will always assert DTR.
But then along came China and threw the CH340G into the works.  Now we have a third option, with dodgy drivers from who knows where. And who has the slightest clue what they do? Do they assert DTR for you? Your guess is as good as mine.  If it doesn't, then you won't need the capacitor. If it does, then you will.
It's all such a mess now thanks to too many options and combinations.  It's simpler just to have the capacitor regardless, since it won't stop it working if it's not actually needed in your specific configuration.

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

If you're using Nick Gammon's programmer, the RESET signal to the target board comes from the Arduino programmer - from Pin 10. Read his instructions:
https://www.gammon.com.au/bootloader
You modify the 6 pin cable as shown on his website.


text:
Servo position is always changing
When I send an SMS like this:

Tilt:090
Azimuth:120

First time an SMS is read, the servo rotates to the correct position, but after they change a small angle, it's like noise.
I do following things to stop that change:

First try with motor driver

Capacitor circuit use

Here is my code:
#include <AFMotor.h>
#include <Sim800l.h>
#include <SoftwareSerial.h>
#include <Servo.h>

Sim800l Sim800l; //to declare the library
Servo Tilt;
Servo Azimuth;

String text; // to storage the text of the sms
uint8_t index; // to indicate the message to read.
int t, pos, old_pos, pos1, old_pos1; // to indicate the int value.

void setup()
{
    Tilt.attach(9); // attaches the servo on pin 5 to the servoH object
    Azimuth.attach(10); // attaches the servo on pin 6 to the servoV object
    Serial.begin(9600); // only for debug the results .
    Sim800l.begin(); // initializate the library.
    index = 1; //  position in the prefered memory storage.
}

void Tilt_servo()
{
    if (old_pos > pos) {
        for (int q = old_pos; q > pos; q--) {
            Tilt.write(q);
            delay(20);
            Serial.println("position dicreasing");
        }
    }
    else if (old_pos < pos) {
        for (int q = old_pos; q < pos; q++) {
            Tilt.write(q);
            delay(20);
            Serial.println("position increasing");
        }
    }
    else {
        Tilt.write(pos);
    }
}

void Azimuth_servo()
{
    if (old_pos1 > pos1) {
        for (int d = old_pos1; d > pos1; d--) {
            Azimuth.write(d);
            delay(20);
            Serial.println("position1 dicreasing");
        }
    }
    else if (old_pos < pos) {
        for (int d = old_pos1; d < pos1; d++) {
            Azimuth.write(d);
            delay(20);
            Serial.println("position1 increasing");
        }
    }
    else {
        Azimuth.write(pos1);
    }
}

void loop()
{
    delay(1000);

    Serial.println("---------------------------------------------------------------------------");
    old_pos = pos;
    old_pos1 = pos1;

    Serial.println("old_pos:");
    Serial.println(old_pos);
    Serial.println("old_pos1:");
    Serial.println(old_pos1);

    text = Sim800l.readSms(index);
    Serial.println(text);
    String W = text.substring(33, 45); // filter phone number...
    Serial.println(W);
    String y = text.substring(20, 30); // filter REC UNREAD
    Serial.println(y);

    if (y == "REC UNREAD") {

        String s = text.substring(74, 79); // filter the "Tilt:"
        Serial.println(s);
        String p = text.substring(79, 82); // filter the position
        int t = p.toInt(); // convert position as int value
        Serial.println(t);
        pos = t;

        String v = text.substring(83, 91); // filter the "Azimuth:" letter
        Serial.println(v);
        String u = text.substring(91, 94); // filter the position as string
        int b = u.toInt(); // convert position as int value
        Serial.println(b);
        pos1 = b;

        if (s == "Tilt:" && v == "Azimuth:") {

            Tilt_servo();
            delay(1000);
            Serial.println("done....Tilt...");
            Serial.println(pos);
            Azimuth_servo();
            delay(1000);
            Serial.println("done....Azimuth...");
            Serial.println(pos1);
        }
        //Sim800l.delAllSms();
        //delay(5000);
    }

    else {
        Tilt.write(pos);
        Azimuth.write(pos1);
    }

    delay(1000);
    Sim800l.delAllSms();
    delay(5000);
    Serial.println("---------------------------------------------------------------------------");
}

you need to start troubleshooting by writing minimal code that positions one servo, holds position for a second or so, then positions servo to another point and holds again .... test all servos that way

i tested all servo.then they all work correctly. but above code running it start the same problem

comment out lines like this Serial.println("position1 dicreasing"); ... see if that may clear it up ... btw, the word is "decreasing"

i tested. in these two lines executed that error happen.so it can be affect sim800l library.    text = Sim800l.readSms(index); and Sim800l.delAllSms();


text:
LED fading effect using a push button
Guys please help me out in verifying my program for my project -- led fading effect using a push button.
My project is simple, I want to start the LED fading effect (i.e., glowing and dimming one after another) at one click on the push button that is pushing and then leaving the push button and on my another click I want the effect to get off.
The main problem is coming in the programming part and rest all the circuit and components are fine.
THIS IS MY SKETCH :-
int ledpin = 9;
int buttonpin = 8;
boolean buttonpressed = false;   // to check whether the button was pressed //
int brightness = 0;
int fadeamount = 5;

void setup ()
{
pinMode (ledpin, OUTPUT);
pinMode (buttonpin,INPUT);
digitalWrite (ledpin,LOW);
}

void loop ()
{
if ( digitalRead (buttonpin) == HIGH)
 {
  buttonpressed = true;
 }

 else {
     if ( buttonpressed = true && digitalRead(ledpin) == LOW)
       {
           brightness = brightness + fadeamount;
           if ( brightness == 0 || brightness == 255)
            {
             fadeamount = -fadeamount;}
             analogWrite(ledpin, brightness);
             delay (30);
             buttonpressed = false;
        }
      if (buttonpressed == true && analogRead(ledpin) == brightness)
        {
          digitalWrite(ledpin,LOW);
          buttonpressed = false;
        }
   }
 }

THIS IS THE CIRCUIT DIAGRAM

Where's the resistor on your LED?

digitalWrite (buttonstate,HIGH); - What is that supposed to achieve?!

int fadeamount = 51; - That's a huge amount to fade by...

bro brightness doesn't matter i can change it any time to 5 or something low.......and about digitalWrite (buttonstate,HIGH); i used it to let the button state as high even after i leave the pushbutton so that the LED doesn't get off !!

i used it to let the button state as high even after i leave the pushbutton so that the LED doesn't get off !! well it doesn't. I don't know how you thought that might work. You're actually writing HIGH to either pin 0 or pin 1.

I think you meant to write buttonstate=HIGH; instead of digitalWrite (buttonstate,HIGH);

yep i got it wrong there...

@electromaniac That button is absolutely wrongly wired.... My suggestion, however, is to use a reverse logic: wire the button between pin 8 and ground, get rid of the resistor, then enable the internal pullup (pinMode(pushbutton,INPUT_PULLUP);). When you are reading the button, just invert the logic (digitalRead == LOW means that the button is pressed). Then I suggest you to use the Bounce2 library to debounce the button (search for it on google). And then, there are lots of problems (for instance brightness = 0 should be brightness == 0)

Your pull-down resistor on your button should be on the other side of the switch, and 1K is too low. You'll waste power. Use a 10K resistor instead. Or, as the other poster said, skip the resistor, invert your logic, and use INPUT_PULLUP mode.

I changed things a bit and got a solution
int led = 3;
int buttonpin = 8;
boolean waspressed = false;

int inertia = 10;

void setup (){
  pinMode(buttonpin,INPUT);
  pinMode(led,OUTPUT);
  analogWrite(led,0);
}

void loop(){
  if(digitalRead(buttonpin) == HIGH){
    waspressed = true;
  }else{
     if (waspressed == true){
       fadeLed(digitalRead(led), inertia);
       waspressed = false;
     }
  }
}

void fadeLed(boolean input, int inertia){
  for(int state=0;state<256;state++){
    if (input==LOW){
      analogWrite(led, state);
    }else{
      analogWrite(led, 255-state);
    }
    delay(inertia);
  }
}

I created a function called fadeLed that receives two arguments: The actual state of the led and the delay - in miliseconds - that is going to determine how long the fading is going to last.
You can see that the rest of the code is pretty much the one you got in the other question you asked. This is because we already got a good code to control the behavior of the button, so its a good practice to keep it and just change what you want to be changed: to fade instead of blink. So we just change a single line and create a function to be called by that line. Functions are a good way to keep a clean code and are a good programming practice. They make the code easy to read and maintain.
The function fadeLed() uses PWM to fade the led. In Arduino Uno, PWM is available in digital pins 3, 5, 6, 9, 10, and 11. This may change according to the model you are using. It's very important to understand PWM so you can know why analogWrite() is used in a digital pin.
If you check the documentation of analogWrite(), you are going to see that for most of the Arduino boards the default resolution is 8 bits, i.e, 0 to 255. To use all this 256 values to fade the led, a for loop is used. If you are not used to for loops, I strongly recommend you to read the documentation.
The for loop is programed to go through 256 iterations - the variable state going from 0 to 255. At each iteration, the value of state is incremented by 1. When state gets to be equal to 256, the loop ends itself. Every iteration verifies the value of input, which is just the state of the led when the button was released. This value is passed to the function only when the button is released, but the function uses it internally at every iteration. If input is LOW, it means that the led was off, so analogWrite(led, state); uses the value of state - increasing at every iteration - to fade the led, turning it on. If input is  HIGH, it means that the led was on, so analogWrite(led, 255-state); will fade the led turning it off. In this case, 255-state is just a way to set a range starting at 255 and ending at 0 while using a range that we already have - state - that starts at 0 and ends at 255.
The last line is just to set how long the fade action is going to last. To be more specific, delay(inertia) determine how long each iteration is going to last. So, when you set inertia to 10, will you see that fading will take 10(miliseconds)*255(iterations) + execution times =~ 2,6 seconds. I chose this name when I was coding and I'm not sure now if it was the better one. Maybe something like duration will have a more clear meaning. If you want to set the duration of the fade on your code - instead of the duration of each iteration - you can to something like
int fadeDuration = 3000; //duration of fade in ms

...

void fadeLed(boolean input, int inertia){
  for(int state=0;state<256;state++){
    if (input==LOW){
      analogWrite(led, state);
    }else{
      analogWrite(led, 255-state);
    }
    // delay in every iteration to achieve 3 seconds in total.
    delay(fadeDuration/256); //=(total fading duration)/(number of iterations)
  }
}

Hope this is clear. Don't forget to check the links I placed, they are all VERY important.

Can you explain me the use of inertia ? Also how are you using the fadeLed fuction ?

I tried to describe what I did. Check out

The 1k (pulldown-)resistor must be placed at the other side of the button (the pin8 side, not the 5v side).
The led needs a resistor, to limit the current.
There is no need for the buttonstate variable, as you can just check the brightness to see if the PWM value must be changed.
int ledpin = 9;
int pushbutton = 8;

int brightness = 0;
int fadeamount = 1;

void setup ()
{
  pinMode (ledpin,OUTPUT);
  pinMode (pushbutton,INPUT);
}

void loop ()
{
  if( digitalRead(pushbutton)==HIGH && brightness<255 )
  {
    // fade in led
    brightness = brightness + fadeamount;// increase brightness
    if( brightness>255 ) // check that brightness doesn't exceed 255
      brightness = 255;
    analogWrite(ledpin,brightness);
    delay (1);
  }
  else if( digitalRead(pushbutton)==LOW && brightness>0 )
  {
    // fade out led
    brightness = brightness - fadeamount;// decrease brightness
    if( brightness<0 ) // check that brightness doesn't go below 0
      brightness = 0;
    analogWrite(ledpin,brightness);
    delay (1);
  }

}

but this program will only work when i will push or leave the push button not like i wanted............i wanted the fading effect to continuously work even after leaving the push button. it should be like on first click(pressing and leaving) the fading effect should start and on another click the LED turns off again if i click the push button the fading effect should start and on my another click the LED turns off.

try this, its simple and easy to understand,
int ledPin = 9;
int btnPin = 8;
int brightness = 0;
int btnState = LOW;
bool trigger = LOW;
void setup ()
{
  pinMode (ledPin, OUTPUT);
  pinMode (btnPin, INPUT);
}

void loop ()
{
  if ( digitalRead(btnState) && !btnState)
  {
    if (trigger)
    {
      for (int i = 0; i < 256; i++)
      {
        analogWrite(ledPin, i);
        // wait for 30 milliseconds to see the dimming effect
        delay(30);
      }
    }
    else
    {
      for (int i = 255; i >= 0; i--)
      {
        analogWrite(ledPin, i);
        // wait for 30 milliseconds to see the dimming effect
        delay(30);
      }
    }
    trigger = !trigger;
  }
  btnState = digitalRead(btnState);
}

You might want to add some delay, or the fade is so fast you can see it.

you should break down the code into two pieces, one to read the button and another to fade the led.
to fade an led, you just need to change its brightness and hold at that brightness for a short period of time. to drive the led at its brightness, use pwm.
that's all there is.
fancier ones will try to do a gamma correction but to just get started, the above is sufficient enough.

There are basically two parts to your program and it's best if you deal with them completely separately:

Reading a push button to turn fading on or off
Fading if fading is turned on

Start by making an LED fade all the time. The Fade example can help you with that.
Then as a separate sketch program the button to turn an LED on or off each time you press it.
Once you have those working change the LED in the second sketch to setting a flag, and make the code from the first sketch look at that flag.

actually i had tried to make this sketch after learning to fade an LED and  toggling the the LED on and off using push button but something is still getting wrong.

Show us your LED toggling code.

@Majenko Tehee, try not to use the word "fool". But you've put some quite some effort into the question/answer which somewhat justifies it. But keep in mind that the way StackExchange works, might not be as trivial to new or foreign users (again and again indeed).

@Paul I was doing my Mr T impression. I guess these kids these days wouldn't recognise him if he jumped up in front of them and punched them in the face...

@Majenko, Ahaha, I was already thinking something, but such things can be hard to spot (depending on your frame of reference). In Germany, Mr. T wouldn't talk English (they've got those annoying voice-over things on TV) ;D and some Arduino Engineers might indeed not know him, yet. Fact of the day: "A snickers commercial (featuring Mr. T) was once banned from TV https://www.youtube.com/watch?v=Ona7QYULRVE"

I didn't get the reference. But then I never watched the A-team. You need to be careful with cultural references, sometimes they can go over people's heads due to age, country of origin, etc.


text:
Why is my LED blinking?
I have this simple push button schematic:

The idea is that the LED is on as long as the button stays pushed, with the switch closed.
The code is below:
int ledPin=10;
int switchPin=5;

void setup()

{
  Serial.begin(9600);
  pinMode(switchPin, INPUT);
  pinMode(ledPin,OUTPUT);

}
void loop()

{
  digitalWrite(ledPin,LOW);//DBG
  if (digitalRead(switchPin)==HIGH)
{
 digitalWrite(ledPin,HIGH);//DBG
 delay(500);
}
 if (digitalRead(switchPin)==LOW);
{
digitalWrite(ledPin,LOW);//DBG
delay(200);
}
}

As I keep the button pressed, the LED blinks regularly, instead of staying on. Why?
I have tried using a capacitor between the switch and switchPin, with no change.

The beginning of your code in the loop:
void loop()  {
  digitalWrite(ledPin,LOW); //remove this line here
  if (digitalRead(switchPin)==HIGH)
{
     digitalWrite(ledPin,HIGH);//DBG
     delay(500);
}
 if (digitalRead(switchPin)==LOW);
 {
      digitalWrite(ledPin,LOW);//DBG
       delay(200);
     }
}

Before your first if(digital read(switch pin) == HIGH)  you turn the LED off, and then you have a delay, which gives the blinking effect, remove that and it will not blink.

@GiuseppeBarbesino not stupid just the formating of the code makes it unreadable, and will cause one to miss read code, happens to many ;)


text:
Use object of LiquidCrystal class within another class
I am quite new to C++ and hope that I don't bore you too much with my question.
I want to use an object of LiquidCrystal Class in another class called "Display_ManagerClass". I followed the instructions of the 2nd alternative in the following link:
Use object of other class within class
Unfortunately, I receive a linker error.
.ino-file:
#include "Licht_Manager.h"
#include "Display_Manager.h"
#include "Zeit_Manager.h"

LiquidCrystal lcd(8, 13, 9, 4, 5, 6, 7);

void setup()
{

    Licht_Manager.init();
    Display_Manager.init(&lcd);
}

void loop()
{
    Display_Manager.showText("Hello", "World");
    while (1)
    {
        Licht_Manager.blink(1);
    }
}

Display_Manager.h:
#ifndef _DISPLAY_MANAGER_h
#define _DISPLAY_MANAGER_h

#if defined(ARDUINO) && ARDUINO >= 100
    #include "arduino.h"
#else
    #include "WProgram.h"
#endif

#include <LiquidCrystal/src/LiquidCrystal.h>

class Display_ManagerClass
{
    protected:

    public:
        //void init();
        void init(LiquidCrystal* _p_lcd);
        void showText(String DisplayText1, String DisplayText2);
    private:
        LiquidCrystal* p_lcd;

};

extern Display_ManagerClass Display_Manager;

#endif

Display_Manager.cpp:
#include "Display_Manager.h"

void Display_ManagerClass::init(LiquidCrystal* _p_lcd)
{
    p_lcd = _p_lcd;
    p_lcd->clear();
}

void Display_ManagerClass::showText(String DisplayText1, String DisplayText2)
{
    p_lcd->clear();
    p_lcd->setCursor(0,0);
    p_lcd->print(DisplayText1);
    p_lcd->setCursor(0,1);
    p_lcd->print(DisplayText2);
}

Display_ManagerClass Display_Manager;

I receive the following errors:
Display_Manager.cpp.o:In function `Display_ManagerClass::init(LiquidCrystal*)
Display_Manager.cpp:clear()
Display_Manager.cpp.o:In function `Display_ManagerClass::showText(String, String)
Display_Manager.cpp:clear()
Display_Manager.cpp:setCursor(unsigned char, unsigned char)
Display_Manager.cpp:setCursor(unsigned char, unsigned char)
collect2.exe*:error: ld returned 1 exit status
Error creating .elf

I made sure that the correct directory of the library is set up in the project properties. The library also works in the normal way, but in combination with the class it doesn't.
I work with Atmel Studio 7 in combination with VisualMicro, Arduino IDE 1.6 and Arduino Uno.
Thank you in advance.

You must also include LiquidCrystal.h in your sketch. That way the IDE will know to include it in the list of files to compile and link with your sketch.

In the main .ino file is what Majenko is referring to. The IDE uses include directives there to know which libraries to include for linking purposes.


text:
RGB LED strip green LEDs cannot be dimmed to less than 50%
I have an RGB LED strip which I want to control with my arduino uno, everything works fine, except for the green LEDs.
They cannot be dimmed to less than 50%, because they will simply turn off.
I have this test code in my setup:
Serial.write("dimming green test started");
for(int x = 255; x > 0; x--) {
    analogWrite(greenPin,x);
    Serial.write(" - g:");
    Serial.print(x);
    delay(6);
  }
  Serial.println();
  Serial.write("dimming green test done");
  Serial.println();

And the green LEDs are fully turned on in the beginning, and at about 127, the just turn off. All the other colors are perfectly dimmable.
I checked the energy usage, and green does only use a little more than the other colors, so that's not the problem.
Are green LEDs not dimmable? Or is this just an optical effect?
(I use a setup very similar to this one with one difference: but only use 5V, because my LED strip only needs 5V)

switch connections at arduino. swap pin 4 and 7 ... does the problem move to red color?

the pins marked with ~ are the PWM pins ... use those

so why does blue and red work :p

I used pins 5-7 (so the image was not exactly correct)

analogWrite only works on pins that support PWM. Those are the pins with the ~ next to it.
On no-PWM pins, analogWrite will set the pin to LOW, for all values lower than 128, and HIGH for all the higher values. Which is what you are experiencing.

interestingly, none of the 3 pins chosen by the OP - 2,4 and 7 - have that ~ symbol in the image in the question!

@JaromandaX the OP said the image was from a similar project, so I’m not assuming he used those exact pins.

with one difference - well, there's three connections to LED's, but only one fails to work ... must be at least two differences between actual wiring and what OP shows in the question :p

I used pins 5-7, so only one of them was not PWM


text:
remove weird chars from char array ESP32
When I'm converting a string to a char array there are always some weird chars at the end.
I have to do it manualy because the convertTochar function crashes my ESP.
  String sssid = module.getCssid(); //String is stored in the eeporm
  char cssid[sssid.length()];
  Serial.println(sssid.length()); //prints correct length of 6
  //convert do ssid
  for( int i = 0; i<sizeof(cssid);i++){
    cssid[i] = sssid[i];
  }
  Serial.println(cssid); //prints myssid⸮?⸮2⸮?
enter code here

If I'm printing the value directly fromm eeprom there are no wired characters.
Also the max eeprom size for the string is 10 bytes...
Why are these characters at the end of string?

You forgot to add one more character to the array to place a \0 (0 value byte) in. This denotes the end of a string. If you forget this, the string will continue until it finds the first 0 byte, which will probably be after the original string copy. This can be dangerous, because it might be in memory that is not containing useful data, and those weird character can be many if there is not a 0 soon or at all.
Note that the 6 bytes you get are the bytes EXCLUDING this 0 byte, so you need to allocate 7 bytes to store a string of length 6.
Instead of the for loop you can use the strcpy function which copies a function including the 0 string.
See description:
Description
The C library function char *strcpy(char *dest, const char *src) copies the string pointed to, by src to dest.
Declaration
Following is the declaration for strcpy() function.
char *strcpy(char *dest, const char *src)
Parameters
dest − This is the pointer to the destination array where the content is to be copied.
src − This is the string to be copied.
Return Value
This returns a pointer to the destination string dest.
Example
The following example shows the usage of strcpy() function.
#include <stdio.h>
#include <string.h>

int main () {
   char src[40];
   char dest[100];

   memset(dest, '\0', sizeof(dest));
   strcpy(src, "This is tutorialspoint.com");
   strcpy(dest, src);

   printf("Final copied string : %s\n", dest);

   return(0);
}

Note that sizeof() only works for statically allocated arrays - that is, arrays that are allocated at compile time with a constant value. Using sizeof() with an array that is sized using a variable (or the return value of a function) will instead result in a pointer to a block of memory allocated on the stack, and sizeof() would return the size of that pointer - 2 on an 8-bit Arduino, or 4 on a 32 bit system like an ESP8266.  You need to use strlen() not sizeof().

Thank you for the answer! But strcpy only works when you copy char to char not string to char, right?  ('strcpy(myChar, mystring)') Making the size of the char array bigger fixed the problem.

Probably you have to make the string 1 bigger (to store the \0 at the end).


text:
Arduino - Extracting Multiple Strings from Serial Read
I am trying to write an Arduino code that reads a long string, example <11,22,33>, through the Serial Monitor and then stores the 11,22, and 33 into separate bins of a matrix array.
So the user could input: <11,22,33>
And the code would store the three entries into a matrix of strings:
matrix[0]=11;

matrix[1]=22;

matrix[2]=33;

Whenever I try to run the code the only result that's outputted is
matrix[0]=33;

matrix[1]=33;

matrix[2]=33;

But the strange part is when I put print commands after the Matrix[i]=data line in the code, the output shows the correct numbers! I'm not sure where the issue is and if somehow I made all entries the final entry. Any help is appreciated!
// Example 3 - Receive with start- and end-markers

const byte numChars = 32;
char data[numChars];    //data entry for appending Serial data
char *matrix[numChars]; //matrix of data entries
static byte i=0;  //matrix index

boolean newData = false;

void setup() {
    Serial.begin(9600);
    Serial.println("<Arduino is ready>");
}

void loop() {
    recvWithStartEndMarkers();
    showNewData();
    Serial.println(matrix[1]);
}

void recvWithStartEndMarkers() {
    static boolean recvInProgress = false;
    static byte ind = 0;  //data index
    char startMarker = '<';
    char midMarker = ',';
    char endMarker = '>';
    char rc;    //Serial read character

    while (Serial.available() > 0 && newData == false) {
        rc = Serial.read();

        if (rc == startMarker) {
            recvInProgress = true;  //if startMarker arrives then enter secondary if below
        }

        else if (recvInProgress) {  //begin appending characters if startMarker activated switch

            if (rc == midMarker) {  //if midMarker is reached...
                matrix[i]=data;     //append data to i-th entry in matrix
                i++;                //add to matrix index
                data[0] = '\0';     //clear data
                ind = 0;            //reset data index
            }
            else if (rc == endMarker) {     //if endMarker is reached...
                matrix[i]=data;             //append data to last entry in matrix (ensures last data is appended)
                data[ind] = '\0';           // terminate the string
                recvInProgress = false;
                ind = 0;                    //reset counters for data and matrix
                i = 0;
                newData = true;
            }
            else {
                data[ind] = rc;           //eppend Serial character into data
                ind++;                    //add to data index
                if (ind >= numChars) {
                    ind = numChars - 1;
                }
            }
        }
    }
}

void showNewData() {
    if (newData == true) {
        Serial.print("This just in ... ");
        Serial.println(matrix[0]);
        Serial.println(matrix[1]);
        Serial.println(matrix[2]);
        newData = false;
    }
}

You define pointers for each value as :
char *matrix[numChars]; //matrix of data entries

However, in all cases you let it point to data:
matrix[i]=data;

Than you set the value starting from that address. So what happens is after you read the first value (11), and matrix[0] contains '11', than matrix[1] points to the same data which you write the value 22 to. And you do the same for 33. So you end up with 3 pointers to the same address (data) containing/overwriting the last value (33). So you get three times 33.
You should either continuing writing the string in data and refer to the correct part inside the string data.  If you want to do a Serial.println, you have to end the strings with \0, so the string data and matrix references should be:
index:    0   1  2  3  4  5  6  7  8
data:     1   1 \0  2  2 \0  3  3 \0
matrix:  [0]       [1]      [2]
i:        0         1        2

It will help if you change
matrix[i]=data;

to
matrix[i]=&(data[ind]);

I'm not sure I understand your corrections. If I change matrix[i]=data to matrix[i]=&(data[ind]) what's printed is blank.

I didn't try the program, so it's a bit hard to verify out of my head. I think you should change the line at the end of my answer in both cases (if (rc == midMarker) and (rc == endMarker). Also in the midMarker case, I think you have to put i++ before the matrix[i] assignment.
However, I suggest you test this function not on an Arduino but in e.g. VisualStudio on a PC. Call the function and step with a debugger through the code so you can see immediately what is wrong.


text:
How to find the MAC address using NodeMCU when connecting to WiFi?
I am new to using NodeMCU and IOT. I am testing the NodeMCU (ESP8266) so that I can connect with pubnub server. Have taken code from github but there is error saying
'mac was not declared in this scope'

and some other error too.
Can anyone tell whats the problem?
This code is from pubnub github page - https://github.com/pubnub/arduino
Code:-
#include <Ethernet.h>

#include <PubNub.h>

void setup() {
    /* For debugging, set to speed of your choice */
    Serial.begin(9600);

    /* If you use some other HW, you need to do some other
       initialization of it here... */
    Ethernet.begin();

    /* Start the Pubnub library by giving it a publish and subscribe
       keys */
    PubNub.begin(publisher key, subscriber key);
}

void loop() {
    /* Maintain DHCP lease. For other HW, you may need to do
       something else here, or maybe nothing at all. */
    Ethernet.maintain();

    /* Publish message. You could use `auto` here... */
    PubNonSubClient *pclient = PubNub.publish(pubchannel, "\"message\"");
    if (!pclient) return;
    PublishCracker cheez;
    cheez.read_and_parse(pclient);
    /** You're mostly interested in `outcome()`, and,
        if it's "failed", then `description()`.
    */
    Serial.print("Outcome: "); Serial.print(cheez.outcome());
    Serial.print(' '); Serial.println(cheez.to_str(cheez.outcome()));
    Serial.print("description: "); Serial.println(cheez.description());
    Serial.print("timestamp: "); Serial.println(cheez.timestamp());
    Serial.print("state: "); Serial.print(cheez.state());
    Serial.print(' '); Serial.println(cheez.to_str(cheez.state()));
    pclient->stop();

    /* Wait for news. */
    PubSubClient *sclient = PubNub.subscribe(subchannel);
    if (!sclient) return; // error
    String msg;
    SubscribeCracker ritz(sclient);
    while (!ritz.finished()) {
        ritz.get(msg);
        if (msg.length() > 0) {
            Serial.print("Received: "); Serial.println(msg);
        }
    }
    sclient->stop();

    delay(1000);
}

error :-
  sketch_jan17a:28:47: error: 'pubchannel' was not declared in this scope

     PubNonSubClient *pclient = PubNub.publish(pubchannel, "\"message\"");

                                               ^

sketch_jan17a:44:46: error: 'subchannel' was not declared in this scope

     PubSubClient *sclient = PubNub.subscribe(subchannel);

                                              ^

Multiple libraries were found for "Ethernet.h"
 Used: C:\Users\sultan\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0-beta2\libraries\Ethernet
 Not used: C:\Program Files (x86)\Arduino\libraries\Ethernet
exit status 1
'mac' was not declared in this scope

I don't believe you have an Wiznet Ethernet module connected to your NodeMcu. Ethernet library is for the Wiznet chips for wired LAN. You want to use the WiFi of the NodeMcu. For that the esp8266 core has the ESP8266WiFi library. It has the same API as other WiFi libraries based on Arduino WiFi library. So you can modify the WiFi examples of the Arduino pubnub library. Only change #include <WiFi101.h> to #include <ESP8266WiFi.h>. (And remove #include <SPI.h>.)

yes no error after doing it. But now it says "Error compiling for board NodeMCU 1.0 (ESP-12E Module)."  Mine is node mcu 2 but can;t find it in the board setting. what to do?

if it is ""Error compiling..." then there is some compilation error

no worries, got it


text:
How to (optimally) fetch a button press?
For my hardware, I need to check if the button was pressed, but I need to do things only once every half a second.
if (digitalRead(pin) == HIGH)
{
    doStuff();
    delay(500);
}
The above does not work, because I have to check other things in the main loop as well.

You should use the millis function (see millis).
Create a variable of type unsigned long and check it against the current time, with some offset.
See also the debouncing example, how to use this function and maybe you want to implement the debouncing too.


text:
What would cause one Arduino to be recognized but not another?
I have two Arduinos, A cheap china-knockoff and an original one. I have had no problem with either of them before. But when I moved from connecting the original with a USB A-hub to running it over USB-C my computer can't find it any more.
I run OSX and tried to install a new USB serial driver. Didn't work either. Then I tried the cheap clone, same computer, same wire, same computer and it works fine.
The faulty Arduino powers up and I can reset it. So it seems to be working. What might cause this?

Do the two boards use different USB chips? I.e., the clone use CH340G?

How can I tell?

By looking. Black thing. Near the USB connector on the board.

Yeah, the clone is CH340G... what's the original one?

ATMega16U2. There's the probable difference that means one is detected and the other not. As to why the genuine one isn't detected, I have no idea.  The clone uses the custom CH340G driver. The original uses the default CDC/ACM driver. I have an itch at the back of my head about something to do with CDC/ACM in later versions of OS X, but I don't know what.

This might help: https://discussions.apple.com/thread/8297132

Are you 100% sure the USB cable is a data cable, not just a power cable? A power cable will only provide power to the USB device, but no data communications.

Thx, the problems started when I went from a usb hub to usb3. @tom, yeah, it works with the chineese knockoff...