what data type can analogwrite accept ?

I know that analogwrite expects 0 - 255 values, but what datatypes can it handle ? I have a project whereby the variable that is used for the PWM value may go above 255 or below 0 but will be set to 0 or 255 should it try to go out of range but I need to use something like and int rather than a byte data type, will i need to convert types before doing the analogwrite or will any datatype in the correct range work ?

analogWrite expects the "byte" type which is unsigned 8-bits. The compiler may accept other things (like float) but convert and truncate them to be in the range 0 to 255.

Having said that, feeding it negative values may not have the response you expect. Look up the "map" function on the Arduino reference page, or just do it yourself with some "if" tests.

I'll have a couple of if statements that will set the value to just over 0 or just under 255 should it go over either way before it is put into an analog write

can i transfer a value from an int type to a byte type ? So i do my math on an int type variable and once I'm ready to sent it to analogWrite I do

"int variable" = "byte variable"

So i do my math on an int type variable and once I'm ready to sent it to analogWrite I do

Without the quotes and without the byte keyword, yes. On the other hand, it is not necessary. The analogWrite() call will perform the downcast for you.

So is it possible to analogWrite a float value like 230.5,... will it convert the number into an integer data type or maintain the current form as a floating value?

So is it possible to analogWrite a float value like 230.5,... will it convert the number into an integer data type or maintain the current form as a floating value?

You van pass a flot to a function that expects an int. The value will be truncated to fit.

thanks man.. :slight_smile:

If you can get away without floats, your code will be faster and likely use less RAM.

If your algorithm uses a function that can be tabled, the table can be stored in flash.

Hi,
If you are worried about going outside 0-255 use the constrain function.

constrain(x, a, b)

Description

Constrains a number to be within a range.

Parameters

x: the number to constrain, all data types

a: the lower end of the range, all data types

b: the upper end of the range, all data types

Returns

x: if x is between a and b

a: if x is less than a

b: if x is greater than b

Tom...... :slight_smile:

analogWrite takes int, not byte. On the Due this is vital as you can change the analog resolution
from 8 bit upto 12 bit.

On the Uno the values 0 and 255 are treated specially and call digitalWrite, other values are
used as if 8 bit (the top 8 bits are dropped).

For instance this means that analogWrite (pin, 256) will not do what you might expect.