PeterH:
The serial monitor sends text, not binary data. When you type in "0x0" the sketch actually receives three characters '0' (ascii code 0x30), 'x' (ascii code 0x78) and '0' (ascii code 0x30). Depending on the serial monitor settings that may also be followed by CR (ascii code 0x0x0D) and/or NL (ascii code 0x0A).If you want to be able to type in "0" or "1" in the serial monitor, you can detect those by comparing the received byte with '0' or '1' characters. For example:
if(incomingByte=='0')
thanks for response, but I am trying to integrate this arduino witha FPGA, so that FPGA Transmits HEX bytes 0x0 and 0x1 then if byte recieeved by arduino is 0x0 then transmit back content of sesnor1. Thant is why I was using if(incomingByte==0x0). Do you knwo how would I be able to send HEX form serial monitor. Actually my main is code below, but it doesnt work, I am not sure how serial communication works in arduino
const int pingPin1 = 7; // CONTECT SENSOR 1 to pin 7
const int pingPin2 = 8; // CONTECT SENSOR 1 to pin 7
long DataAvg[8];
void setup() {
// initialize serial communication:
Serial.begin(115200);
// initialize the data averaging filter
int i;
for(i = 0; i < 8; i++)
{
DataAvg[i] = 0;
}
}
int ping(int pingPin)
{
// establish variables for duration of the ping,
// and the distance result in inches and centimeters:
long duration, mm;
// The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
// Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);
// The same pin is used to read the signal from the PING))): 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(pingPin, INPUT);
duration = pulseIn(pingPin, HIGH);
// convert the time into a distance
mm = (duration / 3) / 2;
// Filter the data
int i;
long FiltData = 0;
for(i = 7; i >= 1; i--)
{
DataAvg[i] = DataAvg[i-1];
FiltData += DataAvg[i];
}
DataAvg[0] = mm;
FiltData = (FiltData + DataAvg[0]) >> 3;
// Truncate the data if it's too big so the value is contained within a single byte
int pingData = 0;
if(FiltData >= 255)
pingData = 255;
else if(FiltData <= 0)
pingData = 0;
else
pingData = FiltData & 0xff;
return pingData;
}
void loop()
{
byte incomingByte = 0; // for incoming serial data
// send data only when you receive data:
if (Serial.available() > 0) {
incomingByte = Serial.read();
if(incomingByte==0x0)
{
Serial.write(ping(pingPin1));
delay(100);
}
if(incomingByte==0x1)
{
Serial.write(ping(pingPin2));
delay(100);
}
}
}