how to make the code 'faster'?

//initialization
#include <ps2.h>

//mouse pin
PS2Mouse mouse(11, 12); //pin 11 as SCLK, pin 12 as SDIO


//pin initialization
//motor
int rmotorpin1=5;
int rmotorpin2=6;
int rena=4;
int lmotorpin1=9;
int lmotorpin2=10;
int lena=8;

//ultrasonic sensor
int pingKiri=2;
int pingKanan=3;


//LED
int LED=A5;



//variable initialization
//ultrasonic sensor
long durationKiri, durationKanan, cmKanan, cmKiri;
//mouse coordinates
int mouseX;
int mouseY;

//serial declaration to show serial.read
int serial;
char buff[24];

void setup()
{
  //pin declaration
  //motor
   pinMode(rmotorpin1,OUTPUT); 
   pinMode(rmotorpin2,OUTPUT); 
   pinMode(rena,OUTPUT); 
   pinMode(lmotorpin1,OUTPUT); 
   pinMode(lmotorpin2,OUTPUT); 
   pinMode(lena,OUTPUT); 
   digitalWrite(rena, HIGH);
   digitalWrite(lena, HIGH);
  
  //LED
  pinMode(LED, OUTPUT);

  //mouse initialization
  mouse.init();
  
  //open com
  Serial.begin(38400);
}

void loop()
{
    ultrasonic();
    motor();
    printing();
  }

//declaring function for motor movement


void motor() 
{  
   //motor kanan &kiri maju
   analogWrite(rmotorpin1, 200);
   digitalWrite(rmotorpin2, LOW);
   analogWrite(lmotorpin1, 200);
   digitalWrite(lmotorpin2, LOW);   
} 


void ultrasonic()
{
  // The ultrasonic sensor is triggered by a HIGH pulse of 2 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  //Kiri
  pinMode(pingKiri, OUTPUT);
  digitalWrite(pingKiri, LOW);
  delayMicroseconds(2);
  digitalWrite(pingKiri, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingKiri, LOW);

  // The same pin is used to read the signal from the ultrasonic sensor: a HIGH
  // pulse whose duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  pinMode(pingKiri, INPUT);
  durationKiri = pulseIn(pingKiri, HIGH);

  //doing the same routine for right sensor
  //Kanan
  pinMode(pingKanan, OUTPUT);
  digitalWrite(pingKanan, LOW);
  delayMicroseconds(2);
  digitalWrite(pingKanan, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingKanan, LOW);

  pinMode(pingKanan, INPUT);
  durationKanan = pulseIn(pingKanan, HIGH);
  
  // convert the time into a distance
  cmKiri = microsecondsToCentimeters(durationKiri);  
  cmKanan = microsecondsToCentimeters(durationKanan); 
}

long microsecondsToCentimeters(long microseconds)
{
  // The speed of sound is 340 m/s or 29 microseconds per centimeter.
  // The ping travels out and back, so to find the distance of the
  // object we take half of the distance travelled.
  return microseconds / 29 / 2;
}

void printing()
{
  //getting mouseinfo for printing subroutine.
  MouseInfo mouseInfo;
  mouse.getData(&mouseInfo);
  //sprintf(buff, "%.3d %.3d %.3d %.3d", cmKanan, cmKanan, cmKanan, cmKanan);    //printing with the same digit for all numbers
  //Serial.println(buff);   //print numbers
  sprintf(buff, "%.3d", cmKanan);
  Serial.print(buff);Serial.print(" ");

  sprintf(buff, "%.3d", cmKiri);
  Serial.print(buff);Serial.print(" ");

  sprintf(buff, "%.3d", mouseInfo.cX, DEC);
  Serial.print(buff);Serial.print(" ");

  sprintf(buff, "%.3d", mouseInfo.cY, DEC);
  Serial.print(buff);Serial.println();
  delay(500);
}

i have this code inside the arduino and each of the serial.print is taken to VB. inside the VB data is processed into making dots based on the numbers.

these is the code inside the VB,

Imports System.IO.Ports
Imports System.Drawing
Imports System.Drawing.Drawing2D
Imports System.Windows.Forms
Imports System.Windows.Forms.Cursor

Public Class Form1
    Dim RangeLeft As Integer
    Dim RangeRight As Integer
    Dim X As Integer
    Dim Y As Integer
    Dim LeftScreen As Integer
    Dim RightScreen As Integer
    Dim XScreen As Integer
    Dim YScreen As Integer
    Dim picture1 As Object
    Dim Ico As New Icon("Vehicle.ico")
    Dim Rect As New Rectangle(-100, -100, Ico.Width, Ico.Height)
    Dim pen1 As New System.Drawing.Pen(Color.Black, 10)
    Dim pen2 As New System.Drawing.Pen(Color.Red, 10)
    Dim g As System.Drawing.Graphics
    Dim PingPosLeft As Integer
    Dim PingPosRight As Integer
    Dim power As Integer
    Dim j As Random


    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Control.CheckForIllegalCrossThreadCalls = False
        DoubleBuffered = True

        With SerialPort1
            'Set the serial port you want to use.
            .PortName = "COM29"

            'Set baud rate, parity, data bits, and stop bits.
            .BaudRate = 38400
            .Parity = Parity.None
            .DataBits = 8
            .StopBits = StopBits.One

            'Set DTR and RTS
            .DtrEnable = True
            .RtsEnable = True

            'Set number of bytes before DataRecieved event is raised.
            .ReceivedBytesThreshold = 1

            'Open serial port.
            .Open()
        End With


    End Sub
    Private Sub SerialPort1_DataReceived(ByVal sender As System.Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
        'reading data form serial
        TextBox1.Text = SerialPort1.ReadLine()
        RangeLeft = Mid(SerialPort1.ReadLine(), 1, 3)
        RangeRight = Mid(SerialPort1.ReadLine(), 5, 3)
        X = Mid(SerialPort1.ReadLine(), 9, 3)
        Y = Mid(SerialPort1.ReadLine(), 13, 3)

        'printing data to the form
        LabelLeft.Text = RangeLeft
        LabelRight.Text = RangeRight
        LabelX.Text = X
        LabelY.Text = Y

        'make the data as variable to easily access them
        XScreen = (X + 400)
        YScreen = (Y + 300)
        PingPosLeft = (XScreen - RangeLeft)
        PingPosRight = (XScreen + RangeRight)

        'create a 'moving-like' icon by substract the previous picture
        Invalidate(Rect)
        Rect.Y = YScreen
        Rect.X = XScreen

        'creating an instance of pen to draw the 'wall'
        Dim pen2 As New System.Drawing.Pen(Color.Black, 10)
        Dim g As System.Drawing.Graphics
        g = PictureBox1.CreateGraphics
        g.DrawArc(pen2, PingPosRight, YScreen, 5, 5, 180, 90)
        g.DrawArc(pen2, PingPosLeft, YScreen, 5, 5, 180, 90)
        Dim vehicle As New Icon("Vehicle.ico", 2, 2)
        Dim d As System.Drawing.Graphics
        Dim icon1 As New System.Drawing.Icon(vehicle, 1, 1)
        d = PictureBox1.CreateGraphics
        d.DrawIcon(Ico, Rect)
    End Sub

the problem is, data sent and received is too slow, so that the dot's representation is not so thick..

the thing that i want to ask is, is there any way that i can make the data transfer between arduino and VB is fast enough so that every step or every data is count precisely?

thank you..

Use the max speed Arduino can Handle

Serial.begin(115200)

Gains a factor 3

Furthermore replace the printing routine with code below including the removing of the delay from the printing ; move the delay to loop();

void printing()
{
  //getting mouseinfo for printing subroutine.
  MouseInfo mouseInfo;
  mouse.getData(&mouseInfo); 
  sprintf(buff, "%.3ld %.3ld %.3d %.3d", cmKanan, cmKiri, mouseInfo.cX,  mouseInfo.cY);  [glow]// use %ld for longs! don't know cX and CY assume they are int.[/glow]
  Serial.println(buff);
}

i`ll try using faster baud rate..

for the sprintf.. i've tried many times and many ways to get the code printed only with 1 line of code. but the code will be error if i print it only once (meaning 1 sprintf and 1 serial.print).. so i decided to do it one by one and its success. but costing some line...

why there is a different moving the delay on void loop rather than on printing subroutine? any explanation??

thank you very much..

so i decided to do it one by one and its success. but costing some line...

The number of bytes to be transmitted is the controlling factor for speed, not the number of calls to sprintf or Serial.print().

why there is a different moving the delay on void loop rather than on printing subroutine? any explanation??

The suggestion was not to move the delay. It was to get rid of the delay. While in a delay(), nothing happens. It is not possible to go as fast as possible, if you artificially slow down periodically.

@lucandut

Have you tried the printing() as I proposed? did it work?
If not could you post the output you got?

@ PaulS

i see, the first reason i use delay is to make the clear enough to be seen by human eyes. if done without delay, it is too fast to see.. but now it is automatic i also think it would be better to remove the delay.. thanks!!

@robtillaart

this is the discussion when i use the printing like you proposed, http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1293560469

the error is strange.. what i try is, printing 4 variables, all 4 variables contain the same number which is cmKanan. the output expected is suppose to be xxx xxx xxx xxx, but the output is xxx 000 xxx 000. the second and fourth number are always zero.. i don't know why this is happening, but with some trials i found out if i use sprintf for each variables, it would turn correctly.. so i use it..

sorry i couldn't post some picture or anything..because i'm on university's examination and i don't have much time to try with this project. so i`ll just put some story.. ;D

thanks for the reply btw...

the error is strange.. what i try is, printing 4 variables, all 4 variables contain the same number which is cmKanan. the output expected is suppose to be xxx xxx xxx xxx, but the output is xxx 000 xxx 000. the second and fourth number are always zero.. i don't know why this is happening, but with some trials i found out if i use sprintf for each variables, it would turn correctly.. so i use it..

sprintf() uses %d for an integer (2 bytes) and %ld (note the l ) for long (4bytes) , these small differences in source cause great differences in output.

[glow]long [/glow]durationKiri, durationKanan, [glow]cmKanan[/glow], cmKiri;

So you must use %ld for cmKanan.

Explanation:
sprintf(s, "%d %d %d %d ", cmKanan, , cmKanan, cmKanan, cmKanan) ;
puts 4 longs on the stack. sprintf parses the format string and sees a %d => fetch 2 bytes from the stack (lower bytes of cmkanan), encounters another %d => fetch 2 bytes from stack (upper bytes of cmKanan) .... etc

i see... thank you very much.. I just realize about that long data type.. thanks for noticing.. i`ll fix my code and see the difference..