I have an HC06 for bluetooth communication, but it does not print anything on the serial port and this is giving me a headache because I need to read values on the pc by bluetooth for an academic work.
I used an example from the internet to see if the problem was my module or some communication error.
//Include the SoftwareSerial library
#include "SoftwareSerial.h"
//Create a new software serial
SoftwareSerial bluetooth(2, 3); // TX, RX (Bluetooth)
const int ledPin = 8; // the pin that the LED is attached to
int incomingByte; // a variable to read incoming serial data into
void setup() {
//Initialize the software serial
bluetooth.begin(9600);
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
}
void loop() {
// see if there's incoming serial data:
if (bluetooth.available() > 0) {
// read the oldest byte in the serial buffer:
incomingByte = bluetooth.read();
// if it's a capital H (ASCII 72), turn on the LED:
if (incomingByte == 'H') {
digitalWrite(ledPin, HIGH);
bluetooth.println("LED: ON");
}
// if it's an L (ASCII 76) turn off the LED:
if (incomingByte == 'L') {
digitalWrite(ledPin, LOW);
bluetooth.println("LED: OFF");
}
}
}
using this code I can control the led, but no print is made on the serial port
Does anyone have any idea what happens?
mikb55:
On a related theme, I have no idea why the official Arduino documentation suggests using a int (2 bytes) variable to store a single byte. Serial.available() - Arduino Reference
That sort of thing is actually pretty common in the official Arduino example code. I'm not sure what the reasoning was. In this particular case, it actually makes some sense because Serial.available() returns an int:
You can see from Google searches that beginners are copying/pasting the example code and then running into problems because the datatype is inappropriate for their needs.
Ah, I see now. I didn't take the time to look at the reference page carefully. I just assumed it was about the return from Serial.available() because that was the page name and then I jumped right into the source code.
However, the same argument applies somewhat to Serial.read() too, since it also returns an int:
int HardwareSerial::read(void)
{
// if the head isn't ahead of the tail, we don't have any characters
if (_rx_buffer_head == _rx_buffer_tail) {
return -1;
} else {
unsigned char c = _rx_buffer[_rx_buffer_tail];
_rx_buffer_tail = (rx_buffer_index_t)(_rx_buffer_tail + 1) % SERIAL_RX_BUFFER_SIZE;
return c;
}
}
However, it's really not necessary in this example code because it only gets called when Serial.available() > 0, so you know it can't return -1. It might be that the author of the example wanted to provide code that could be modified by a beginner without resulting in confusing breakage in the event that the modified code did not check Serial.available(). Or maybe they just said "Serial.read() returns an int so the data type of incomingByte should be int".