I wanted to send values from a light sensor, using an HC-06. I have everything connected properly. I used MIT App Inventor and the image shows how I connect to the Bluetooth module, and how do I show the data.
Arduino Code
int analogInPin = A0;
int sensorValue = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
sensorValue = analogRead(analogInPin);
Serial.println(sensorValue);
delay(100);
}
Phone
I already searched for several solutions but none worked. I have the baud rate at 9600 (the same as the Bluetooth module).
Related
Is there a possibility how to "overcome" BLE MAC address randomization and detect presence of my own Android phone(s)?
I'm looking for a solution how to detect presence of my phone in close-range to ESP32 without installing something like iBeacon app which would drain my battery.
I've started with example for BLE sniffer which works nice but with MAC randomization on Android it is useless.
Then I moved to the solution using emulation of a HID keyboard. After pairing it, it is nicely reconnecting when the phone comes into the range. Once it is connected I can trigger needed action and then I can turn ESP32 Bluetooth off not to be connected whole time. When I need check the phone again I just can turn the server back on. It would be neat solution but... I need to check more (at least two) phones. I've tried to duplicate BLEServers to swith between or run two simoutinasly but without success - either it is not possible or it is exceeding my knowladge about this BLE advertising/pairing/connecting magic.
Third solution would be to have separate ESP for each phone - doable but only as a last resort
Has somebody solved such task somehow already?
For the keyboard solution I'm using this code found online:
#include <Arduino.h>
#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEServer.h>
#include "BLE2902.h"
#include "BLEHIDDevice.h"
#include "HIDTypes.h"
#include "HIDKeyboardTypes.h"
#include <driver/adc.h>
BLEHIDDevice* hid;
BLECharacteristic* input;
BLECharacteristic* output;
BLEAdvertising *pAdvertising;
BLEServer *pServer;
bool connected = false;
bool restart = false;
class MyCallbacks : public BLEServerCallbacks {
void onConnect(BLEServer* pServer){
connected = true;
Serial.println("Connected");
BLE2902* desc = (BLE2902*)input->getDescriptorByUUID(BLEUUID((uint16_t)0x2902));
desc->setNotifications(true);
// NEEDED ACTIONS
}
void onDisconnect(BLEServer* pServer){
connected = false;
Serial.println("DisConnected");
BLE2902* desc = (BLE2902*)input->getDescriptorByUUID(BLEUUID((uint16_t)0x2902));
desc->setNotifications(false);
restart = true;
}
};
void setup() {
Serial.begin(115200);
Serial.println("Starting BLE work!");
BLEDevice::init("Backpack-MeowMeow");
pServer = BLEDevice::createServer();
pServer->setCallbacks(new MyCallbacks());
pServer->getPeerDevices(true);
hid = new BLEHIDDevice(pServer);
input = hid->inputReport(1); // <-- input REPORTID from report map
output = hid->outputReport(1); // <-- output REPORTID from report map
std::string name = "ElectronicCats";
hid->manufacturer()->setValue(name);
hid->pnp(0x02, 0xe502, 0xa111, 0x0210);
hid->hidInfo(0x00,0x02);
BLESecurity *pSecurity = new BLESecurity();
// pSecurity->setKeySize();
pSecurity->setAuthenticationMode(ESP_LE_AUTH_BOND);
hid->startServices();
pAdvertising = pServer->getAdvertising();
pAdvertising->setAppearance(HID_BARCODE);
pAdvertising->addServiceUUID(hid->hidService()->getUUID());
pAdvertising->start();
hid->setBatteryLevel(7);
//ESP_LOGD(LOG_TAG, "Advertising started!");
//delay(portMAX_DELAY);
}
void loop() {
if(connected){
delay(10);
}
if (restart) {
restart = false;
pAdvertising->start();
}
delay(50);
}
I am new to Arduino and I have been working on a problem that has been troubling me for a few days.
I have an Arduino Uno and an HC-05 Bluetooth module.
Basically I want to send String and Int data together through Bluetooth.
CODE
#include <SoftwareSerial.h>
SoftwareSerial BTSerial(10, 11); // RX | TX
void setup(void) {
// Arduino setup
Serial.begin(9600);
// setting the baud rate of bluetooth
BTSerial.begin(38400); // HC-05 default speed in AT command more
}
void loop(void) {
int num = 123;
BTSerial.write("#"); // Works
BTSerial.write(num); // works
BTSerial.write(String(num) + "#");
// Error: no matching function for call to 'SoftwareSerial::write(StringSumHelper&)'
}
Also the result string should have '#' character at last.
According to the Arduino Website, it has 2 functions.
- Serial.write(val)
- Serial.write(str)
Any help appreciated.
Thank you.
write is for sending raw bytes. You want to use Serial.print instead.
if you want to send String from an another device to arduino, your code sould be like this:
#include <SoftwareSerial.h>
SoftwareSerial BT(3, 4);
String bt = "";
void setup() {
BT.begin(9600);
Serial.begin(9600);
}
void loop() {
if(BT.available()){
bt = BT.readString();
}
Serial.println(bt);
while(!BT.available());
}
the above code, waits for your bluetooth module to recieve any data and reads a String from it and prints it in Serial.
In order to send Int, you can read a String and parse it to Int.
I have battled this issue for a while now and it is driving me nuts:
I am trying to communicate very simply with an Arduino Mega 2560 (via USB as a serial device) from pc running Linux (Knoppix on a usb-dok) when all I am trying to accomplish at this stage is that for each number sent by the laptop to the Arduino, a 'stobe' signal will switch for High to Low or the other way around, and i use this strobe to light turn an LED on and off.
pc side C code:
#include <stdio.h>
int main ()
{
FILE * Device = NULL;
int counter = 0;
Device = fopen("/dev/ttyACM0", "w+");
if(Device == NULL)
{
printf("could not open Device\n");
return -1;
}
while (counter < 10)
{
fprintf(Device, "%d\n", counter);
printf("Sent to Device: %d\n", counter);
counter++;
sleep(2);
}
fclose(Device);
return 0;
}
Arduino code:
int cnt = 0;
int strobe = 0;
int num;
int ValidInput = 0;
char intBuffer[12];
String intData = "";
int delimiter = (int) '\n';
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(3, OUTPUT);
}
int input;
void loop()
{
while(num = Serial.available())
{
delay(5);
// Serial.println(num);
int ch = Serial.read();
if(ch == delimiter)
{
ValidInput = 1;
break;
}
else
{
intData += (char) ch;
}
}
int intLen = intData.length() + 1;
intData.toCharArray(intBuffer, intLen);
intData = "";
int i = atoi(intBuffer);
if(ValidInput)
{
if(i == 0)
{
strobe = 0;
Serial.print("Initializing strobe");
}
else
{
strobe = !strobe;
}
digitalWrite(3, (strobe) ? HIGH : LOW);
Serial.println(i);
ValidInput = 0;
}
}
The problems I am having:
Not sure if fopen is the correct way to communicate with a serial device in Linux, and if so in which mode?
This is the main issue - I am experiencing non-deterministic behavior:
if i run this code right before opening the Arduino editor's 'Serial monitor' it doesn't work as I explained above, instead - it will turn the LED on and then off right away, for each incoming new number.
but once I open the 'Serial monitor' it would act as I want it to - changing the LED's state for each new incoming number.
I am thinking this has something to do with the Arduino's reset or something of that sort.
I looked in many threads here and other forums and couldn't find any solution to this problem.
I'd really appreciate your insight.
First of all, the arduino side looks ok. On the Linux side you need to do some reasearch since the serial communication on posix systems is a little bit more complicated than only opening a file and writing to it. Please use the linux man pages for termios where you can find information on how to setup the communication port parameters and use this document http://tldp.org/HOWTO/Serial-Programming-HOWTO/ for actually learning how to put everything altogether. The serial programming howto will guide you through the process of setting up a port, learning how to control it and learn how to accept input from multiple sources. Also in order to access successfully the serial port from an unprivileged account, you might need to add that user (your user) to a specific group (dialout group in Ubuntu and Fedora). You can search on Google about serial port access under linux and you can fine a lot of code samples ready for you to integrate in your application. You can find an excellent reference and a full documented implementation at the bottom of this thread , also on SO How do I read data from serial port in Linux using C?
A simple fopen doesn't setup any of the serial ports communication parameters. You need to set the baud rate, number of bits, parity, and number of stop bits. And, if you want to use the linux line discipline or not. The termio structure is used to do this.
There are a couple good tutorial on how to use serial between linux and arduinos.
http://chrisheydrick.com/2012/06/12/how-to-read-serial-data-from-an-arduino-in-linux-with-c-part-1/
http://todbot.com/blog/2006/12/06/arduino-serial-c-code-to-talk-to-arduino/
I have written an application for Android in Java using Eclipse to send data to an Arduino via Bluetooth.
The devices seem to be connected okay, but when I send data from the Android to the Arduino the receive (RX) light on the Arduino board doesn't light up.
Can someone help?
#define arduinoRx 2
#define arduinoTx 3
int gelen_veri;
int LedCikis = 8;
SoftwareSerial bluetooth(arduinoRx, arduinoTx);
void setup() {
bluetooth.begin(9600);
}
void loop() {
if (bluetooth.available() > 0) {
gelen_veri=bluetooth.read();
switch (gelen_veri) {
case 'A' :
digitalWrite(LedCikis, HIGH);
break;
case 'K' :
digitalWrite(LedCikis, LOW);
break;
default:
break;
}
}
}
Use the serial rx/tx pins instead of SoftwareSerial. I've had problems with SoftwareSerial in the past and my HC-05 bluetooth module.
My purpose is to use Arduino to set up communication between a PC and an Android device using an HC-05 bluetooth module.
I use the USB communication between the PC and the Arduino (Serial Monitor) and a SoftwareSerial to connect to the HC-05.
My problem is that the communication works well from BT to the PC, but doesn't work as expected in the other way. When sending from the PC to BT all the characters sent are received by the BT device only when I close the Serial Monitor on the PC or when I reset the Arduino.
I've excluded a problem with the BT Module or the Android application because if in Arduino I implement an "ECHO" code (write in Android and the send in Android) everything works fine.
With the Arduino code posted below the expected behaviour is: Arduino reset-> Hello word sent, Serial monitor opened-> nothing happens, character written on serial monitor-> character received on BT, character written on BT-> character received on Serial Monitor, Serial monitor closed-> nothing happens.
The real behaviour is: Arduino reset-> Hello word sent, Serial monitor opened-> 2 Hello word on BT and 1 ("goodnight") on PC, character written on serial monitor-> nothing, character written on BT-> character received on Serial Monitor, Serial monitor closed-> previous written character(s) in serial monitor received + Hello Word.
How can I fix this problem?
Code:
#include <SoftwareSerial.h>
SoftwareSerial mySerial(2, 3); // RX, TX
int a=0;
char c;
char d;
void setup() {
Serial.begin(9600);
Serial.println("Goodnight moon!");
mySerial.begin(9600);
mySerial.println("Hello, world?");
}
void loop() {
delay(10);
if (Serial.available()) {
c=Serial.read();
delay(10);
Serial.write(c);
}
delay(10);
if (mySerial.available()) {
d=mySerial.read();
delay(10);
mySerial.write(d);
}
}
This code is working for me on an Arduino Mini Pro (should be the same as UNO) with an HC-05. I have the HC-05 paired with my laptop. Using HyperTerminal on the COM port associated with the HC-05 and the Arduino serial console, I can send messages bidirectionally. The Serial.println statements show up in the Hyperterminal window like they should.
#include <SoftwareSerial.h>
#define rxPin 8
#define txPin 7
SoftwareSerial mySerial(rxPin, txPin); // RX, TX
char myChar ;
void setup() {
Serial.begin(9600);
Serial.println("Goodnight moon!");
mySerial.begin(9600);
mySerial.println("Hello, world?");
}
void loop(){
while(mySerial.available()){
myChar = mySerial.read();
Serial.print(myChar);
}
while(Serial.available()){
myChar = Serial.read();
mySerial.print(myChar);
}
}
I have implemented a serial communication between Arduino Uno and PC and this was my code, hope it can help:
int data;
char character;
int start_flag = 0;
void setup() {
Serial.begin(921600);
pinMode(2, OUTPUT);
}
void loop() {
if(Serial.available() > 0){
character = (char) Serial.read();
if(character == 's') {
start_flag = 1;
}
if(character == 't') {
start_flag = 0;
}
}
if (start_flag == 1) {
Serial.print(data); //data that was acquired by internal ADC
}
}
You could try this. It's about the simplest code you can use when testing Arduino bluetooth <-> C# communication. Note: the code was tested by connecting PIN1(TX) <-> MODULE RX, PIN2(RX) <-> MODULE TX and dividing the PIN1(TX) 5V to 2,5V before feeding it to the module.
Hope this helps all that are trying this!
Use this serial setup. With this code I can receive and send date to bluetooth from Serial Monitor
void setup(){
Serial.begin(9600); // Begin the serial monitor at 9600bps
bluetooth.begin(115200); // The Bluetooth Mate defaults to 115200bps
bluetooth.print("$"); // Print three times individually
bluetooth.print("$");
bluetooth.print("$"); // Enter command mode
delay(100); // Short delay, wait for the Mate to send back CMD
bluetooth.println("U,9600,N"); // Temporarily Change the baudrate to 9600, no parity
// 115200 can be too fast at times for NewSoftSerial to relay the data reliably
bluetooth.begin(9600); // Start bluetooth serial at 9600
pinMode(led, OUTPUT);
pinMode(buttonPin1, INPUT);
pinMode(buttonPin2, INPUT);
}
For more information, visit
http://www.circuitmagic.com/arduino/arduino-and-bluetooth-hc-06-to-control-the-led-with-android-device/
I recommend to use this app for testing:
https://play.google.com/store/apps/details?id=com.vagoscorp.virtualterminal
It let you see and send bytes as bytes(number from 0b00000000 to 0b11111111 (0 to 255 in decimal))
so you can make a simple echo firmware to test if your baudrate is correct and with that working, begin sending commands to turn on/off some LEDs
this is an echo code example:
char dato = 0;
void setup() {
Serial.begin(9600);//9600 is the default baudrate of the HC-05 (you can change it by AT commands, google it if you want)
//pinMode(13, OUTPUT); //enable this pin if you want to use de LED idea
//digitalWrite(13, HIGH);
}
//////////////////////////////////////////////////////////////////////////
void serialEvent() { //if you have received serial data
while (Serial.available() > 0) {
char dato = (byte)Serial.read();//save the byte
Serial.write(dato);//send the just received byte (echo)
}
}
///////////////////////////////////////////////////////////////////////////
void loop() {
}
I hope it helps you
Had the same problem, you have to view the BT module as 2 different baud rates on the wired side and the radio side. The radio side is set by whatever you connect at through putty, the wired side is programmed via AT commands. HC-05 defaults at 38400.