Arduino XBee sending data API - c++

I want to send data from an end device to a coordinator with XBee and Arduino. But, the Arduino reboots when sending data (sending data was aborted). What could the problem be?
/* Transmit */
#include <SoftwareSerial.h>
#include <XBee.h>
int end = 1;
int alim_XbeeRS = A7;
int RX_XBee = 14;
int TX_XBee = 15;
XBee xbee = XBee();
//Allume le périphérique
void powerOn(SoftwareSerial portcom)
{
portcom.begin(57600);
digitalWrite(alim_XbeeRS, HIGH);
}
void setup ()
{
SoftwareSerial XbeeRS(RX_XBee,TX_XBee);
Serial.begin(57600);
XbeeRS.begin(57600);
pinMode(RX_XBee, INPUT); // Rx
pinMode(TX_XBee, OUTPUT); // Tx
pinMode(alim_XbeeRS, OUTPUT);
powerOn(XbeeRS);
xbee.setSerial(XbeeRS);
delay(5000);
Serial.println("XBee OP");
}
void loop()
{
if (end == 1)
{
Serial.println("sending");
ZBTxRequest _zbTx;
uint8_t payload[] = {'Y','E','S','\0'};
XBeeAddress64 address = XBeeAddress64 (0x13A200,0x4081B77C );
_zbTx = ZBTxRequest(address, payload, sizeof(payload));
Serial.println("sending");
xbee.send(_zbTx); // The program blocks here
}
else
{
Serial.println("waiting");
xbee.readPacket(100);
if (xbee.getResponse().isAvailable())
{
Serial.println("waiting 1");
if( xbee.getResponse().getApiId() == ZB_RX_RESPONSE)
{
Serial.println("waiting 2");
ZBRxResponse _rx;
xbee.getResponse().getZBRxResponse(_rx);
uint8_t* response= new uint8_t[50];
for(int i=0; i<_rx.getDataLength(); i++)
{
response[i] = _rx.getData()[i];
Serial.println(char(response[i]));
}
}
}
}
}
EDIT (additional information):
It doesn't change anything if I change the value type in the payload. About the baud rate, both of XBees are configured to 57600 baud. Here is the XBee's configuration:
ENDEVICE
COORDINATOR
The result from the serial port of this device is:
Finally, I use the Arduino ATmega 1284P. I really have no idea what kind of problem could do this.

There is some trouble :/
First, the default coordinator ADD is 0x0 0x0, so the line where
XBeeAddress64 address = XBeeAddress64 (0x13A200,0x4081B77C );
should be
XBeeAddress64 address = XBeeAddress64 (0x0,0x0 );
Then, is the Xbee at 57600 baud too?
To get an ACK, you can use:
if (xbee.readPacket(1000))
{
if (xbee.getResponse().getApiId() == ZB_TX_STATUS_RESPONSE)
{
xbee.getResponse().getZBTxStatusResponse(txStatus);
if (txStatus.getDeliveryStatus() == SUCCESS)
{
//It's sent
}
}
It could be from you payload too. You better use a hexadecimal value or int to be sure of what you send.
EDIT:
I see you don't use the last version of Xctu. Try it and test the direct communication between them to see if you can have direct contact between Coordinator and Routeur/End device.

Related

How to use RTCM data to achieve RTK?

I'm using this example from the Sparkfun Arduino Library
/*
Use ESP32 WiFi to get RTCM data from RTK2Go (caster) as a Client
By: SparkFun Electronics / Nathan Seidle
Date: November 18th, 2021
License: MIT. See license file for more information but you can
basically do whatever you want with this code.
This example shows how to obtain RTCM data from a NTRIP Caster over WiFi
and push it over I2C to a ZED-F9x.
It's confusing, but the Arduino is acting as a 'client' to a 'caster'. In this case we will
use RTK2Go.com as our caster because it is free. See the NTRIPServer example to see how
to push RTCM data to the caster.
You will need to have a valid mountpoint available. To see available mountpoints go here: http://rtk2go.com:2101/
This is a proof of concept to show how to connect to a caster via HTTP. Using WiFi for a rover
is generally a bad idea because of limited WiFi range in the field.
For more information about NTRIP Clients and the differences between Rev1 and Rev2 of the protocol
please see: https://www.use-snip.com/kb/knowledge-base/ntrip-rev1-versus-rev2-formats/
Feel like supporting open source hardware?
Buy a board from SparkFun!
ZED-F9P RTK2: https://www.sparkfun.com/products/16481
RTK Surveyor: https://www.sparkfun.com/products/18443
RTK Express: https://www.sparkfun.com/products/18442
Hardware Connections:
Plug a Qwiic cable into the GNSS and a ESP32 Thing Plus
If you don't have a platform with a Qwiic connection use the SparkFun Qwiic Breadboard Jumper (https://www.sparkfun.com/products/14425)
Open the serial monitor at 115200 baud to see the output
*/
#include <WiFi.h>
#include "secrets.h"
#include <SparkFun_u-blox_GNSS_Arduino_Library.h> //http://librarymanager/All#SparkFun_u-blox_GNSS
SFE_UBLOX_GNSS myGNSS;
//The ESP32 core has a built in base64 library but not every platform does
//We'll use an external lib if necessary.
#if defined(ARDUINO_ARCH_ESP32)
#include "base64.h" //Built-in ESP32 library
#else
#include <Base64.h> //nfriendly library from https://github.com/adamvr/arduino-base64, will work with any platform
#endif
//Global variables
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
long lastReceivedRTCM_ms = 0; //5 RTCM messages take approximately ~300ms to arrive at 115200bps
int maxTimeBeforeHangup_ms = 10000; //If we fail to get a complete RTCM frame after 10s, then disconnect from caster
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
void setup()
{
Serial.begin(115200);
Serial.println(F("NTRIP testing"));
Wire.begin(); //Start I2C
if (myGNSS.begin() == false) //Connect to the Ublox module using Wire port
{
Serial.println(F("u-blox GPS not detected at default I2C address. Please check wiring. Freezing."));
while (1);
}
Serial.println(F("u-blox module connected"));
myGNSS.setI2COutput(COM_TYPE_UBX); //Turn off NMEA noise
myGNSS.setPortInput(COM_PORT_I2C, COM_TYPE_UBX | COM_TYPE_NMEA | COM_TYPE_RTCM3); //Be sure RTCM3 input is enabled. UBX + RTCM3 is not a valid state.
myGNSS.setNavigationFrequency(1); //Set output in Hz.
Serial.print(F("Connecting to local WiFi"));
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(F("."));
}
Serial.println();
Serial.print(F("WiFi connected with IP: "));
Serial.println(WiFi.localIP());
while (Serial.available()) Serial.read();
}
void loop()
{
if (Serial.available())
{
beginClient();
while (Serial.available()) Serial.read(); //Empty buffer of any newline chars
}
Serial.println(F("Press any key to start NTRIP Client."));
delay(1000);
}
//Connect to NTRIP Caster, receive RTCM, and push to ZED module over I2C
void beginClient()
{
WiFiClient ntripClient;
long rtcmCount = 0;
Serial.println(F("Subscribing to Caster. Press key to stop"));
delay(10); //Wait for any serial to arrive
while (Serial.available()) Serial.read(); //Flush
while (Serial.available() == 0)
{
//Connect if we are not already. Limit to 5s between attempts.
if (ntripClient.connected() == false)
{
Serial.print(F("Opening socket to "));
Serial.println(casterHost);
if (ntripClient.connect(casterHost, casterPort) == false) //Attempt connection
{
Serial.println(F("Connection to caster failed"));
return;
}
else
{
Serial.print(F("Connected to "));
Serial.print(casterHost);
Serial.print(F(": "));
Serial.println(casterPort);
Serial.print(F("Requesting NTRIP Data from mount point "));
Serial.println(mountPoint);
const int SERVER_BUFFER_SIZE = 512;
char serverRequest[SERVER_BUFFER_SIZE];
snprintf(serverRequest, SERVER_BUFFER_SIZE, "GET /%s HTTP/1.0\r\nUser-Agent: NTRIP SparkFun u-blox Client v1.0\r\n",
mountPoint);
char credentials[512];
if (strlen(casterUser) == 0)
{
strncpy(credentials, "Accept: */*\r\nConnection: close\r\n", sizeof(credentials));
}
else
{
//Pass base64 encoded user:pw
char userCredentials[sizeof(casterUser) + sizeof(casterUserPW) + 1]; //The ':' takes up a spot
snprintf(userCredentials, sizeof(userCredentials), "%s:%s", casterUser, casterUserPW);
Serial.print(F("Sending credentials: "));
Serial.println(userCredentials);
#if defined(ARDUINO_ARCH_ESP32)
//Encode with ESP32 built-in library
base64 b;
String strEncodedCredentials = b.encode(userCredentials);
char encodedCredentials[strEncodedCredentials.length() + 1];
strEncodedCredentials.toCharArray(encodedCredentials, sizeof(encodedCredentials)); //Convert String to char array
snprintf(credentials, sizeof(credentials), "Authorization: Basic %s\r\n", encodedCredentials);
#else
//Encode with nfriendly library
int encodedLen = base64_enc_len(strlen(userCredentials));
char encodedCredentials[encodedLen]; //Create array large enough to house encoded data
base64_encode(encodedCredentials, userCredentials, strlen(userCredentials)); //Note: Input array is consumed
#endif
}
strncat(serverRequest, credentials, SERVER_BUFFER_SIZE);
strncat(serverRequest, "\r\n", SERVER_BUFFER_SIZE);
Serial.print(F("serverRequest size: "));
Serial.print(strlen(serverRequest));
Serial.print(F(" of "));
Serial.print(sizeof(serverRequest));
Serial.println(F(" bytes available"));
Serial.println(F("Sending server request:"));
Serial.println(serverRequest);
ntripClient.write(serverRequest, strlen(serverRequest));
//Wait for response
unsigned long timeout = millis();
while (ntripClient.available() == 0)
{
if (millis() - timeout > 5000)
{
Serial.println(F("Caster timed out!"));
ntripClient.stop();
return;
}
delay(10);
}
//Check reply
bool connectionSuccess = false;
char response[512];
int responseSpot = 0;
while (ntripClient.available())
{
if (responseSpot == sizeof(response) - 1) break;
response[responseSpot++] = ntripClient.read();
if (strstr(response, "200") > 0) //Look for 'ICY 200 OK'
connectionSuccess = true;
if (strstr(response, "401") > 0) //Look for '401 Unauthorized'
{
Serial.println(F("Hey - your credentials look bad! Check you caster username and password."));
connectionSuccess = false;
}
}
response[responseSpot] = '\0';
Serial.print(F("Caster responded with: "));
Serial.println(response);
if (connectionSuccess == false)
{
Serial.print(F("Failed to connect to "));
Serial.print(casterHost);
Serial.print(F(": "));
Serial.println(response);
return;
}
else
{
Serial.print(F("Connected to "));
Serial.println(casterHost);
lastReceivedRTCM_ms = millis(); //Reset timeout
}
} //End attempt to connect
} //End connected == false
if (ntripClient.connected() == true)
{
uint8_t rtcmData[512 * 4]; //Most incoming data is around 500 bytes but may be larger
rtcmCount = 0;
//Print any available RTCM data
while (ntripClient.available())
{
//Serial.write(ntripClient.read()); //Pipe to serial port is fine but beware, it's a lot of binary data
rtcmData[rtcmCount++] = ntripClient.read();
if (rtcmCount == sizeof(rtcmData)) break;
}
if (rtcmCount > 0)
{
lastReceivedRTCM_ms = millis();
//Push RTCM to GNSS module over I2C
myGNSS.pushRawData(rtcmData, rtcmCount, false);
Serial.print(F("RTCM pushed to ZED: "));
Serial.println(rtcmCount);
}
}
//Close socket if we don't have new data for 10s
if (millis() - lastReceivedRTCM_ms > maxTimeBeforeHangup_ms)
{
Serial.println(F("RTCM timeout. Disconnecting..."));
if (ntripClient.connected() == true)
ntripClient.stop();
return;
}
delay(10);
}
Serial.println(F("User pressed a key"));
Serial.println(F("Disconnecting..."));
ntripClient.stop();
}
on an ESP32 Thing Plus C with a ZED-F9P and it's working fine, but it only outputs RTCM data. How do I apply the RTCM data to the GPS data and achieve RTK? My goal is to have the ESP32 Thing Plus C output RTK Latitude and Longitude to the serial monitor.
Example output:
RTCM pushed to ZED: 163
RTCM pushed to ZED: 311
RTCM pushed to ZED: 1694
RTCM pushed to ZED: 1332
Any ideas would be appeciated! Thanks
Answered by PaulZC on Sparkfun Forum
Hi Jacob,
It sounds like everything is working OK. But, correct, there is
nothing in that example to actually print out the position.
Please try Example17. It is better-structured and uses callbacks to:
display your position; and push NMEA GGA data to the server. Some
NTRIP servers require the GGA data, others don't. If the GGA data
causes problems, you can comment this line to disable the push:
https://github.com/sparkfun/SparkFun_u- ... ck.ino#L81
Have fun! Paul

Splitting BLE findings and sending out to MQTT line by line using an ESP32

So I have two ESP32s for this project, one sending BLE scanned device info and the other ESP32 sending the scan results to an MQTT broker. I am currently facing the issue where I cannot break the results up into multiple JSON lines and send them out to the MQTT broker line by line. Please do let me know if you have any solutions. Thank you!!
#include <WiFi.h> //Remove when not MQTT-ing using WiFi
#include <PubSubClient.h>
const char* ssid = "--------";
const char* password = "+++++++++++";
#define RXD2 16
#define TXD2 17
WiFiClient espClient;
PubSubClient client(espClient);
// MQTT Broker
const char* mqtt_broker = "broker.hivemq.com";
const char* topic = "**********";
const int mqtt_port = 1883;
void setup() {
Serial.begin(115200);
Serial2.begin(115200, SERIAL_8N1, RXD2, TXD2);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connected to the WiFi network");
//connecting to a mqtt broker
client.setServer(mqtt_broker, mqtt_port);
while (!client.connected()) {
String client_id = "esp32-client-";
client_id += String(WiFi.macAddress());
Serial.printf("The client %s connects to the public mqtt broker\n", client_id.c_str());
if (client.connect(client_id.c_str())) {
Serial.println("Public hivemq broker connected");
} else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
}
}
}
void loop() {
// put your main code here, to run repeatedly:
String msg = "";
msg = Serial2.readString();
//String msg = "test MQTT";
// publish
int index = msg.lastIndexOf('}');
int length = msg.length();
String subMsg = msg.substring(index, length);
client.publish(topic,subMsg.c_str());
Serial.println("Message has been sent is: ");
Serial.println(subMsg.c_str();
delay(5000);
}
This is the output that I have:
{"Device Name":"GXHGA22CF3B9","EDID":"d4:0b:dd:2c:f3:b9","RTID":"FF005802600001F","RSSI":"-77"}
{"Device Name":"","EDID":"d7:9c:0e:1d:e6:a2","RTID":"FF005802600001F","RSSI":"-71"}
{"Device Name":"Buds2","EDID":"d8:4d:72:1f:80:15","RTID":"FF005802600001F","RSSI":"-75"}
{"Device Name":"KBPro_185309","EDID":"dd:34:02:06:33:a8","RTID":"FF005802600001F","RSSI":"-87"}
{"Device Name":"GXHGA2DAEC2A","EDID":"de:1e:da:da:ec:2a","RTID":"FF005802600001F","RSSI":"-86"}
{"Device Name":"","EDID":"e9:c7:1b:79:e1:41","RTID":"FF005802600001F","RSSI":"-76"}
{"Device Name":"","EDID":"e9:f5:80:7f:c8:ea","RTID":"FF005802600001F","RSSI":"-89"}
{"Device Name":"","EDID":"ef:e0:22:b2:c6:d0","RTID":"FF005802600001F","RSSI":"-84"}
{"Device Name":"GXHGA20A5D4A","EDID":"f6:4e:4d:0a:5d:4a","RTID":"FF005802600001F","RSSI":"-84"}
{"Device Name":"","EDID":"ff:65:fa:78:7f:c1","RTID":"FF005802600001F","RSSI":"-93"}
{"Device Name":"","EDID":"00:64:0f:26:92:09","RTID":"FF005802600001F","RSSI":"-90"}
Your current code finds the last } in the message and then takes that as the starting point for a substring to the end of the message. So you will always get a } character. You need to loop through the messages in a single read and find the start and end braces, pulling out each message.
Something like this:
void loop() {
// put your main code here, to run repeatedly:
String msg = "";
msg = Serial2.readString();
int start_idx = 0 ;
while( start_idx >= 0 )
{
start_idx = msg.indexOf('{',start_idx);
if ( start_idx >= 0 )
{
int end_idx = msg.indexOf('}',start_idx+1);
String subMsg = msg.substring(start_idx, end_idx+1);
client.publish(topic,subMsg.c_str());
Serial.println("Message has been sent is: ");
Serial.println(subMsg.c_str();
start_idx = end_idx + 1;
}
}
}
Note - this assumes that the JSON doesn't contain any objects - since the internal braces will also be separated. It also assumes you get complete JSON messages with each Serial read (i.e. they're not truncated). So you may need to handle these cases - but this should give you a start.
I've also removed the delay - I don't know why you'd want to delay for 5 seconds between reads - unless this was just for testing.

ESP32 Bluetooth connection status

I am running into some problems finding a solution when it comes to performing some form of Bluetooth connection check for my project that will allow me to have a connection status light.
My project consists of creating a Bluetooth speaker that has Led Strips controlled over Bluetooth serial (an app will be made to handle this) and audio stream over Bluetooth from a single ESP32.
I have found plenty of examples and had success with performing an spp callback event, however, of course this only works if I connect to the Bluetooth serial side of things through my 'Serial Bluetooth Terminal' app on my phone. If I just go into my phone Bluetooth list and connect to the audio side of things, nothing is registered, which isn't very useful for a Bluetooth speaker!
Basically I really need some help finding a way of registering that a device has connected to the Bluetooth audio so that I can have some form of indication light to tell the user that they are successfully connected to the speaker to play music.
Below is my code:
#include <btAudio.h> //<-------this is the library that I am using to handle Bluetooth audio to an external I2s DAC
#include "BluetoothSerial.h"
#include <FastLED.h>
TaskHandle_t Task1;
//POWER/BT-LIGHT-SETUP----------------------------------------
int powerPinR = 4;
int powerPinG = 16;
int powerPinB = 17;
bool BTisConnected;
//FAST-LED-STUFF----------------------------------------------
CRGB leds[NUM_STRIPS][NUM_LEDS];
CRGB leds_temp[NUM_STRIPS][NUM_LEDS/2];
//BLUETOOTH-SETUP---------------------------------------------
btAudio audio = btAudio("");
BluetoothSerial SerialBT;
//CONNECTION-CHECK--------------------------------------------
void callback(esp_spp_cb_event_t event, esp_spp_cb_param_t*param){
if(event == ESP_SPP_SRV_OPEN_EVT){
Serial.println("Client Connected");
BTisConnected = true;
}
else {
BTisConnected = false;
}
}
//------------------------------------------------------------
void setup() {
//CORE-1-INITIALISE
xTaskCreatePinnedToCore(
codeForTask1, /* Task function. */
"Task_1", /* name of task. */
1000, /* Stack size of task */
NULL, /* parameter of the task */
1, /* priority of the task */
&Task1, /* Task handle to keep track of created task */
0); /* Core */
//POWER/BLUETOOTH-CONNECTION-LIGHT-SETUP
pinMode(powerPinR, OUTPUT);
pinMode(powerPinG, OUTPUT);
pinMode(powerPinB, OUTPUT);
digitalWrite (powerPinR, HIGH);
digitalWrite (powerPinG, HIGH);
digitalWrite (powerPinB, HIGH);
//COOLDOWN-DELAY
delay(3000);
//AUDIO-INITIALISE
audio.begin();
int bck = 26;
int ws = 27;
int dout = 25;
audio.I2S(bck, dout, ws);
//LED-STRIP-SETUP-&-CLEAR-ALL
FastLED.addLeds<WS2812B,STRIP1PIN,GRB>(leds[0], NUM_LEDS);
FastLED.addLeds<WS2812B,STRIP2PIN,GRB>(leds[1], NUM_LEDS);
FastLED.clear();
FastLED.show();
//SERIAL-INITIALISE-&-CLIENT-CONNECTION-CHECK
Serial.begin(115200);
SerialBT.begin("Pilot"); //<-----BLUETOOTH NAME
SerialBT.register_callback(callback); //<-- SerialBT connection check works perfectly, but nothing for audio connection! :(
}
//CORE-0-VOID-LOOP--------------------------------------------
void codeForTask1( void * parameter )
{
for (;;) {
manageData();
delay(10);
}
}
//CORE-1-VOID-LOOP--------------------------------------------
void loop() {
BTconnectionCheck();
playScene();
}
//MANAGE-INCOMING-BLUETOOTH-SERIAL-DATA-----------------------------------------------
void manageData() {
//READ FROM SERIAL AND PARSE OUT ** READ FROM SERIAL AND PARSE OUT ** READ FROM SERIAL AND PARSE OUT **
char rawData[100] = "";
char keyword[] = "Mydata=";
if (SerialBT.available() > 0) {//new data in
size_t byteCount = SerialBT.readBytesUntil('\n', rawData, sizeof(rawData) - 1); //read in data to buffer
rawData[byteCount] = NULL;//put an end character on the data
const char delimiter[] = ",";
char parsedStrings[5][8]; //first number = how many bits of data - 2nd number = max size of eeach data
int dataCount = 0;
int dataPosition = 0;
char *token = strtok(&rawData[dataPosition], delimiter);//look for first piece of data after keyword until comma
if (token != NULL && strlen(token) < sizeof(parsedStrings[0])) {
strncpy(parsedStrings[0], token, sizeof(parsedStrings[0]));
dataCount++;
} else {
Serial.println("token to big");
strcpy(parsedStrings[0], NULL);
}
for (int i = 1; i < 5; i++) {
token = strtok(NULL, delimiter);
if (token != NULL && strlen(token) < sizeof(parsedStrings[i])) {
strncpy(parsedStrings[i], token, sizeof(parsedStrings[i]));
dataCount++;
} else {
Serial.println("token to big");
strcpy(parsedStrings[i], NULL);
}
}
if (dataCount == 5) {
scene = atoi (parsedStrings[0]);
hue = atoi(parsedStrings[1]);
saturation = atoi(parsedStrings[2]);
brightness = atoi(parsedStrings[3]);
eventInterval = atol (parsedStrings[4]);
}
}
}
//BLUETOOTH-CONNECTION-CHECK---------------------------------------------------------
void BTconnectionCheck(){
SerialBT.register_callback(callback);
if (BTisConnected == true){
bluetoothConnected();
}
else {
bluetoothSearch();
}
}
void bluetoothSearch(){
digitalWrite (powerPinR, LOW);
digitalWrite (powerPinG, LOW);
digitalWrite (powerPinB, HIGH);
}
void bluetoothConnected(){
digitalWrite (powerPinR, HIGH);
digitalWrite (powerPinG, LOW);
digitalWrite (powerPinB, HIGH);
}
I have cut lots of the code to do with the LEDs out but its still quite long, If it would help to have a more condensed version then I will chop it down further. Or if it helps to have the full code then I can also post it.
Any help would be greatly appreciated as I am well and truly stuck with this one and its a pretty important part of the project.
Thanks in advance!

sim800 cme erro2 when i pass at commands through code arduino esp32

I am trying to push sensor data to aws cloud database through sim800 gsm module.
I am able to do it by entering the at commands manually via serial monitor but when i incorporate the at commands in the code to automate the process so I don't have to enter commands manually I am getting cme error 3.
Please guide how to solve or identify the problem.
Code
#include <Arduino.h> //Arduino librabry...optional
#include <SPI.h>//SPI communication library
#define TINY_GSM_MODEM_SIM800
#include <TinyGsmClient.h>//library with GSM commands
HardwareSerial SerialGSM(1);
TinyGsm modemGSM(SerialGSM);
const int BAUD_RATE = 115200;
//Pin definition for RX and TX GPIO2 and GPIO4 are the pins in ESP32 Wroom
const int RX_PIN = 4, TX_PIN = 2;
//const char *APN = "";
//const char *USER = "";
//const char *PASSWORD = "";
//Initialize the gsm
void setupGSM() {
SerialGSM.begin(BAUD_RATE, SERIAL_8N1, RX_PIN, TX_PIN, false);
delay(3000);
Serial.println(modemGSM.getModemInfo());
delay(1000);
}
String sendAT(String command)
{
String response = "";
SerialGSM.println(command);
// aguardamos até que haja resposta do SIM800L
while(!SerialGSM.available());
response = SerialGSM.readString();
Serial.println(response);
return response;
}
void setup() {
Serial.begin(BAUD_RATE);
Serial.println("Starting the device");
Serial.println("Initializing GSM device");
setupGSM();
delay(5000);
SerialGSM.println("AT+CMEE=1");
}
unsigned long start;
void loop() {
//SerialGSM.println("AT+CMEE?");
sendAT("AT+CMEE?");
// SerialGSM.write("AT+COPS?\r\n");
delay(100);
//SerialGSM.println("AT+CSQ");
sendAT("AT+CSQ");
// if(SerialGSM.available()){
// Serial.write(SerialGSM.read());
// }
delay(100);
// SerialGSM.println("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"");
sendAT("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"");
delay(1000);
// SerialGSM.println("AT+SAPBR=3,1,\"APN\",\"www\"");
sendAT("AT+SAPBR=3,1,\"APN\",\"www\"");
delay(1000);
//SerialGSM.println("AT+SAPBR=1,1");
sendAT("AT+SAPBR=1,1");
delay(2000);
//SerialGSM.println("AT+HTTPINIT");
sendAT("AT+HTTPINIT");
delay(1000);
//SerialGSM.println("AT+HTTPPARA=\"CID\",1");
sendAT("AT+HTTPPARA=\"CID\",1");
delay(1000);
//SerialGSM.println("AT+HTTPPARA=\"URL\",\"http://ec2-18-217-119-145.us-east-2.compute.amazonaws.com:8000/?light=0&var=1&var2=2&var3=3&var4=4\"");
sendAT("AT+HTTPPARA=\"URL\",\"http://ec2-18-217-119-145.us-east-2.compute.amazonaws.com:8000/?light=0&var=1&var2=2&var3=3&var4=4\"");
delay(1000);
//SerialGSM.println("AT+HTTPACTION=0");
sendAT("AT+HTTPACTION=0");
delay(2000);
//start=millis();
//
// while(millis()-start<1000)
// {
// if(SerialGSM.available()){
// Serial.write(SerialGSM.read());
// }
// }
}

interfacing c++ to control motor stepper with arduino

I have tried to control motor stepper via arduino uno board with slider in visual C++.
but the servo didnot move at all.
here the program at PC side:
void CENVSConfigDlg::OnBnClickedButton1()
{
SetTimer(cTimer1,80,NULL);
}
void CENVSConfigDlg::OnTimer(UINT_PTR ID)
{
if(ID==cTimer1){
DWORD nbytes;
char buf[5];
sprintf(buf, "%d \n", val_test);
/* Open serial port. */
if(!WriteFile( hnd_serial, (void*)buf, 5, &nbytes, NULL )){MessageBox(L"Write Com Port fail!");return;}
}
and the program in arduino:
#include <Servo.h>
Servo servoMain;
int index=0;
String inputString;
void setup()
{
Serial.begin(9600);
servoMain.attach(9);
}
void loop()
{
int data;
while (Serial.available())
{
char inChar = (char)Serial.read();
if (inChar == '\n' || inChar == 'z')
{
data=stringToInt(inputString);
Serial.println(data); //
inputString="";
servoMain.write(data); //tambahannya
delay(50);
break;
}
if (inChar != 0)
{
inputString += inChar;
}
}
}
int stringToInt(String s)
{
char char_string[s.length()+1];
s.toCharArray(char_string, s.length()+1);
return atoi(char_string);
}
the pc i think is sending the data, but why the motor didnot working? any idea?
First off, does the serial link work at all? The number of ways that an RS232 link can not work, for both hardware and software reasons, is legendary. Unless you can show that the hardware can transfer data, it's pointless to look at your dedicated software. If you have a scope, use that to see if anything is being transmitted and then check that it arrives at the correct pin on the arduino input. If you have no access to a scope, a small LED and a 4.7K resistor can be used to indicate that there is data on the line - it will flicker with the data.