Hey i recently started using the arduino duemilanove and now i have a problem which i solve myself.
I've build a circuit where the speed of a motor is controlled using pulse width modulation and this works as intended.
the thing is, now i want to control the motorspeed by inputting a value between 0 and 255 through the serial monitors send function, but when i try to do that the value that the arduino reads is nothing like the value i sended. I've managed to figure out that the arduino reads the data input from the serial as bytes/hex but i do not know how to convert it.
can any of you guys help me convert the incoming data through the serial, so that it can be used to control the motor
The first thing to understand is where the serial data that the Arduino is to read is coming from. The data may be sent as numeric data, using multiple bytes for larger values, or it may be that the "number" is sent as a string (123 is sent as '1', '2', '3').
If you are receiving a string (a series of characters), the digit that corresponds to each character can be determined.
0 = '0' - '0'
1 = '1' - '0'
2 = '2' - '0'
etc.
Then, reconstructing the initial number is a matter of multiplying the previous value by 10, and adding the new digit.
int digit, val;
char aChar;
val = 0;
while(Serial.available() > 0)
{
aChar = Serial.read();
if(aChar >= '0' && aChar <= '9')
{
val *= 10;
digit = aChar - '0';
val += digit;
}
}
There are some issues with this code to read the serial data. First, it assumes that all the data for a packet will be available to read. Second, it assumes that there are no characters other than digits that are sent. But, it is a starting point, if the data being sent is coming from the Serial Monitor or some application that sends numbers as strings.