How to send data from arduino to processing over wifi? - android

i'm actually trying to make a connected doorbell. Like when you press the button, the wifi-arduino ( ESP32 DEVKITV1 ) sends to my laptop (on Processing) the signal to make a song over wifi. The laptop is connected to a wireless to make the song stronger.
I don't suceed in the wifi connexion :
#include <WiFi.h> // Include the Wi-Fi library
const char* ssid = "Wifi Guest"; // The SSID (name) of the Wi-Fi network you want to connect to
const char* password = ""; // The password of the Wi-Fi network
const int bouton = 14;
const int ledtemoin = 12;
int compteur = 0;
int etatbouton = 0;
int etatboutonprecedent = 0;
void setup() {
Serial.begin(115200); // Start the Serial communication to send messages to the computer
delay(10);
Serial.println('\n');
pinMode(bouton, INPUT);
pinMode(ledtemoin, OUTPUT);
Serial.begin(115200);
WiFi.begin(ssid, password); // Connect to the network
Serial.print("Connecting to ");
Serial.print(ssid);
while (WiFi.status() != WL_CONNECTED) { // Wait for the Wi-Fi to connect
delay(500);
Serial.print('.');
}
Serial.println('\n');
Serial.println("Connection established!");
Serial.print("IP address:\t");
Serial.println(WiFi.localIP()); // Send the IP address of the ESP8266 to the computer
pinMode(13, OUTPUT);
}
void loop() {
etatbouton = digitalRead(bouton);
if (etatbouton != etatboutonprecedent) {
if (etatbouton == HIGH) {
compteur++;
digitalWrite (ledtemoin, HIGH);
Serial.println("APPUI");
Serial.print("nombre d'appuis: ");
Serial.println(compteur, DEC);
}
else {
Serial.println("PAS D'APPUI");
digitalWrite (ledtemoin, LOW);
}
etatboutonprecedent = etatbouton;
}
}

You have to connect the ESP32 (it is not an Arduino) to your WiFi router.
On
const char* ssid = "Wifi Guest"; // The SSID (name) of the Wi-Fi network you want to connect to
const char* password = ""; // The password of the Wi-Fi network
You have to give the SSID and password of your router. This is the only way to connect your ESP32 to your network.
Using some library line WiFiManager, you can set your ESP32 as AccessPoint and so, if it can't connect to your router, it will create a new Network. So you can set the SSID and password over your phone or your PC, without coding it in your code.
But to keep it short: put your router ssid and router password in your code, if you want see your esp32 inside your network.

Related

Android and C++ socket communication over WiFi Direct

Overview: I'm currently working on an Android app which connects to a Linux system via WiFi Direct, with the final intent of streaming video over this established connection.
The raspi will be acting as a server in this scenario, with the Android being the client. I will be streaming from a camera attached to the pi, and receiving this video on the Android side to display in my app using ExoPlayer. The pi cannot start sending this video over a datagram socket without having the client's ip address. The Android device will also need to send out miscellaneous packets to the Pi which would be telling it what to do, thus the need for both devices having each others ip addresses.
The current Linux system I am working on is a Raspberry Pi running Raspian, with development taking place in C++. The Android runtime environment being a Samsung Galaxy Tab A.
Problem: I'm able to successfully establish a connection between the two devices, which I have setup so that the Raspberry Pi is always the group owner. With the Pi being group owner, it doesn't have immediate access to the Android's IP address; thus a temporary TCP socket connection must be made between the two so the Raspberry Pi can take note of the Android's IP address.
After a WiFi connection is established, this C++ code is ran on the Pi to open & accept a TCP socket connection from the Android:
#include<cstddef>
#include<iostream>
#include<string>
#include<sys/types.h>
#include<sys/socket.h>
#include<sys/un.h>
#include<unistd.h>
#include<netdb.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#define BACKLOG 2 //Allowed connection count.
#define PORT 8988 //The port we will be listening on.
//The static IP of p2p-dev-wlan0
const std::string MY_IP = "192.168.4.1";
bool listen_for_ip() {
//Buffer for receiving messages.
char buffer[256];
//Create Server Socket:
int sock_fd = socket(AF_INET, SOCK_STREAM, 0);
if (sock_fd < 0)
return false;
else
std::cout << "Created Server" << std::endl;
struct sockaddr_in my_addr, peer_addr;
//Recieve messages from IPv4 addresses.
my_addr.sin_family = AF_INET;
//Set our IP address of the socket to the value in "MY_IP"
my_addr.sin_addr.s_addr = inet_addr(MY_IP.c_str());
//my_addr.sin_addr.s_addr = INADDR_ANY; // Also tested with this, no luck.
//Set our in port to the value in "PORT"
my_addr.sin_port = htons(PORT);
//Attempt to bind to IP and port.
if (bind(sock_fd, (struct sockaddr*) &my_addr, sizeof(my_addr)) == 0)
std::cout << "Binded successfully" << std::endl;
else
return false;
//Listen on the socket
if (listen(sock_fd, BACKLOG) < 0)
return false;
//Accept a connection.
socklen_t peer_addr_size = sizeof(peer_addr);
std::cout << "Accepting connection ..." << std::endl;
int new_fd = accept(sock_fd, (struct sockaddr*) &peer_addr, &peer_addr_size);
if (new_fd == -1) {
std::cout << "Error accepting connect" << std::endl;
close(sock_fd);
return false;
}
else
std::cout << "Connection accept completed status = " << new_fd << std::endl;
//
char ip[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &(peer_addr.sin_addr), ip, INET_ADDRSTRLEN);
if (recv(new_fd, buffer, 256, 0) < 0) {
close(new_fd);
close(sock_fd);
return false;
}
std::cout << "Client says " << buffer << std::endl;
//Do other stuff with connection ...
close(new_fd);
close(sock_fd);
return true;
}
This code runs successfully, and as should blocks on the accept() call to wait for the Android connect to the socket.
On the Android side this code is ran to connect to the Pi (Group owner) over a basic socket:
public static final int PORT = 8988;
private static final int TIMEOUT_MS = 10000;
private final String myIp;
private WifiP2pInfo mGroupInfo;
private final WifiDirectService mWifiDirectService;
public P2pClientSocket(WifiDirectService wifiDirectService, WifiP2pInfo groupInfo, String ourDeviceIP) {
mGroupInfo = groupInfo;
myIp = ourDeviceIP;
mWifiDirectService = wifiDirectService;
exchangeIP();
}
/**
* Utilizes a basic socket & TCP to ensure that the IP address of this machine is sent to the group owner of established P2P group.
* If there is an error with sending or writing this message, or the message times out,
* {#link WifiDirectService} will be notified to immediately dispose of its current connection.
*/
private void exchangeIP() {
Socket initSocket = new Socket();
Runnable r = () -> {
try {
String host = mGroupInfo.groupOwnerAddress.getHostAddress();
Log.d(TAG, "Opening socket to : " + host + ", " + PORT);
initSocket.connect(new InetSocketAddress(host, PORT), TIMEOUT_MS);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(initSocket.getOutputStream(), StandardCharsets.UTF_8);
outputStreamWriter.write(myIp, 0, myIp.length());
outputStreamWriter.close();
Log.d(TAG, "Successfully wrote IP.");
} catch (SocketTimeoutException e) {
String message = "Connection Timeout - Disconnecting.";
Log.e(TAG, message, e);
mWifiDirectService.socketError(message);
} catch (IOException e) {
String message = "IP Exchange Error - Disconnecting.";
Log.e(TAG, message, e);
mWifiDirectService.socketError(message);
} finally {
try {
initSocket.close();
} catch (IOException e) {
Log.e(TAG,"Error Closing Init Socket.");
}
}
};
new Thread(r).start();
}
The value of
String host = mGroupInfo.groupOwnerAddress.getHostAddress()
will always be the IP address of the raspberry pi. I have configured it so it runs as a DHCP server with a static IP using:
cat > /etc/systemd/network/12-p2p-wlan0.network <<EOF
[Match]
Name=p2p-wlan0-*
[Network]
Address=192.168.4.1/24
DHCPServer=yes
EOF
However, on the .connect() call, the timeout threshold is always reached. I'm a bit of a networking noob so I'm not entirely sure on what I'm doing wrong. Included is the timeout stack trace:
java.net.SocketTimeoutException: failed to connect to /192.168.4.1 (port 8988) from /192.168.4.163 (port 33122) after 10000ms
at libcore.io.IoBridge.connectErrno(IoBridge.java:191)
at libcore.io.IoBridge.connect(IoBridge.java:135)
at java.net.PlainSocketImpl.socketConnect(PlainSocketImpl.java:142)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:390)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:230)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:212)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:436)
at java.net.Socket.connect(Socket.java:621)
at com.nlos.networking.P2pClientSocket.lambda$exchangeIP$0$P2pClientSocket(P2pClientSocket.java:54)
at com.nlos.networking.-$$Lambda$P2pClientSocket$fxU2Z0Zg0gRF1Fyl1fNnqgO2m8I.run(Unknown Source:4)
at java.lang.Thread.run(Thread.java:919)
I've tried multiple different sockets, ensured that the pi is actually up and listening, and am honestly stumped at this point. Any help would be greatly appreciated!

Cannot connect BLE to android apps

I just bought a Bluetooth HM-10 module with CC2541 chip. I am powering it with Arduino Uno. I scanned for bluetooth devices with my phone (samsung j3, 2016) and found the module named as BT05. I paired the devices but I could not connect the bluetooth module with any app. I tried to connect it with AMR Voice/BT Voice Control app and LED controller.
The code I used for controlling LED through app came from here: create.arduino.cc/projecthub/user206876468/arduino-bluetooth-basic-tutorial-d8b737
I put the code here aswell:
char data = 0; //Variable for storing received data
void setup()
{
Serial.begin(9600); //Sets the baud for serial data transmission
pinMode(13, OUTPUT); //Sets digital pin 13 as output pin
}
void loop()
{
if(Serial.available() > 0) // Send data only when you receive data:
{
data = Serial.read(); //Read the incoming data & store into data
Serial.print(data); //Print Value inside data in Serial monitor
Serial.print("\n");
if(data == '1') // Checks whether value of data is equal to 1
digitalWrite(13, HIGH); //If value is 1 then LED turns ON
else if(data == '0') // Checks whether value of data is equal to
0
digitalWrite(13, LOW); //If value is 0 then LED turns OFF
}
}
These are the errors I get:
Maybe you can try if it's work and change the code by urself
#include <SoftwareSerial.h>
SoftwareSerial BT(2, 3); //RX, TX
char val;
void setup() {
Serial.begin(9600);
BT.begin(9600);
Serial.println("BT is ready!");
}
void loop() {
if (BT.available()>0) {
val = BT.read();
Serial.print(val);
}
}

arduino uno with shield sim900 cant read text message

i meet a issue. when i send a text message to my arduino board with a shield sim900 its show my message in number mode. who know what is the problem? here is my code. at the bottom i use serial monitor to see my message and it is read the message in number.
`
#include <SoftwareSerial.h>
SoftwareSerial SIM900(7, 8);
char incoming_char=0;
void setup()
{
Serial.begin(19200); // for serial monitor
SIM900.begin(19200); // for GSM shield
SIM900power(); // turn on shield
delay(25000); // give time to log on to network.
pinMode(4, OUTPUT);
digitalWrite(4, LOW);
SIM900.print("AT+CMGF=1\r"); // set SMS mode to text
delay(1000);
SIM900.print("AT+CNMI=2,2,0,0,0\r");
// blurt out contents of new SMS upon receipt to the GSM shield's serial out
delay(1000);
}
void SIM900power()
// software equivalent of pressing the GSM shield "power" button
{
digitalWrite(9, HIGH);
delay(1000);
digitalWrite(9, LOW);
delay(7000);
}
void loop()
{
// Now we simply display any text that the GSM shield sends out on the serial monitor
if(SIM900.available() >0)
{
incoming_char=SIM900.read(); //Get the character from the cellular serial port.
Serial.print(incoming_char); //Print the incoming character to the terminal.
if (incoming_char=='a')
{
digitalWrite(4,HIGH);
Serial.println(incoming_char);
SIM900.println("AT+CMGD=1,4"); // delete all SMS
}
if (incoming_char=='b')
{
digitalWrite(4,LOW);
Serial.println(incoming_char);
SIM900.println("AT+CMGD=1,4"); // delete all SMS
}
}
}

Android get IP-Address of a hotspot providing device

I'm currently using
public static String getLocalIPAddress(WifiManager wm){
return Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
}
to get the IP-Address of the executing devices. That works fine if the device is connected to a "common" wlan-network as well as the device is connected to a wifi network which is hosted by an other android device via hotspot. If the device is not connected to any wifi network "0.0.0.0" is returned (correct). But if the device is hosting a wifi network by providing a hotspot the methode is still returning "0.0.0.0". How can I get the real IP-Address of a hotspot providing device "in its own wifi-network"?
thx & regards
You're almost right, the default IP address of hotspot is 192.168.43.1 (If device maker didn't change.)
You can check the source code of Android framework (AOSP).
/frameworks/base/services/java/com/android/server/connectivity/Tethering.java
/frameworks/base/wifi/java/android/net/wifi/WifiStateMachine.java
In the Tethering.java,
private static final String USB_NEAR_IFACE_ADDR = "192.168.42.129";
private static final int USB_PREFIX_LENGTH = 24;
// USB is 192.168.42.1 and 255.255.255.0
// Wifi is 192.168.43.1 and 255.255.255.0
// BT is limited to max default of 5 connections. 192.168.44.1 to 192.168.48.1
// with 255.255.255.0
private String[] mDhcpRange;
private static final String[] DHCP_DEFAULT_RANGE = {
"192.168.42.2", "192.168.42.254", "192.168.43.2", "192.168.43.254",
"192.168.44.2", "192.168.44.254", "192.168.45.2", "192.168.45.254",
"192.168.46.2", "192.168.46.254", "192.168.47.2", "192.168.47.254",
"192.168.48.2", "192.168.48.254",
};
Also, in the WifiStateMachine.java
private boolean startTethering(ArrayList<String> available) {
boolean wifiAvailable = false;
checkAndSetConnectivityInstance();
String[] wifiRegexs = mCm.getTetherableWifiRegexs();
for (String intf : available) {
for (String regex : wifiRegexs) {
if (intf.matches(regex)) {
InterfaceConfiguration ifcg = null;
try {
ifcg = mNwService.getInterfaceConfig(intf);
if (ifcg != null) {
/* IP/netmask: 192.168.43.1/255.255.255.0 */
ifcg.setLinkAddress(new LinkAddress(
NetworkUtils.numericToInetAddress("192.168.43.1"), 24));
ifcg.setInterfaceUp();
mNwService.setInterfaceConfig(intf, ifcg);
}
} catch (Exception e) {
loge("Error configuring interface " + intf + ", :" + e);
return false;
}
if(mCm.tether(intf) != ConnectivityManager.TETHER_ERROR_NO_ERROR) {
loge("Error tethering on " + intf);
return false;
}
mTetherInterfaceName = intf;
return true;
}
}
}
// We found no interfaces to tether
return false;
}
Therefore, the default value is 192.168.43.1 .
I tested a small couple of different devices and it seems that the hotspot providing device has always the IP 192.168.43.1 on its network. Can somebody please check/confirm this assumption?
Though this is an old question, but this might help someone. This will return the ip address of your device, as long as you've turned on the hotspot.
private String getIpAddress() {
String ip = "";
try {
Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
.getNetworkInterfaces();
while (enumNetworkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = enumNetworkInterfaces
.nextElement();
Enumeration<InetAddress> enumInetAddress = networkInterface
.getInetAddresses();
while (enumInetAddress.hasMoreElements()) {
InetAddress inetAddress = enumInetAddress.nextElement();
if (inetAddress.isSiteLocalAddress()) {
ip += "SiteLocalAddress: "
+ inetAddress.getHostAddress() + "\n";
}
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ip += "Something Wrong! " + e.toString() + "\n";
}
return ip;
}
The Hotspot likely acts as a DHCP server. so,
To get IP address (server) of wifi hotspot after getting connected to it call method from remote (client)
intToInetAddress(wifiManager.getDhcpInfo().serverAddress);// get hotspot ip
then
public InetAddress intToInetAddress(int hostAddress)
{
byte[] addressBytes = {(byte) (0xff & hostAddress),
(byte) (0xff & (hostAddress >> 8)),
(byte) (0xff & (hostAddress >> 16)),
(byte) (0xff & (hostAddress >> 24))};
try
{
return InetAddress.getByAddress(addressBytes);
}
catch (UnknownHostException e)
{
throw new AssertionError();
}
}
will return ip address of connected hotspot, and yes most default IP address of hotspot is 192.168.43.1
open termux and run
ip -4 route get 8.8.8.8 | grep via
You'll something like this:
8.8.8.8 via 192.168.43.248 dev wlan0 table 1030 src 192.168.43.20 uid 12345
I was also checked several number of devices all the devices have same ip that is 192.168.43.1
you can try this address
but in android pie it becomes 192.168.43.68

Amarino Bluetooth Connectivity

I am working with Aurdino and Amarino task. I am able to connect with Aurdino and I can send data to Aurdino from Android app. In the same way how I can access the data from Aurdino which I supposed to send to Android app(accessing data from aurdino means not the same data which I have sent from android app to aurdino). Aurdino can contain different data and I want to access that. Please help me
Regards,
Krishna
If you connect the Bluetooth RX to your Arduino TX (after uploading your sketch), you should be able to the data that is coming from Android with normal Serial operations. Here is an example sketch, that will turn LED on port 13 on if '1' is received otherwise it will be turned off
see this for a tutorial
You can also use a SoftSerial port
char val;
int ledpin = 13;
void setup() {
pinMode(ledpin, OUTPUT);
Serial.begin(9600);
}
void loop() {
if( Serial.available() )
{
val = Serial.read();
Serial.println(val);
}
if( val == '1' )
{
digitalWrite(ledpin, HIGH);
} else {
digitalWrite(ledpin, LOW);
}
delay(100);
}

Categories

Resources