How to use analogWrite to regulate a led?

I want to send a value to the cloud via a mobile app and this value I want it’s going to be the analogWrite value of a led. I want start with the led at maximum.
I did that but i think it’s not well done. A function can’t recive an int, must recibe a string, can it?
How can I do that?
Thank you so much, and sorry for my mistakes.

    int led2 = A5;

    void setup() {




    void loop() {


    int ledToggleAnalog(int value) {
    return 1;

I’m not sure what this is but pinMode() is used to set the mode of the specified pin, for example INPUT or OUTPUT. Also, analogWrite(), by default, takes a value between 0 and 255. Your code should look like this:

pinMode(led2, OUTPUT);
analogWrite(led2,255);   // Full ON LED

Particle.function(), is passed a String object so your callback function definition needs to look like:

int ledToggleAnalog(String value) {

Assuming you pass a numerical value (between 0 and 255) while calling the Particle.function(), then your code needs to convert the String to an integer value:

    int ledToggleAnalog(String value) {
    // Convert the ascii representation (string) of the value to an integer
    int val = value.toInt();
    if (val < 0 || val > 255)  //check if within acceptable range
      return -1;               // return -1 to indicate error
    return 1;

Make sure to add a current limiting resistor (150 - 1K ohms) in series with your LED on pin A5 or you may damage the Photon GPIO pin. Also note that LED brightness will not be linear over the PWM range (0-255) of the analog output. I highly recommend you read the documentation on the various functions you are using.

1 Like

Below the WebIDE you will find example sketches - the example number 2 fits perfectly for your purpose: Web-Controlled LED - recommendation for transparency.

sorry! It was:
thanks for the reply, now I’m going to study it well!

Yes, but it’s with digital not analog. Thanks.

@fcabana, in the Arduino world, the digital PWM output is considered “analog” (loosely said). In electronics, true analog is obtained via a DAC (digital to analog).

1 Like