Hi All,
I am new to Arduino and C programming. I am trying to write commands to my device using Serial Monitor. then read my device response and write it also the serial monitor.
I am facing two problems first is the Ascii conversion to hex. I looked at this post http://forum.arduino.cc/index.php/topic,123309.0.html but with no luck. the second problem is I want to send more than one char at a time. its taking each char and trying to process it by its own.
this my code
int i=0;
int indexB = 0 ;
byte inByte = 0 ;
byte inB = 0 ;
byte buf[2] ;
byte buffer[8] ;
void setup()
{
// Start the computer serial port
Serial.begin(9600);
//Start the Hardware serial port
Serial1.begin(1000000);
}
void loop()
{
if( ! Serial.available() )
{
Serial.println( "Finish loading buffer array " );
Serial1.write( buffer , sizeof( buffer ) );
if ( Serial1.available() ) {
Serial.println( "Serial1 is available " );
//Read first byte usually is the command return
if( Serial1.available() > 0 )
{
inB = Serial1.read();
Serial.write( "The first byte: " );
Serial.print( inB , HEX );
}
//read rest of the data
if( Serial1.available() >= 1 )
{
Serial.println( "read Byte 1 " );
for( int i =0 ; i < 1 ;i++ ){
if( i == 0 )
{
inB = Serial1.read();
inByte = inB ;
}
else
{
inByte = Serial1.read();
}
if( inByte < 16 )
{
Serial.print( '0' );
}
Serial.print( inByte , HEX );
Serial.write( ' ' );
}
Serial.println();
}
}
}
else
{
while (Serial.available() > 0 ) {
//read data from Serial Monitor
byte data = Serial.read();
data = h2d( data );
Serial.println( "Data after conversion:" );
Serial.println( data , HEX );
buffer[indexB] = data;
indexB++;
Serial.println( "Print array content:" );
for( int x =0 ; x < 8 ; x++ )
{
Serial.print( buffer[x] );
Serial.print( " " );
}
}
}
}
unsigned char h2d(unsigned char hex)
{
if(hex > 0x39) hex -= 7; // adjust for hex letters upper or lower case
return(hex & 0xf);
}
Note : if I hardcoded buffer array it will work fine and I am getting the proper response.
Thanks in advance.