Go Down

Topic: Help reading a number over serial? (Read 1 time) previous topic - next topic


I wanted a simple control of voltage over USB serial, where i type in a number in the serial moniter and it sets that number to the pin, but i know that the serial is sending the ascii numbers or something... anyway here's my code.


void setup(void) {
 // initialize inputs/outputs
 int val;

 // begin the serial communication

void loop()
 int val;
 val == 0;
 if (Serial.available()) {
  val = Serial.read();
   analogWrite(9, val);
   analogWrite(11, val);

Is there any way to get it so that i type 225 into a serial program and it sends that value to the board?
Thanks in advance, Cybot.


Mar 09, 2009, 08:55 am Last Edit: Mar 09, 2009, 09:00 am by mem Reason: 1
Try something like this:
Code: [Select]

// code for receiving a value followed by a letter
// that writes the value to an analog pin corrosponding to that letter

int analogPins[] = {3, 5, 6, 9, 10, 11};  // 'a','b','c','d','e','f'

void setup()

void loop()

// serviceSerial expects data in the form:
// "255a"  - analog writes 255 to pin 3
// "127c"  - analog writes 127 to pin 6
// "0f"    - analog writes 0 to pin 11
void serviceSerial()
 static int val = 0;

 if ( Serial.available()) {
   char ch = Serial.read();

   if(ch >= '0' && ch <= '9')              // is ch a number?  
     val = val * 10 + ch - '0';            // yes, accumulate the value
   else if(ch >= 'a' && ch <= 'f'){        // is ch a letter for one of the analog pins?
      int pin = analogPins[ch - 'a'];      // use the letter to index into the pin array
      analogWrite(pin, val);               // write the previously received val to the pin  

sending a value followed by a letter writes the value to an analog pin corrosponding to the letter :

send: "255a" to analog writes 255 to pin 3
send  "127c"  to analog writes 127 to pin 6
send: "0f"   to analog write 0 to pin 11

I have not run the code but it should get you going in the right direction.

Have fun!


works better but it isnt writing the value i give it, eg i think that when i send 450d it write 200 to pin 9...


Mar 09, 2009, 11:02 am Last Edit: Mar 09, 2009, 11:09 am by mem Reason: 1
try setting val to 0 after the pin identifer is received
you may also want to add some print statments immediatly after the analogWrite
Code: [Select]

  analogWrite(pin, val); // the exisiting analogWrite statement      
   val = 0;

edit: added suggestion to reset val to 0 


when i send 450d

450 is out of the legal range of 0-255 (decimal).  You'll need to either add some error-checking and reject numbers greater than 255, or accept that the code will truncate the number to 8 bits.


Now that makes sence, Thanks for all your help!

Go Up