text:
ESP8266 HTTPS post body request with WifiClientSecure
Is there a way to post HTTPS body request in Arduino esp8266.
I am able to HTTPS parameter request with WifiClientSecure library,but is not safe compared to Request Body send in POST.

You do it like any other POST. It's just you happen to be using a secure client to make the connection.

Open the connection
Send the right headers, including a Content-Type and Content-Length and maybe a Content-Encoding if you encode it.
Send the body

It's not any different to an unencrypted POST request.

Can you provide me some example? or the format to include Request body with
a Content-Type and Content-Length and maybe a Content-Encoding as you said in point 2

Just look at any post request available on any of the millions of examples.

client.print(String("POST ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n"+
"Content-Length: " + data.length() + "\r\n" +
"Content-Type: application/json;charset=UTF-8\r\n\r\n"+
data +"\r\n");
data variable will contain json body?
Will this work??


text:
MQTT subscribe callback fails to be called in ESP8266 deepsleep mode
Refer to

ESP8266 deep sleep and MQTT

I executed the code in the given link. However i am not able to receive the subscribe message that are send from MQTT test broker(MQTT Lens) on the serial console.
Please help.
I am receiving successful call to both publish methods
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char* ssid = "honored";
const char* ss_pswd = "12345678";
const char* mqtt_server = "iot.eclipse.org";

void callback(char* topic, byte* payload, unsigned int length);
WiFiClient EspClient;

PubSubClient client(EspClient);

void wifi_setup() {
  Serial.print("Connecting to: ");
  Serial.println(ssid);
  WiFi.begin(ssid, ss_pswd);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}
void reconnect() {
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    String ClientId = "ESP8266";
    ClientId += String(random(0xffff), HEX);
    if (client.connect(ClientId.c_str())) {
      Serial.println("connected");
      client.publish("outtopic", "hello world, finally");
      client.subscribe("/room/test");
    } else {
      Serial.print("failed, rc=");
      Serial.println(client.state());
      Serial.println("Try again...");
      delay(5000);
    }
  }
}
void sendMQTTMessage() {
  Serial.println("sending your message");
  if (!client.connected()) {
    reconnect();
  }
  client.publish("/sensor/pir", "on");
}
void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived: ");
  Serial.println(topic);
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
  }
}

void setup() {
  Serial.begin(115200);
  wifi_setup();
  client.setServer(mqtt_server, 1883);
  sendMQTTMessage();
  client.setCallback(callback);
  delay(2000);
  Serial.println("going into deep sleep");
  ESP.deepSleep(10 * 1000000);
}

void loop() {

}

Once you enter deepsleep the processor will not be woken up by anything but the reset pulse after the deepsleep time expired. Your callback will never be called. Also once you enter Deepsleep you switch off your WiFi connection, no chance of receiving data. Read https://diyprojects.io/esp8266-deep-sleep-mode-test-wake-pir-motion-detector/#.XNGv1UOxWAk

Deep sleep proves useless if there are such restrictions in web based application. How do i save battery and do subscribe call? looks like i have to giveup one or another.

My solution:
update_mqtt() is called before deepSleep
PubSubClient mqtt_client(client);
boolean cb = false;

void callback_mqtt_switch(char* topic, byte* payload, unsigned int length) {
  String lowerstr = "";
  for (uint8_t i = 0; i < length; i++) {
    lowerstr += (char)payload[i];
  }
  lowerstr.toLowerCase();
  DebugOut("Sleep payload: " + lowerstr);
  if (!back_to_sleep) {
    sleep_on = lowerstr == "ein";
  }
  cb = true;
}

void update_mqtt() {
  int i = 0;
  while (!cb && i++ < 30) {
    mqtt_client.loop();
    delay(10);
  }
  #ifdef TEST
    Serial.print("Warte ");
    Serial.println(i * 10); // max. 300ms gewartet
  #endif
  cb = false;
}

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
ESP8266 http.get() issue due to wifi authentication failure
Facing a weird issue while reading data from esp8266.
I am trying to read dynamic data from a demo text file on test server on same network in deep sleep mode.
Case1: Joining new network
I am using WifiManager to join network and then followed by http.get()
However whenever i try to join the wifi with correct credentials it does not connect sometimes. Post some time ,if i try to wake the device it automatically connects and displays the data.
Case2: Rejoining existing network
Similar issue happens when i stop the test server and update the text file contents and up the server and try to read it on esp8266. It ask me the credentials again which it should have remembered 1st time. Post some time, if i try to wake up device sometimes it automatically connnects and prints updated value.
I am unable to figure out the problem here and its solution.
Any suggestion please.
#include <WiFiManager.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <Arduino.h>
#include <ESP8266httpUpdate.h>

ESP8266WiFiMulti WiFiMulti;
HTTPClient http;
WiFiManager manager;

  int publishPin = 0;
  int wifiPin = 5;
  unsigned int baud = 115200;
  const char* url3 = "192.168.43.215";
  const int httpsPort = 80;

  const String macValue = WiFi.macAddress();

 void publishData()
 {
    String link = "/one.txt";
    Serial.print("connecting to ");
    Serial.println(url3);

    http.begin("http://192.168.43.215/one.txt");

    int httpCode = http.GET();
    if (httpCode > 0) {
    if (httpCode == HTTP_CODE_OK) {
      Serial.println("This device is authorized!");
      Serial.println(http.getString());
      Serial.println(httpCode);

    }else {
    Serial.println("Failed to connect to API.");
    Serial.println(httpCode);
    return;
  }

  http.end();
  delay(1000);
}

void restPublish(){
  Serial.println("Rest publish");

  publishData();

}

void setup()
{
  Serial.begin(115200);
  Serial.println("setup2");

  manager.autoConnect("espdevice");
  restPublish();

 Serial.println("entering deepsleep now. DND");
 ESP.deepSleep(0);

}

void loop()
{
}

I didn't see any point where you are trying to connect to WIFI. 2. As far as I understand you had create a local network over your laptop using some APACHE or something else. As your question that sometimes you are not connecting to the server, for connection your client and server must be on the same network to connect. Please make sure that your local sever and esp device must be connected to the same network

I would try some small delays between connecting and publishing and between publishing and deep sleep

Thanks for the reply Vaibhav,
Above it did mention i have the client and server running on the same network and i am using nginx as the server.
Case1, is the code newly installed on ESP so it will get me webpage for 1st time configuration.
Case 2 i made clear about network, it doesnot join the wifi

Thanks juraj,  it works i think it needed some delay. i will do some more testing on it.

you could search for more exact solution. there are some recommendations on what to do before deepSleep. and you can test if the wifi is connected. delay() calls yield() which performs 'background' tasks...

Could you share some links for recommendation before deep sleep.
Yes i will work on check wifi connection. thanks

now I see you have a delay in restPublish() at  the end

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
How can I discard power from a device I want to read from?
I want to read the data line from a device that normally interfaces with a controller. It has 3 pins, 3.3v power, gnd, and data. I don't need the power line since the Arduino will be USB powered and I obviously don't want to just connect it straight to ground. What would be the best way to handle this without introducing extra hardware components. Can I just connect the power to an input pin, and then I can use that to see if the device is on?
I'm using an Arduino Mega2560

What is the "device that normally interfaces with a controller"? If the device is meant to talk to a controller or Arduino and provides power, ground and data, it's likely that you now need to provide the 3.3V so the device has power to operate. But perhaps it's a passive device? Tell us more.

No, I'm connecting to the controller socket of a Nintendo 64. The Nintendo is powered, and normally supplies power to a controller. I want my Arduino to be a controller.

Only connect data and gnd. Assuming the data pin is an output of the N64 and the Arduino only reads it. Otherwise you would need some voltage shifting circuit, as the N64 is 3.3V and the Mega is 5V. Beside that, I'd add a resistor between the data and the arduino INPUT, so you can't damage any of the two device if they aren't power on and off at exactly the same time.

You don't need to "discard" power. You just ignore it.
If you don't need a connection, then don't connect it.  The only important connection is the ground connection. Everything else can be used, or not used, at your discretion.
There's nothing "magical" about a power connection. It's just a voltage that comes from a source that happens to be able to provide more current.  If you want to use it to power something, you can. If you want to just sense what the voltage is, you can. If you want to ignore it, you can.
It's not like a mountain: just because it's there, it doesn't mean you have to climb it...

I believe you want to check whether your device is on or not without drawing power from it. Something like the following circuit could be useful:

simulate this circuit – Schematic created using CircuitLab
R2 limits the current going into Arduino input pin. Resistor with value around 1K should be good given the voltages you mentioned. Arduino can read the input pin to see whether the device is on or off.
R1 pulls Arduino input pin to ground in when the device is off. This gives a "0" value at the input pin. R1 can be a high value ~10K. High value would limit current leakage to ground via R1.
Though this answer won't exactly satisfy your requirement of not using additional components.


text:
Issue with Indenting the Serial Print data in the Serial Monitor
I have a question with Serial Print. I want the Sensor reading values to fall under 3 columns, and each column should have the readings from the same sensor.
Raw Value |    Sensor 1 |   Sensor 2  |   Sensor 3
how can I modify this code do this?
Below I have posted my code and what I currently see using the Serial Monitor
    void loop(){

  RawValue0 = analogRead(analogIn0);
  Voltage0 = (RawValue0 / 1023.0) * 5000; // 5000 to get millivots.
  tempC0 = (Voltage0-500) * 0.1; // 500 is the offset
  tempF0 = (tempC0 * 1.8) + 32; // conver to F
  Serial.print("Raw Value = " );  // shows pre-scaled value
  Serial.print(RawValue0);
  Serial.print("\t milli volts = "); // shows the voltage measured
  Serial.print(Voltage0,0); //
  Serial.print("\t Sensor 1: Temperature in C = ");
  Serial.print(tempC0,1);
  Serial.print("\t Sensor 1: Temperature in F = ");
  Serial.println(tempF0,1);
  delay(500);

you have no code for dealing with sensor 2 and sensor 3 ..... there is no way to modify non-existent  code

is this schoolwork?

you already know how to print in column format .... it is entirely unclear what you are having a problem with

think  very carefully about this .... do you really want Raw Value | Sensor 1 | Sensor 2 | Sensor 3?

Columns with lines?
The sprintf function can fill data with spaces to align them. However, the Arduino sprintf function does not support floating point variables. The dtostrf function has already a fixed output width by itself.
The sketch below is a combination of UTF-8 characters and the dtostrf and sprintf functions.
void setup() {
  Serial.begin(9600);

  Serial.println();
  Serial.println("┏━━━━━━┳━━━━━━━━┳━━━━━━━━┓");
  Serial.println("┃  raw ┃   °C   ┃   °F   ┃");
  Serial.println("┣━━━━━━╋━━━━━━━━╋━━━━━━━━┫");
}

void loop() {
  int raw = random(0, 1024);
  float c = random(-1000, 1000) / 10.0;
  float f = random(-500, 1500) / 10.0;

  char buffer_c[20];
  char buffer_f[20];

  dtostrf(c, 6, 1, buffer_c);
  dtostrf(f, 6, 1, buffer_f);

  char buffer[80];
  sprintf(buffer, "┃ %4d ┃ %s ┃ %s ┃", raw, buffer_c, buffer_f);
  Serial.println(buffer);

  delay(500);
}

The strlen() function can not be used before printing a floating point number to the serial port, since its length is determined while printing characters to the serial port. The final number of bytes that is written is the return value.
There is a way to use that return value, by using a dummy write to a dummy serial port. After that the number of spaces to align the floating point number can be calculated.
That reduces the code size from 6160 to 4708 for an Arduino Uno.
class DummyClass : public Stream
{
  int available() {return 0;}
  int read() {return 0;}
  int peek() {return 0;}
  void flush() {return;}
  size_t write(uint8_t) {return 1;}
  using Print::write;
};

DummyClass Dummy;

const int width_r = 4;
const int width_c = 6;
const int width_f = 6;

void setup() {
  Serial.begin(9600);

  Serial.println();
  Serial.println("┏━━━━━━┳━━━━━━━━┳━━━━━━━━┓");
  Serial.println("┃  raw ┃   °C   ┃   °F   ┃");
  Serial.println("┣━━━━━━╋━━━━━━━━╋━━━━━━━━┫");
}

void loop() {
  int raw = random(0, 1024);
  float c = random(-1000, 1000) / 10.0;
  float f = random(-500, 1500) / 10.0;

  int i;
  Serial.print("┃ ");
  Spaces(width_r - Dummy.print(raw));
  Serial.print(raw);
  Serial.print(" ┃ ");
  Spaces(width_c - Dummy.print(c,1));
  Serial.print(c,1);
  Serial.print(" ┃ ");
  Spaces(width_f - Dummy.print(f,1));
  Serial.print(f,1);
  Serial.print(" ┃");
  Serial.println();

  delay(500);
}

void Spaces(int n)
{
  for(int i=0; i<n; i++) {
    Serial.print(' ');
  }
}

I advise not to use this "Dummy" trick. It is mere a coding exercise. I can not find a problem with this trick, but I'm not 100% sure that it is okay.

use dtostrf for raw too and and save 1kB flash on sprintf

@Juraj I can do better than that. After reading your answer here: https://arduino.stackexchange.com/questions/62783/create-new-serial-class-inheriting-from-stream I tried a dummy class. To my surprise it worked.

Here is a sketch that uses a different approach than Jot uses in his answer. There is no question that Jot's answer is excellent and takes very few lines of code to accomplish.
I thought it would look nice if the Raw Value, an integer, was centered under the "Raw Value" column when it was at it's maximum value of 1023. A value of 1 would be right-ish justified, but still aligned with the center in mind.
The floating point numbers, which could be positive or negative, should be right justified I thought, so I wrote a second function to deal with those numbers.
int RawValue0;
float Voltage0, tempC0, tempF0;

void setup(){
  Serial.begin(9600);

  Serial.println();
  Serial.println("Raw Value | Sensor 1 | Sensor 2 | Sensor 3");
  Serial.println("------------------------------------------");

  RawValue0 = 1023; //analogRead(analogIn0);
  Voltage0 = 11.0; //(RawValue0 / 1023.0) * 5000; // 5000 to get millivots.
  tempC0 = -100.0; //(Voltage0-500) * 0.1; // 500 is the offset
  tempF0 = 1212.0; //(tempC0 * 1.8) + 32; // conver to F
}

void loop(){

  // Increment the variables to simulate test data.
  RawValue0 += 51;
  if(RawValue0 > 1023){RawValue0 = 0;}
  Voltage0 += 99.99;
  if(Voltage0 > 9999.99){Voltage0 = 0.0;}
  tempC0 -= 99.99;
  if(tempC0 < -9999.99){tempC0 = 0.0;}

  // Print out the data in columns.
  printNumber(RawValue0);
  Serial.print("   | ");
  printNumber(Voltage0);
  Serial.print(" | ");
  printNumber(tempC0);
  Serial.print(" | ");
  printNumber(tempF0);
  Serial.println();
  delay(250);
}

long printNumber(int number){
  Serial.print("   ");
  int spaces = 0;
  if(number < 1000){spaces = 1;}
  if(number < 100){spaces = 2;}
  if(number < 10){spaces = 3;}
  for(int i = 0; i < spaces; i++){
    Serial.print(" ");
  }
  Serial.print(number);
}

float printNumber(float number){
  int spaces = 0;
  if(number > -1000.00){Serial.print(" ");}
  if(number < 1000){spaces = 1;}
  if(number < 100){spaces = 2;}
  if(number < 10){spaces = 3;}
  if(number < 0){spaces = 0;}
  if(number == -99.99){spaces = 1;}
  for(int i = 0; i < spaces; i++){
    Serial.print(" ");
  }
  Serial.print(number);
}

When I compile Jot's sketch, it's 6640 bytes. If you remove his "fancy" header, it drops to 6414 bytes. My sketch is 5124 bytes. There is a certain amount of "overhead" involved when using sprintf().
The question you have to ask yourself is, "Does saving 1000 bytes matter?".


text:
Ethernet Shield: Maximum speed
Looking at this shield here: https://store.arduino.cc/arduino-ethernet-shield-2
It states that "Connection speed: 10/100Mb". However from looking at various forums it appears that no one can get much more than 300Kb/sec with this device?
Can anyone explain what causes this limitation and how to overcome it? If its SPI that is the bottleneck is there some alternative? I am looking to get speeds of 6 mega bytes per second or more using a TCP connection.
I am extremely new to all this so apologies if I've missed something extremely obvious here. I also had a look at bluetooth/wifi shields but it appears they seem to also have some similar throughput issues. USB looked like it could work but is extremely complex for a newbie.

If you have a caravan that is rated at up to 50 mph, and you attach it to a 50cc scooter, do you think you will be able to get the full 50 mph out of it?

Also: what do you want to do with all that data? Or how are you hoping to generate so much data so fast?

The data will be streamed from a PC into a games console, the stuff I am adding will sit in the middle

"Sit in the middle"... what does that even mean?

@paulm According to your description, that PC is the best place to put that "man in the middle". However this is more like XY problem

you would have a hard time getting a reliable and constant 6MBs from a 10/100 network no matter what you hook up to it; 2/3rd utilization is respectable, so unless there's no other traffic, you're already close to the limit.

It's not just the SPI what limits overall speed. You also need some proccessing power, and AVR based Arduinos lacks of it. It all depens what do you want to do with data.
If you need some serious processing power, it might be better to use something much more powerfull, like raspberry PI with real operating system. You can even run some web server at the speeds you can't even imagine with Arduino with the ethernet shield

Would it be possible to do it without needing a full blown OS? For just passing data between devices at higher speeds it feels like overkill?

@paulm Of course it's possible. If you are a billion dollar company that Broadcom is willing to release the datasheet for the Pi's SoC to... And if you're a good programmer that understands all the underlying hardware.

Maybe FPGAs? Though it might be a really tricky and much work to program them for implementing ethernet.

A guy on this forum reports achieving 100 Kbyte/sec with a W5100 ethernet shield, which would be 800 kbit/sec:
https://forum.arduino.cc/index.php?topic=555957.0


text:
tty doesn't list ttyUSB0 so arduino doesn't list serial ports
Okay so lsusb gives
Bus 002 Device 019: ID 1a86:7523 QinHeng Electronics HL-340 USB-Serial adapter
dmesg|grep 'ttyUSB' gives
[63723.589107] usb 2-1: ch341-uart converter now attached to ttyUSB0
but tty lists only /dev/pts/0 although in /dev there is a ttyUSB0 file (or whatever it is because vim says its not a file)
I can use cu -l /dev/ttyUSB0 -s 9600 and transmit to arduino nano as the rx LED blinks. On starting arduino I get the "java.lang.NullPointerException thrown while loading gnu.io.RXTXCommDriver" error.
System: Linux Mint 19.1 Tessa (64 bit)

tty tells you the terminal device that your current terminal session is connected to. Nothing to do with listing what terminal devices are available.

You are assuming a problem with serial ports. That is unlikely to be the case. Your real problem is something to do with the Arduino IDE's programming. What version of the IDE are you using and how did you install it?

I agree with Majenko and also don't believe it has anything to do with your ports. The exceptions you mentioned look like there is something wrong with your environment, maybe updating the arduino IDE or java itself will help. You could also check if the problem persists when using an older version of the IDE

To be sure that has nothing to do with the ports/serial communication, I suggest reading out the atmega with avrdude manually

Sorry, I was using the software center to get arduino IDE and that didn't work well. Downloading the official IDE from arduino.cc worked without hassle. Lesson learnt: Not all linux distros have package repos as up-to-date as Arch. :P


text:
Sim800 FTP Arduino
I've been unable to FTP anything using an Arduino and SIM800L. I have reduced the code as far as possible:
#include <SoftwareSerial.h>

//Create software serial object to communicate with SIM800L
SoftwareSerial mySerial(3, 2); //SIM800L Tx & Rx is connected to Arduino #3 & #2

String moduleAnswer = "";

void setup()
{
  //Begin serial communication with Arduino and Arduino IDE (Serial Monitor)
  Serial.begin(9600);

  //Begin serial communication with Arduino and SIM800L
  mySerial.begin(9600);

  Serial.println("Initializing...");
  delay(1000);

  SoftwareATCommand("AT"); //Once the handshake test is successful, it will back to OK
  SoftwareATCommand("AT+CSQ"); //Signal quality test, value range is 0-31 , 31 is the best
  SoftwareATCommand("AT+CCID"); //Read SIM information to confirm whether the SIM is plugged
  SoftwareATCommand("AT+CREG?"); //Check whether it has registered in the network

  //APN and GRPS Setup
   SoftwareATCommand("AT+SAPBR=0,1"); //Close GPRS before connecting
   SoftwareATCommand("AT+SAPBR=3,1,\"Contype\",\"GPRS\""); //Configure bearer profile

  SoftwareATCommand("AT+SAPBR=1,1"); //Connect to GPRS

  //FTP Connection
  SoftwareATCommand("AT+FTPCID=1");
  SoftwareATCommand("AT+FTPSERV=127.189.249.205"); //Not real IP
  SoftwareATCommand("AT+FTPPORT=21");
  SoftwareATCommand("AT+FTPUN=user");
  SoftwareATCommand("AT+FTPPW=pass");

  //FTP Upload
  uploadFTP();

 }

void loop()
{
}

void uploadFTP()
{
  SoftwareATCommand("AT+FTPPUTNAME=\"test.txt\""); //Filename
  SoftwareATCommand("AT+FTPPUTPATH=/home/arduino/SolarDataLogger/"); //Path
  SoftwareATCommand("AT+FTPPUT=1"); //Start FTP
  delay(10000);
  SoftwareATCommand("AT+FTPPUT=2,100"); //Send 100 bytes of data
  delay(10000);
  SoftwareATCommand("Hello12345"); //Send Data
  SoftwareATCommand("AT+FTPPUT=2,0"); //Close FTP

}

String SoftwareATCommand(String strAT)
{

  String strNotice = "Sending: " + strAT;
  Serial.println(strNotice);
  mySerial.println(strAT);

  delay(500);
  moduleAnswer = "No Response";

  while(mySerial.available())
  {
    moduleAnswer = mySerial.readString();

    char* buf = (char*) malloc(sizeof(char)*moduleAnswer.length()+1);
    moduleAnswer.toCharArray(buf, moduleAnswer.length()+1);
    Serial.write(buf);//Forward what Software Serial received to Serial Port
     - Module answer sent to screen
    free(buf);
   }

   return moduleAnswer;
}

The serial output where the trouble is:

I've tried waiting longer for the +FTPPUT: 1,1,1360 response or sending something twice, but nothing seems to work. The file gets created but no other data is ever sent.

Maybe its too late to respond but the line +FTPPUT: 1,65 indicates a server error.
https://www.elecrow.com/wiki/images/2/20/SIM800_Series_AT_Command_Manual_V1.09.pdf - page 275.
Please check a sequence of commands , maybe something is missing ?
I use the following sequence :
"AT+CREG?"
"AT+SAPBR=3,1,\"Contype\",\"GPRS\""
"AT+SAPBR=3,1,\"APN\",\"NAME OF YOUR PROVIDER \""
"AT+SAPBR=1,1"
"AT+SAPBR=2,1"
"AT+FTPCID=1"
"AT+FTPSERV=\"SERVER ADDRESS\""
"AT+FTPPORT=21"
"AT+FTPTYPE=\"I\""
"AT+FTPUN=\"USERNAME\""
"AT+FTPPW=\"PASSWORD\""
"AT+FTPPUTNAME=\"" + NAME OF FILE + "\""
"AT+FTPPUT=1"
"AT+FTPPUT=2," + STRING OF BUFFER SPACE ( Get from response of FTPPUT=1 )
"AT+FTPPUT=2,0"

Look on the manual for the commands above.
Sorry about my grammar

Thanks for the input. I posted this after moving to a Pi instead for anybody else that might run into the same issue and I think your input will be useful to someone.

what I observed in your code-I think you did not follow the proper sequence of connecting the GPRS context mentioned in the sim800l datasheet.
Please follow the section 3.1. bearer configuration. I also attached the screenshot herewith. So you missed setting the Access Point Name(APN). After you query the GPRS context(last step in the image), if you get the proper IP address, then you are sure to send the data over FTP. Please follow the FTP sequence mentioned in the datasheet.


text:
Interfacing MPU6050 with Arduino uno
What is the meaning of "volatile bool mpuInterrupt = false; " in Arduino Program interfacing MPU6050?

what program? I would guess it is a flag set in interrupt triggered by the MPU6050 indicating to the reset of the sketch that the interrupt was triggered

The i2cdevlib has that declared in this file: https://github.com/jrowberg/i2cdevlib/blob/master/Arduino/MPU6050/examples/MPU6050_DMP6/MPU6050_DMP6.ino
That is the "dmp" example.
Inside the MPU-6050 sensor is a "dmp" and a FIFO buffer. The "dmp" is a processing unit that collects the sensor data, does some calculations and puts the data in the FIFO buffer. After that the Arduino is signalled with a interrupt.
In the Arduino, in the interrupt routine, the flag 'mpuInterrupt' is set. In the loop() that flag is checked and the amount of data in the FIFO buffer is read. When there is enough data, that data is read and used in the sketch.
Since the variable 'mpuInterrupt' is used in a interrupt routine and in the loop(), it is made 'volatile'. That tells the compiler that the variable can change at any moment, so the compiler can keep that in mind when creating binary code for the loop().

Thanks for answering! I got it. From where did u get all this knowledge... any book you can prefer?

@SohamPrajapati I know the mpu-6050 and the i2cdevlib a little. Setting a volatile bool variable in a interrupt routine to 'true' and dealing with that in the loop() is something common for arduino.


text:
Serial.write printing blank values
I've got an Adafruit Bluefruit NRF52 hooked up to the Adafruit BNO055 9-axis orientation sensor, but when I use Serial.write to send the data, serial monitor displays blank values only. The scroll bar drops so something I definitely appearing, it just seems to be empty.
Serial.print works fine, but I cannot use this for my application, as it uses too much memory.
I'm gathering 3 axis of absolute orientation plus 3 axis of acceleration (6 floats in total) plus a three digit number representing the calibration of each sensor.
Each line should look something like
303 68.69   4.19    -2.19   -0.12   0.14    -0.40

My code:
void displayCalStatus(void)
{

  uint8_t system, gyro, accel, mag;
  system = gyro = accel = mag = 0;
  bno.getCalibration(&system, &gyro, &accel, &mag);

  /* Display the individual values */
  Serial.write(gyro);
  Serial.write(accel);
  Serial.write(mag);
  Serial.write("\t");
}

void loop()
{
  imu::Vector<3> accel = bno.getVector(Adafruit_BNO055::VECTOR_LINEARACCEL);

  /* Get a new sensor event */
  sensors_event_t event;
  bno.getEvent(&event);

  displayCalStatus();

  /* Display the floating point data */
  Serial.write(event.orientation.x);
  Serial.write("\t");
  Serial.write(event.orientation.y);
  Serial.write("\t");
  Serial.write(event.orientation.z);
  Serial.write("\t");

    /* Display the floating point data for Linear Acceleration */
  Serial.write(accel.x());
  Serial.write("\t");
  Serial.write(accel.y());
  Serial.write("\t");
  Serial.write(accel.z());
  Serial.write("\n");
}

write transfers a byte, you want print text. replace all write with print

As mentioned, I cannot use print because it uses too much memory. I'm using Serial for debug but am sending over bleuart in prototype. I'm recording high speed, high fidelity movement and so I need the ble connection interval down to 20ms minimum, which means getting the transfer size down. Do you know if there are workable alternatives to print?

This is not good coding: system = gyro = accel = mag = 0; Instead, explicitly set each one to zero.

but you want see the number as text or not? if you write(5) you send a  nonprintable byte. if you print(5) it will print "5". imu::Vector takes much more space then C array

system = gyro = accel = mag = 0; is from the example provided by Adafruit, not my own. Either way that doesn't solve the problem of printing blank values.

I don't need text, just the float, but whole number would do

you print tabs and new line. that is text. if you want to see a number in Serial Monitor you must print it as text with print

Ok thanks for the clarification. Since I will be sending over bleuart ultimately, do you know if there is an alternative for me to send the values alone, without tabs and new line text?

The float values you want to send are 4-bytes long. Serial.write sends 1 byte. To send the raw value, you must send each byte individually, usually by bit-shifting. You would probably do well to send some kind of "end of packet" value to indicate to the receiver that you have now sent all values (in case one gets lost or skipped, the receiver can reset to expect the first value, etc.)

even then you need delimiters, but then you don't know what is a value and what a delimiter so you need a delimiter byte and escaping of the delimiter byte by repeating it twice in data

If all values are 4 byte and the number of values sent each round is the same, there is no need for delimiters, though it could improve robustness.

I see. I am unsure how to do this. Are you able to provide an example which I may be able to use?

Problem 1:
You wish to send/display on the Serial Monitor the int and float values generated by your sensor, but Serial.print() uses too much memory.
Solution 1:
Optimize your sketch to use less memory.

Problem 2:
Serial.write() doesn't cause the values to show up on Serial Monitor, but something is getting sent, because I see scrolling activity.
Solution 2:
Serial.write() sends raw bytes, whereas Serial.print() converts a variable to a string (or series of ASCII bytes) and sends that string. For example, Serial.write(65) sends A to the Serial Monitor because the ASCII value of A is 65; Serial.print(65) sends 65 to the Serial Monitor because it converts the numeric value 65 into a string containing the character 6 and the character 5, and sends that string to Serial Monitor.
The Serial Monitor expects only ASCII data. You are using Serial Monitor for development/debugging, but your final application does not require ASCII, only to transmit the numbers.
Serial.write() comes in a few forms. One is Serial.write(val) which sends a single byte (named val, of type byte or compatible). Another is Serial.write(buf, len) which sends a series of len bytes, starting at the address of memory pointed by by buf. (This is often when buf is an array of bytes, so buf points to the first element of the array.)
If you wanted to send the 4 bytes of a float using Serial.write(), you could call:
Serial.write(&(event.orientation.x), sizeof(event.orientation.x);

As an alternative, you can use bit shifting to send one byte at a time of the 4-byte float:
Serial.write((byte)((event.orientation.x & 0xFF000000) >> 24);
Serial.write((byte)((event.orientation.x & 0x00FF0000) >> 16);
Serial.write((byte)((event.orientation.x & 0x0000FF00) >>  8);
Serial.write((byte)((event.orientation.x & 0x000000FF)      );

On the receiving end, you need to reconstruct your float by doing the reverse.
But you have multiple 4-byte values to send, in rapid repeating loop, so what happens if your receiver and transmitter get out of sync? Then you might want to put in a "flag" value to indicate the start of a sequence of data and a different flag for the stop of a sequence of data. What happens if your start or stop "flag" value actually shows up as one of the bytes you send as part of a real data byte? Then you need to find some way to modify the "real" data so that it's not to be construed as a flag.
This looks to be getting complicated now? Fortunately, these problems have existed and been solved for decades. Unfortunately, there is no consensus on the best or right way.
I did a quick search and found this arduino library that facilitates packet-based serial communication:
https://github.com/bakercp/PacketSerial
Perhaps that can help you take a bundle of numbers and send them reliably to some other system. I don't know that library in particular, and there are probably others that do something similar. This one claims to be compatible with the PySerial, COBS, and SLIP modules for dealing with packetized serial data communications.


text:
Split up Arduino code into multiple files using Arduino IDE
I am working on a very long code that requires multiple functions defined. I want to split the code into two files as main code ("Feeder_Control" in the screenshot) and functions ("connections" in the screenshot) How to import the second file into main code to use its functions?
PS: In C/C++ same thing is done with #include "connections.h". How is it done in Arduino IDE.
.

Though the accepted answer works, I feel while the Arduino "IDE" is great for beginners but it doesn't quite scale well beyond a couple of files. I'd highly recommend checking out platformio as it provides much better project management via integration with atom and vscode, enables you to work with different frameworks including Arduino for AVR, STM32, ESP8266, ESP32 etc and supports debugging if you have the required hardware.

Don't cross post. You already asked this on SO.

There is no need to use an #include directive for the additional .ino file.
Before compilation starts, the Arduino IDE concatenates all .ino files in your sketch into a single file, starting with the .ino file that matches the sketch folder name, followed by the rest of the .ino files in alphabetical order. So there is no difference between one massive .ino file and breaking the same code among multiple .ino files, other than the greater ease of navigating the code via tabs. After a bit more processing, this file is compiled as C++.
Reference:
https://arduino.github.io/arduino-cli/latest/sketch-build-process/#pre-processing

Two comments to answer by per1234 (although old):
You can have multiple .ino files in a project. However:

You can not separate the preprocessor portion from the main file (The file with the project's name) which must include ALL preprocessing.
Arduino IDE compiles all files in a project in a specific order (alphabetically by filename) and includes them into the main .ino file during the linking stage.
Code in later .ino files can access variables and functions defined in earlier ones, but not vice versa.

Please link to the answer and/or state who posted it, rather than saying "answer#1" - the order of answers changes over time, and depending upon the type of ordering selected. Please [edit] and update your answer.

the details you mention, are in the linked page. per1234 is the the tester for Arduino CLI at Arduino and main author of the Arduino CLI documentation including the linked page.

what is that about the preprocessor? there is no such limitation.

Code in later .ino files can access variables and functions defined in earlier ones, but not vice versa That's correct for variables, but not for functions: When concatenating all .ino files into a single .cpp, function prototypes from all .ino files are generated and added to the start of that .cpp file. If that works well, all functions can be used from any part of your code. And it's a good idea to collect all global variables in the projectname.ino file, which comes first in the .cpp concatenation.

Thanks for the details. Yet, I have a main file and in it a large portion of building HTML (or CSS) output code. That HTML portion is currently located in the root of the main. I wish to move it out to a separate file, but it is not defined as an Arduino function and thus it has no prototype function and will not be linked.
Can I define it as a function?
What is the best way to proceed?
Thx

Can I define it as a function? What is the best way to proceed? the question depend on what are the files and data are under one translation unit. There are also  extern storage class specifier that can be used to tell the compiler that a variable is defined externally in a different translation unit.


text:
Can we call GPRS HTTP request asynchronously in Arduino?
Usually GPRS modules (SIM800,900, A6, etc) that used with arduino are called in synchronous way in HTTP (GET/POST) request. It takes more than 10 seconds in most times and this makes the system very slow. Is there a way to use them (libraries or the module) asynchronously (or is there any alternatives) and perform these request in background while main business is being done?

Sure there is. All you're doing is reading and writing serial data. All you have to do is learn how to do that without blocking.
Most code I see bandied around is of the form:
Send AT command
Delay for numerous seconds
Read and discard anything that might be there
Send another AT command
Delay for more seconds
Read and discard anything that might be there
... etc ...

That is completely the wrong way to do things.
Instead you should be using non-blocking reading to look for an actual OK response from the AT commands that you have sent and use that to progress through the different stages of a Finite State Machine.
Some reading resources from my blog:

Reading Serial on the Arduino
The Finite State Machine
The Evils of Arduino Strings
Splitting Up Text in C


text:
What's the required voltage for ws2815?
I am working on ws2815 led strip with the esp8266 on arduino 1.6.6 fast led library.Using CD40109B level shifter to convert 3.3V of esp output to 12V .It's working fine upto 31 leds according to the program pattern if i increase the led count it's giving random pattern .What can be the issue.
This is the code that i am using
#include <FastLED.h>
#define LED_PIN     5
#define NUM_LEDS    50

CRGB leds[NUM_LEDS];

void setup() {
  FastLED.addLeds<WS2813, LED_PIN, GRB>(leds, NUM_LEDS);
}

void loop() {
  for (int i = 0; i <=NUM_LEDS ; i++) {
    leds[i] = CRGB (255,0 , 0);
    FastLED.show();
    delay(40);
  }
  for (int i = NUM_LEDS; i >= 0; i--) {
    leds[i] = CRGB ( 0, 255, 0);
    FastLED.show();
    delay(40);
  }
}

EDIT
We checked in oscilloscope and we observed that after internal signal reshaping of the ws2815 IC ,the RGB values are not as intended.This is also seen on the led strip with changing colour of the leds.
We are trying to generate a single colour on the strip so this colour changing is quite clear.

The current rating of the power supply I am using is 12.5A, which is enough to drive the LEDs, and the voltage is also 12V at the 32nd LED.

The voltage levels needed for the WS2815: see the datasheet. Your question is inconsistent. You ask about voltages in the subject but in the text you mention averything is fine up to 31 LEDs. So what makes you think the voltages are not OK? The LEDs work so the voltages must be OK. How about there being something unexpected happening in the program?

If this code worked for other kinds of LEDs, you were just lucky. You've committed the common error of writing beyond the end of your array, in both of your for() loops. The last location in leds[] is NUM_LEDS-1, not NUM_LEDS. It sounds like you finally got unlucky and started clobbering something important. It isn't too surprising that this occurs at a power-of-2 boundary.

Well, the code in your question still shows the error. How did a simple copy-paste operation create an error like that anyway? If this isn't an exact copy of the code you're actually running, how are we to know whether there are any other differences?

You say you are level-shifting the data from 3.3V to 12V, but the datasheet for the WS2815B indicates the maximum rating for the logic input (the DI pin) is 5.3V. It is only the supply voltage that is 12V.

Another issue that I have noticed is that the code works fine with the brightness level upto 150 and the programmed pattern is observed on the led strip. However, if I increased the brightness level to 255, the code fails after a certain length. What could be the issue?

Same issue here, actually, after the 400th led maybe. My goal is to drive 639 leds.
I tried with both arduino nano and stm32, but, nothing worked. Please, tell me if you got a solution.
Regrds,
Tommy


text:
Creating WebServer ip:port on esp8266 module
I creating Clever House with wifi. For this I'm using ESP8266 as module connected to Arduino. They communicate with SoftwareSerial. And there's a problem with global webserver on ESP8266. That I think to do it I must do this:
1.Create Webserver on another port(Neither 80 nor 443) Or Host will be in this model: https://ip:port/
2.Open port forwarding for port.
3.Almost done.
So how can I do it with AT commands?

http://www.martyncurrey.com/arduino-esp8266-web-server/

Thanks a lot. But this is not solvution of my problem. I want to start webserver and its url should be for example 192.168.0.102:5000 -> ip:port

AT+CIPSERVER=1,5000. IP is IP of the esp8266, reserve it on router or use the AT command to set static IP

what exactly is step number three?

Nothing :) step 3 is nothing

THANKS!! It worked

As @Juraj mentioned, martyncurrey.com/arduino-esp8266-web-server , I need to start server with command: AT+CIPSERVER=1,5000, IP is IP of the esp8266 and reserve it on router or use the AT command to set static IP.


text:
How to create a wired ESP8266 range extender?
Context: I have a NETGEAR router on the first story of my home, the range doesn't extend to the ground floor. I do have a cable duct from my router(on the first story) to the ground floor.
Question:
Is it possible to wire a Keyes ESP8266 to my router to act as a WiFi range extender?
Note: The length of the cable would be 10 meters.

not with Arduino

@Juraj Do you mean "Not with ESP"?

not with esp8266 Arduino core and libraries. maybe with the Espressif SDK, but that is not Arduino

Check out this discussion. I believe your case is deemed off-topic.

There's a project that calls itself a "wifi repeater" at
https://github.com/martin-ger/esp_wifi_repeater
It includes support for an ENC28J60 ethernet adapter connected via SPI.
It has some serious limitations.
First, it's really a NAT (Network Address Translation) router, not a Wifi extender, though it can effectively extend wifi. However, devices being extended will not be able to communicate with devices on the original network via broadcast or multicast. This will break some applications and many IoT devices.
Also, devices on the original network will not be able to originate connections to devices on the extended network.
But if you just have some devices that only need to talk to the Internet and are a little too far for your router, this should work for them.
Also, the ESP8266 can only get about 5Mbps through it (I'm actually surprised it's that high). You probably won't be able to reliably stream video - definitely not 4K video. It's not a good choice for connecting a television and probably won't work well with security cameras.
Finally, as @Juraj mentioned, it's not an Arduino project. You'll need to install the NON-OS SDK and toolchain to build it. It does include a pre-built image and instructions on how to flash it.
I haven't used it and can't promise that it will work well, but it's the closest thing I'm aware of to what you're looking for.

Much appreciation. According to this documentation the Ethernet interface will support about 1 Mbps when the ESP is running at 160 MHz. that will reduce the speed of the connection to the stations connected to the NAT correct?

That sounds right to me.


text:
What's the most direct way to assign Serial.read() bytes to an array?
I'm trying to send NMEA 0183 sentences through LoRa.
Every dinstict NMEA message looks like several char arrays (sentences) followed by '\n'.
In the below picture we see one NMEA distinct message:

This message arrives in the Arduino input buffer every 1 second with differentiated values (numbers) and it has to be sent over LoRa as fast as possible.
In order to send it over LoRa I need to read all bytes on the input buffer and assign them to an array and send them as an array, not one by one. I know that Serial.read() reads only one byte, and that's the problem.
How can I read all bytes and send them as a whole?
This is my code:
  if (Serial.available()) {
     c = Serial.read();
     rf95.send((char *)c, sizeof(c));
     rf95.waitPacketSent();

I use RadioHead library, and the definition of rf.95.send is:
RH_RF95::send  (const uint8_t * data, uint8_t len)
c is of char type.

There is no such thing as "all the bytes ... as a whole" - serial is only individual bytes. Anything more than that is merely a wrapper around reading single bytes.

What I mean with "whole", is an array

@Majenko, for sending over LoRa it matters? is there some overhead? a frame/ envelope?

The reception of serial is often the slowest portion. Anything else you do is pretty much insignificant.

I was missing a null termination character. That got me reading garbage from all over the buffer.
Adding a '0' at the end of the buffer's length is mandatory.
Plus, as David G. noticed, sizeof() function is incorrect. strlen() must be used.

Just use a counted string, not a null terminated string.  Never do strlen() as you know the length already.

The length is not fixed. Sentences can be more or less depending on what sensors must be used every certain moment, and that can happen in run-time.

The length is not fixed, but the length is KNOWN (after you read it).  In fact, you need to know the length to insert the null.  Why insert the null at the known length, and then use strlen to find the length?

The transmitter node doesn't read the length of the transmitting char array until this function: rf95.send((char *)nmea.getSentence(), strlen(nmea.getSentence()));
The receiver node knows the length after accepting it and reading it but there is no strlen() function in there.

Well, what the call probably should be is rf95.send(nmea.getSentence(), nmea.getSentenceLength());  First off: don't cast.  If you seem to need to cast, you've done something wrong.  Figure out what.  Secondly: your nmea wrapper class should know the length of the data it has, so ask it directly.

@DataFiddler suggested something like readBytesUntil.  In fact, you can just use readBytesUntil.  It returns either when timeout happens or when you reach the specified terminator.  It consumes, but does not include the terminator.  The timeout defaults to 1000 milliseconds, and can be modified with the setTimeout() method.
One downside is that you can't differentiate timeout, full buffer, and terminator reached.  This shouldn't be a problem except for serial transmission errors.
If your data is coming in at the NMEA standard 4800 baud, you could reasonably change the timeout to 5 milliseconds and still work.

One thing that might bite you, is the line:
     rf95.send((char *)c, sizeof(c));

It is a mistake to cast the first parameter.  The error you got indicated you should write:
     rf95.send(&c, sizeof(c));

But the sizeof is also wrong.  The return type of Serial::read() is int, in part because there are 257 possible values.  If you declared c as an int, its size would be 2, not 1.
In any case, if you are using readBytesUntil, you pass the same buffer you passed it to rf95.send(), and the return value from the first as the second parameter of the second.

You are right about "sizeof()", strlen() must be used

NO.  strlen() is NOT appropriate.  You already know the number of characters you have read.  Just use that.  In the original example, there was 1 character, so the constant 1 is correct.  In using readBytesUntil, That returns the number of bytes read, which is what should be used.

All more complex Serial reading methods are based on read().
Luckily there's a terminating character '\n' in your case, so you can implement something similar to readBytesUntil by yourself, if you want to.

I suppose I could loop through all data and add them to an array and avoid all '\n' characters except from the las one?


text:
How to drive Arduino UNO as a counter triggered by 555 timer's output (astable mode)
I have an Arduino Uno and a 555 timer configured to astable mode.
What I'm trying to do is to program my Arduino to increase a "counter" variable (counter++) everytime it gets triggered by 555 timer's output (through analogIN pin).
My problem is that Arduino takes 555 timer's output as a continuous triggering and increases my counter as long as the pulse in the analogIN lasts.
So instead of incrementing by 1, it is increased by approximately 97 (sometimes more or less).
I need to take the analog in as a "packet" so everytime analogIN is triggered, no matter how long the pulse lasts, it will be treated as a single event and not as continuous triggering.
What do I have to change?
My code:
int counter = 0;

void setup() {
  Serial.begin(9600);

}

void loop() {
  if(analogRead(A0) > 250) {
    counter++;
    Serial.println(counter);
  }

}

Thanks

Have your code remember the previous value, and only increment when the previous value was below 250, and the current value is above 250.

PS is there any reason why you are using analogRead, instead of digitalRead?

you are checking for high, but you assume that low will somehow be magically checked also

No, even when I checked for low it didn't work as expected

You need to create a finite state machine with 2 states:

Waiting for input from 555 to go high.  When this happens increment the counter & advance to the next state.
Waiting for the input from the 555 to go low.  When this happens advance to the next state.  That is, the first state.

In the following Arduino "State Change Detection (Edge Detection) for pushbuttons" example / tutorial you do not need the complex code to debounce the switch.  However, the edge detection and state machine portion of the code can likely be applied to your project.

It seems that edge detection is what I needed. Thank you!

This approach might lead to unreliable readings when many and/or time consuming tasks are handled in loop(). It might be a proper solution to read slow and single events like button activity, but i don't recommend it to read a 555 pulse signal.

I recommend using one of the atmega's counter modules. That way you can count the pulses synchronuously to your program (real paralellism!) and you also don't have to implement any edge-detection youself as the counter module already provides this feature.
A search for "pulse counter" will lead to many tutorials on how to do that.

Edge detection seems to work fine. What is the difference between edge detection and your solution? is it faster? more reliable?

Yes, it is both faster and more reliable because it is handled by a hardware module that is optimized for edge detection and runs in parallel to your program. The counter module btw also gets involved when generating harfware pwm. Instead of counting a clock's edge it just counts the edges of an input signal.

@BrainTrance, the HW solution is good.  If you are new to Arduino or embedded programming it may be a bit difficult.  But should result in a more robust solution.  That said, do concern your self with directly using HW.  It may be the HW resource of interest is already being used by other software such an included Serial Communication Arduino Library or LED Brightness Controller Arduino Library.


text:
I can't run shell commands on Linux through AVR sketch (Arduino Yun)
I'm a little confused with some Process.h methods.
I'm trying to run the command "nc 192.168.1.15 9911" to the Linux processor through a sketch.
The appropriate netcat listener is waiting on another computer. Arduino Yun is on the same network with thie computer via WiFi.
When I execute this command through SSH connection on Arduino Yun it works fine, but I can't figure out how it's done through a sketch.
This is my code:
#include <Process.h>

Process p;

void setup() {
   Bridge.begin();
   Serial.begin(9600);
   delay(2000);
   p.begin("nc");
   p.addParameter("192.168.1.15 9911");
   p.run();
   //while (!p.running()) {};

 }

 void loop() {
    if (p.available() > 0) {
    Serial.println("test");
 }
}

This code doesn't seem to work, p.available() nerver executes even if I send data packets.
I also tried p.runShellCommand("nc 192.168.1.15 9911"); with no luck.
It seems that the commands never reach the Linux command line.
Any insights?

and does Serial print something at all? the examples for Yun have SerialUSB for Serial Monitor. https://github.com/arduino-libraries/Bridge/blob/master/examples/Process/Process.ino . and I would add parameters with two addParameter

Nothing at all. I did try this example long ago but it didn't work

There's a few things wrong with your program, some more obvious than others.
First, you have to put each parameter to your shell command in a separate addParameter() call. Otherwise it treats all the parameters as a single parameter and tries to connect you to an address of 192.168.1.15 9911 instead of to port 9911 of address 192.168.1.15.
Secondly you should use runAsynchronously() instead of run() otherwise your sketch blocks at that point until nc terminates. If that never happens then your sketch never gets to the point where it can read the data.
Here is an adaption of your sketch that works for me:
#include <Process.h>

Process p;

void setup() {
    Bridge.begin();
    Console.begin();
    p.begin("nc");
    p.addParameter("192.168.1.15");
    p.addParameter("9911");
    p.runAsynchronously();
}

void loop() {
    static uint32_t ts = millis();

    if (millis() - ts > 1000) {
        Console.println(millis());
        ts = millis();
    }

    if (p.running()) {
        while (p.available()) {
            Console.write(p.read());
        }
    } else {
        Console.println("Restarting process");
        delay(100);
        p.begin("nc");
        p.addParameter("192.168.1.15");
        p.addParameter("9911");
        p.runAsynchronously();
    }
}

It also re-runs nc if / when it terminates. There's also a "heartbeat" printing of millis() so that you can see the sketch is running.  It uses the console, not Serial, for its output, so SSH in to the Yun and telnet localhost 6571 to view the output.

Although right now I don't need to implement the above code because things have changed, your answer solves the current question. Thanks.


text:
Arduino Yun receives UDP packets but prints them with gibberish
Arduino Yun is set to receive UDP packets. It receives those data with some gibberish.
How is all set up: Arduino Yun (acts as a server) is connected through Ethernet to a PC which is (through WiFi) connected to the router. Another PC (acts as client), is also connected to the router (through Wifi).
Client uses netcat to connect to Arduino Yun. I write something and press enter. The packets are received by the Arduino Yun with some gibberish. For example, I write "test" and press enter, but this is what I receive on the Arduino Yun:

Sometimes gibberish characters are different, but always exist. This is what Wireshark monitors when I send the "test" packet (with netcat) to my Arduino Yun:

It shows that indeed I send only "test", so the gibberish is created on the Arduino side, I suppose.
This is my sketch (not the entire code, but the important part):
void loop() {
  int udp_received = Udp.parsePacket();
  if (udp_received) {
    char udp_buffer[16];
    udp_buffer[15] = '\0';
    Udp.read(udp_buffer, 15);
    Serial.println(udp_buffer);
  }
}

I use BridgeUdp.h
Any insights appreciated.

udp_received is count of characters received. (and nice progress since previous question)

udp_buffer[udp_received ] = '\0'; you send only 5 or 6  characters "test\r\n". the rest is random memory content

If I'm not mistaken, UDP packets, when printed as strings, might look like gibberish because they are not ASCII but binary in format. You would need to check the documentation and find out what the packet format is or, lacking documentation, you'd need to try and get some idea what the data actually represents.

Thanks Juraj, I'm moving forward slowly. but steadily. So you say that I read more bytes than I actually receive?

@S.Imp, if you send "test", you receive "test"

you don't read more. the function fills only so much bytes as received. the rest of the buffer is uninitialized memory.

@Juraj if you look at his wireshark screenshot, you'll see that the UDP packet received is 47 bytes. "test" is probably only four bytes. So he's got another 43 bytes to figure out.

@S.Imp, it is the envelope

You send only 5 or 6 characters "test\r\n". the rest is random memory content.
The return value of parsePacket should be the count of received characters, but the implementation in BridgeUdp is wrong and returns always 1 on success.
You you can use BridgeUdp.available() to get the count.
void loop() {
  if (Udp.parsePacket()) {
    int udp_received = Udp.available();
    char udp_buffer[16];
    Udp.read(udp_buffer, udp_received);
    udp_buffer[udp_received] = '\0';
    Serial.println(udp_buffer);
  }
}

You are receiving a small packet of about 5 or 6 characters (depending on your line ending). That is being received into a 16 byte buffer which has contents unknown.  So the first 5 or 6 bytes of the array have valid data in it. The rest is whatever was already in there.
You need to use the return value of Udp.parsePacket() to tell you how many of the bytes in your buffer are actually valid received bytes and only print those.
The simplest way:
Serial.write(udp_buffer, udp_received);

int udp_received = Udp.parsePacket();
if (udp_received) {
char udp_buffer[udp_received];
Udp.read(udp_buffer, udp_received);
Serial.write(udp_buffer, udp_received); Is that what you mean?

Sounds about right

This doesn't work as expected. It prints only the first character of each line. For example if I send "test", ENTER, "test", ENTER", "hello", ENTER, Serial monitor prints "tth"

Maybe it's the return value from Udp.read() actually. I haven't used the Yun for UDP before...

And the packetSize is always printed as 1, that's weird


text:
How to run Arduino codes in Java netbeans?
Having a hard time searching the net on how to run arduino codes on java. Can somebody please help me. Thank you.

Arduino code is C, not Java. So you'd need to translate it to java.

It may help if you explain what your intended outcome is.  Your PC (or even an raspberry pi) doesnt have the same GPIO as an arduino. If your code does not interface with any of that, and you are just wanting to port the c++ code to java, there are ways to do that(this would not be the place to look for help with that though)  But maybe try and explain what it is your actually trying to accomplish.

I would like to send sms using arduino and java. But i can't do it. I already made a communication between them but still it doesn't work. What should i do? And what do you guys think of my mistake?

We cannot say anything about your mistake, since you didn't gave us any information. The Arduino itself  cannot run java. I assume you try to let a java program on your PC communicate with the Arduino. Then just google for java serial communication

What i want is to send sms using arduino and java

Java is a programming language. Arduino is a platform that is mostly accessed by the C++ programming language. You cannot run "Arduino code" in Java.

The Arduino can't run Java. Full stop.


text:
How to power Arduino nano and LED strip?
I am making a project that uses an Arduino nano and a sound detector module to power a 1m LED strip. I got the idea from this video and I am not sure how to power it. My LED strip flashes for a split second and turns off, and people say that the usb power source I am using is not enough power. I am worried though that if I use a more powerful power source that it will fry my Arduino. I am very new to this and I have no idea what to do.

How many LEDs on your strip? Is it an RGB, RGBW, or WS2812 strip?

it is WS2812 with 60 LEDs

When using a power source, which can provide more current with the same voltage, you cannot fry your Arduino with the change. The components will draw the current they need, not more. The rest is reserve and not a problem. You can only fry components, if you draw more current through them, as they are capable of. For example: You can fry your PCs USB port, if you draw too much power for lighting the LEDs. If you give power to too many LEDs through the Arduino (for example by using Vin for power and connecting the strip to 5V), the strip will draw too much power for the regulator and fry it.

Ok, so minimum current capacity you need is 60 * 0.02mA * 3, which is 3.6A. Plus some more to power the Arduino. You want a 4A power supply or better really.

That is for all LEDs on white and full brightness.

Ok, thanks. So if I use a 4A power source, can I connect it to the vin and then connect that to the 5v on the LED?

No. Use a 5V 4A power supply. Connect it to both the LED strip and the 5V of the Arduino.

ok, and I connect the gnd on the supply to the one on the LED strip and on the arduino, right?

Yep. Connect all grounds. https://majenko.co.uk/blog/importance-sharing-grounds

A simple solution would be to cut the LED strip to a shorter length (use fewer LED's).  If you avoid using full-on white you should be able to power 10 LED's from a standard USB port.

For the 5v4a power source, do you know where I could get the female part?

WS2812 can draw 60mA when on full white, x 60 LEDs = 3.6A.  If you have a 4 to 5A external 5V supply powering all the components, you'd be okay.  If you're trying to power the strip from the Nano 5V line thru its regulator, the regulator will overheat and shutdown.

You could use a relay and have a larger power supply that will light up the LED strip on the other side, after the relay gets the signal to turn on.

Is there any way I could do this without external hardware though? Apart from the sound detector, Arduino, led strip, some wires, and a usb cable,  I would prefer not to buy anything else, as I need this for a school project and it would take too long to ship.

@Ethangarret You could do it with just the battery and a transistor if you have those, otherwise probably not the arduino nano just can't supply the energy that is needed.

ok, thanks. Would it work if I power the led and Arduino separately?

Yes, and then you could use a switch to turn it on and off.

That is, if they are connected by that switch.

You don't need a relay or transistor here. The LEDs will only be turned on, if you tell them to do so over the data line. It needs just a strong enough power supply that is connected to the Arduino AND the LED strip directly (not through the Arduino). Over the data line the Arduino can then tell the LEDs to light up in the requested pattern.

@chrisl I was saying use a relay and transistor to turn it on and off. And what data line?

The OP stated in the comments, that he uses WS2812 LEDs. The WS2812 is actually the driver chip for every LED in the strip. And the LEDs in the strip actually consist of 3 LEDs in one case making them RGB. And the WS2812 chips are controlled via a single data pin. You can just write the value zero to every LED and the strip will be shut off. No need for a relay or transistor here.

But how would you right zero with the nano

The chips have their own protocol, but there are libraries like Adafruits Neopixel library or the FastLED library. There are tons of tutorials for that on the web, easily to find when you google WS2812 Arduino. You only need 1 pin for it. On setup you use the library function to initiate the strip with all LEDs off. I have build a room light with that myself.

@chrisl Oh that is interesting I’ll have to look into this sometime

@chrisl but the nano couldn’t supply the LEDs, but I see what you mean by no relay, I can’t believe I made that mistake, haha


text:
Basic if endif not working and I'm puzzled
I got this small code I'm trying things on for like an hour.
int receivers = 0;
#if defined(PPM_RECEIVER)
  receivers++;
#endif

And I just cannot get it working, It keeps returning a "'receivers' does not name a type" on line 4.

Question about C/C++ syntax.  This is counted as off topic on Arduino SE.

Maybe you mistyped receivers; did you copy-paste the code here or rewrote it? Of course then this code is written inside a function, isn't it?

You can't use commands like receivers++ outside of a function.  That is runtime executable code, and has to be run from inside a function. Global scope doesn't get executed in the same way as code in a function.

Ah that makes sense, Thank you!


text:
Software serial and port expanders
On my ESP32 project I've run out of pins and have incorporated using a MCP23017 port expander.  I need to run multiple slow serial connections (9600 baud) thru the port expander.  Are there any software serial libraries available that would work over a port expander?

No. Even 9600 baud would be beyond the capabilities of bit-banging through a port expander. Reconsider your topology. What are you trying to achieve that needs you to use multiple UARTs like that?

I have several DHT22's that I want to interface with.  One option is to use a mux on the tx/rx pins such as a 74HC4052.

using a one-way serial connection might half your pins, if you weren't aware that was possible...


text:
SMS with Uno in 2022
I'm trying to develop a simple sensor-triggered SMS message to mobile service from an Uno as a learning project in North America.
I initially thought that it might be wise to purchase a GSM/3G compatible board and follow a tutorial such as this one: https://docs.arduino.cc/tutorials/mkr-gsm-1400/gsm-send-sms or go with Arduino's IoT SIM card package: https://store-usa.arduino.cc/products/arduino-sim-mkr-gsm-1400-cellular-kit (though this one is not exactly what I want since its SIM card only works with Arduino's IoT Cloud service and is not direct SMS to mobile capable).
However, after a bit of further research, it seems as though 2G (GSM)/3G networks are effectively phased out (by this year) and so I'm concerned that the above options won't work.  I'm also generally confused as to the best low-cost SIM cards for those options above (my service will be sending only tens of messages per month).  I have to yet to find similarly well supported shields/boards/SIM cards for 4G/5G networks in North America in the Arduino community.
Can anyone recommend a solution or point out where I may be incorrect in my analysis of current options?
I've considered postponing this particular project and instead accomplishing the same task with WiFi and IFTTT...
If not evident already: I'm new to working with SMS and IoT.

Unless you need SMS I wouldn't bother with it. Or at best use WiFi and an online SMS gateway service. If you need remote connectivity then a 4G WiFi hotspot will connect you to the internet.

Have you tried searching for terms like "Arduino LTE board"? A quick search seams promising. Though it is definitely easier to build when you use wifi and - if necessary - a standard wifi hotspot.

@chrisl Yes and I concluded that the Botletics SIM7000A Shield (along with a Hologram SIM card) is the likely the best way to go for 4g support on Arduino based on these resources: https://www.instructables.com/LTE-NB-IoT-Shield-for-Arduino/ and https://github.com/botletics/SIM7000-LTE-Shield.  Do you agree?

Looks good to me

any luck on getting SMS to work with the hologram sim and SIM7000?

@trevor haven't gotten around to it yet.  I decided for the time being to just use a wifi board


text:
Whats the maximum external voltage/current i can apply through an Arduino Uno ? + a couple mini questions
i'm just starting out with electronics and Arduino's and was wondering about the extent of an Arduino's ability. Will i eventually be able to program and power very high voltage/current requiring devices such as a full sized fan motor? Also at what point would i not be able to use normal wires, components and breadboards due to a high current/voltage (not sure which one would break them).
I know these are total noob questions but thanks in advance!

Arduino Uno
First, never use too high voltages on GPIO pins of an Arduino. if you want to know, search for 'absolute maximum current' or 'absolute maximum voltage'. Probably any pin of an Arduino is about 5 V (plus some headroom).
External power
So since your fan will use more voltage high likely, you are not lost, in contrary, you should use a separate power source (giving the voltage you need for the fan), and use either a relay, or a transistor or MosFet. Than you can program it with a 5 volts pin and control a much higher voltage device (your fan).
Wires
Do not send high voltages/currents through breadboards and jumper wires neither. Use separate wiring, and you can check tables using AWG (thickness of wires) to see how much current they can support. Note that I say current, not voltage. The voltage will drop depending on the length of the wire and the size, so calculate that you have enough voltage at the end of the wire.
Safety
Also for safety, do not forget a fuse, and remember that the external power source and all wires have the same voltage as the fan, which may kill you if you touch them.

Thanks for the in depth answer! The fan was just an example but could you go into a bit more detail in programming a fan? How would i connect it to the Arduino? i couldnt just attach it to pin 11 or whatever and pretend its a servo motor so how would you go about doing something like this?

I don't know how your fan works, first find out in the datasheet or description what the protocol is (just adding power on it? use a relay), some work with PWM (use a PWM signal and transistor/mosfet), if it is a servo motor, than you might need additional components, like a servo motor driver, check for examples, there are plenty on internet).

arduinos, and microcontrollers in general, handle only very small ammounts of current, and they work at what is called 'logic level' voltage, usually much lower than 'line' voltage or 'mains,' which is your wall outlet. in general an arduino will put out 30-50 mAh per pin, and max of about 200mAh combined. again, the total ouput for the entire board is a max of about 0.2 amps. the idea is that the pins are pulled high or low (+5 or ground) depending on the logic of the programming. these signals trigger logic level components to act, usually mosfets/transistors and relays turn higher loads on/off
basically, you dont want to power even a single led without a current limiting resistor. its just a microcontroller after all


text:
Mistaken Connect 5V to SCK Pin
i have old chinese old hotair station that controls by atmega8l 8ua chip..
and the board designer are clever enough to put 2 identical dc plug, 1 is 5v supply cable.. the other one is on off switch that connect ground pin to sck pin..
i was mistaken plug power cable to the on off side that supply 5v+  to sck.. now the station not powering up anymore..
is there anyway to copy the firmware to new chip?
it cannot be detected by usbasp since i believes the sck are toasted..
i'm just a beginners and English are not my native language. sorry if the word are hard to understand..

Welcome to Arduino! Please take the tour and visit the helpcenter to see how things work here. Retrieving the software from this AVR is - with any reasonably amount of effort - rather unlikely. It'll be easierer to guess the function of it and rewrite a "similar" software from scratch.

Both serial and parallel programming modes seem to require the SCK pin.

thanks for both of You.. i think the station manufacture intended to make the port identical to destroying they product if someone try tampered their product.. so there is no chance to duplicate the firmware as Gerben told that both connections required sck pin.. As Ghanima solution to rewrite similar software from scratch it's seem a little difficult to me.. i'm totally noob about arduino, i brought the uno couple of years ago for calibrate drone esc board. then i have never touch the uno again.. i think i need to dig deeper..


text:
ESP8266 official library post request returns 400
Every time I try the post request I get a 400 error but the JSON and URL are identical to those that I used on an online API tester and it worked every time there. I am running this program in the official Arduino IDE and most of this code was taken from the ESP8266 official library here: https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266HTTPClient/src/ESP8266HTTPClient.h
if (http.begin(client, host)) {  // HTTP

  http.addHeader("Content-Type", "application/json");
  // Serial.print("[HTTP] GET...\n");
  // start connection and send HTTP header
  // int httpCode = http.GET();
  String request = "{ \"temperature\": 27.0, \"humidity\": 43 }";
  Serial.print("[HTTP] POST...\n");
  int httpCode = http.POST(request);

and the value of host?

client is an instance of the WiFiClient object and host is a variable declared to the url with my private key included.

error code 400 is "Bad request" and it is a HTTP response from the server

Right, but I'm trying to figure out what the inconsistency is between my code and the API tester I used. The JSON and URL are identical.

only other thing you provide is host in sketch

So maybe my JSON is formatted incorrectly? I just want it to show up as {"temperature": 27.0, "humidity": 43}

it would not be 400. 400 is wrong status line or headers. maybe some missing header?

What header would be missing? I'm not very familiar

some invalid characters in url (host) which should be encoded? space or %

I don't think there's any invalid characters. The format is as follows: https://redacted.redacted.net/some/stuff/here/fad34552435jdasfaghh8?private_key=8342yfsadh4jh38fh27df8

https protocol?

Here is the recommended cURL from the documentation: curl -H "Content-Type: application/json" -X POST
-d '{ "timestamp": 1541519720, "value": 76.5 }'
https://myfarm.farmos.net/farm/sensor/listener/xxxxxx?private_key=yyyyyy

Oh it is https:// could that be my problem here?

https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266HTTPClient/examples/BasicHttpsClient/BasicHttpsClient.ino

I changed the URL to http and now it is giving a 301 error moved permanently. I will take a look at the HTTPS example instead, the reason I avoided was because they had an expired fingerprint so I wasn't sure if it would work (honestly don't even know what the fingerprint is for).

I used some online generator for the fingerprint and switched to HTTPS and it is working and the JSON data is showing up on the server. Thanks for your help. Since you solved my question if you'd like to post something as an answer I will mark you as the answer.

400 is a HTTP error "Bad request" sent by the HTTP server. Possible reasons for this error are malformed HTTP request line, malformed HTTP request headers, missing empty line after the last HTTP header and a request to 'secure' port without encryption.
In your case the HttpClient library constructs the HTTP request so there should be no error. Only thing you supply for the request is the URL in your case it is the variable host. As we cleared in comments, your URL started with https. The HttpClient library parsed the url, detected the https protocol and used the secure port 443. But the underlying networking Client object was not SSL so it didn't encrypt the request.

Thank you for your help!

I appreciate the explanation of what went wrong, but how can we make it work?

@jezmck in this case it would be using the WiFiSecureClient as shown in the BasicHttpsClient example


text:
WiFi or Bluetooth to communicate between several Arduinos and a Raspberry Pi
So I want to set up a network of outdoor sensors (temperature and humidity) connected to an Arduino (and at some point a second or third Arduino further away with its own sensors). Then I'd like this Arduino to wirelessly transmit this data to a Raspberry Pi running some sort of server that can receive the data and then upload it to the cloud. I'm assuming WiFi is the best method to do this because of range and the number of devices at once? Would I just have to get each Arduino a WiFi module and what kind of range can I expect from this setup?

Comments are not for extended discussion; this conversation has been moved to chat.

I would also suggest using WIFI (ESP8266) as you need to create a local network in which all devices will communicate to single host connected to the same network. If range will be issue you can use LORAWAN network for the same. LORAWAN provide high network range and if industrial gateway is used you can connect 10000 nodes(arduino in your case) communicating to the single server at a time.Else WIFI will the good.

If I get an ESP8266-01 module to connect to an Arduino Mega or Uno, will the board still have enough digital and analog slots for some temp and humidity sensors?

Yes. ESP8266-01 require only UART pins to communicate with the arduino, so you have many pins left for another work.


text:
Is there something I can add to my ESP8266 script to track how much data it uses on WiFi?
I want to set it up on a mobile hotspot but I'd like to get an idea of how much data my sketch uses first.

keep a running tally of the length of data being sent ... you could keep track of received data also

But I don't know the size of the data I am sending, it's just two JSON objects.


text:
Serial monitor garbage output on both MacOS and Windows devices, output used to make sense
Baud rate is set to 115200 in both the serial monitor and in the setup() portion of the code. The output to the serial monitor just looks like a bunch of reverse question marks on MacOS and on Windows it's a bunch of gibberish characters. Any idea how to fix this and why it would have changed when the output used to be what I expected? Weird thing is the program on the board is still working because I'm seeing the proper output on my server but I want the serial monitor working for debugging if it's not making it to the server.

what else has changed?

Nothing that I've noticed. I don't think I even changed the code since this started happening.

plain esp8266 doesn't have USB. how do you connect it to Serial Monitor?

I have this board with a built on micro USB port.


text:
how to write Arduino code for a stepper motor to move an arm back and forth 180 degrees
I am currently working on a project which involves picking up plastic balls and depositing them in a box. I am trying to use a stepper motor to move an arm which is attached to a square piece of plywood which has Pringles cans on it. This is how I plan to collect the plastic balls.
The stepper motor needs to move the arm back and forth 180 degrees to collect and deposit the plastic balls. But I am unsure as to how to write the code to accomplish this as I am quite new to Arduino coding. Any form of help would be greatly appreciated. Thank you in advance.

you cannot move the arm 180 degrees until you know how to turn a stepper motor .... start with continuously moving the motor in both directions .... then learn how to move only a specific number of steps

Plenty of examples on the web already.  You can find these via a search engine.

There is not enough information about your stepper motor, so let's assume some: let's use stepper motor with 1.8 degree per step (very popular step motor), and we will drive without any microsteps.
To accomplish the task you would need:

Arduino,
stepper motor,
stepper motor driver (like EasyDriver or some kind of Pololu drivers)
power supply. To avoid interference I would suggest powering up your Arduino with PC (through USB port) and additional, powerful PSU for the motor/motor driver only.

Now, you would need to provide at least two signals from Arduino to stepper driver (what I am saying here is example of EasyDriver). The signals named DIR and STEP. DIR selects the direction of the motor to spin. Depending of the stepper motor to driver PCB connections you may have clockwise spin when signal is in one state and counterclockwise when DIR is in opposite state. STEP accepts pulses to move the step motor. Driver moves the stepper motor when STEP input sees raising edge. One raising edge equals to one step = 1.8 degree (again, this apply when you do not use microstepping). To spin motor 180 degrees you need 100 steps.
To summarise:

Use two ports (simplest solution here with EasyDriver): One defined as DIR, other as STEP.
DIR low (selecting one of directions)
STEP pulse 100 times (step motor rotates 180 degrees)
pause (for whatever needs to be done)
DIR high (opposite direction to rotate back)
STEP pulse 100 times (stepper motor rotates 180 degrees to initial position)


text:
Can't get the right values with the pulse sensor and the LM35 temperature sensor . Reading 2 anolog sesnors
I am trying to combine the two sensors (pulse sensor using this library and LM35 temp)(on a Arduino UNO board),but there is a problem with them when is a noise at the pulse sensor .The values are fluctuates especially the LM35 it goes from 31 degrees (normal value ) to 25-50 and even the pulse one changes .
Here are the results .
The code is this(I got the code form the  Getting_BPM_to_Monitor sketch ) :
#define USE_ARDUINO_INTERRUPTS true    // Set-up low-level interrupts for most acurate BPM math.
#include <PulseSensorPlayground.h>     // Includes the PulseSensorPlayground Library.

const int sensor = A5; // Assigning analog pin A5 to variable ‘sensor’
float tempc; //variable to store temperature in degree Celsius
float vout; //temporary variable to hold sensor reading
//  Variables
const int PulseWire = 0;       // PulseSensor PURPLE WIRE connected to ANALOG PIN 0
const int LED13 = 13;          // The on-board Arduino LED, close to PIN 13.
int Threshold = 550;           // Determine which Signal to "count as a beat" and which to ignore.
// Use the "Gettting Started Project" to fine-tune Threshold Value beyond default setting.
// Otherwise leave the default "550" value.

PulseSensorPlayground pulseSensor;  // Creates an instance of the PulseSensorPlayground object called "pulseSensor"
void setup() {
  Serial.begin(9600);          // For Serial Monitor
  // Configure the PulseSensor object, by assigning our variables to it.
  pulseSensor.analogInput(PulseWire);
  pulseSensor.blinkOnPulse(LED13);       //auto-magically blink Arduino's LED with heartbeat.
  pulseSensor.setThreshold(Threshold);
  // Double-check the "pulseSensor" object was created and "began" seeing a signal.
  if (pulseSensor.begin()) {
    Serial.println("We created a pulseSensor Object !");  //This prints one time at Arduino power-up,  or on Arduino reset.
  }
}

void loop() {
  int temp = analogTemp();
  Serial.print(temp);
  Serial.println("Temp");

  if (pulseSensor.sawStartOfBeat()) {            // Constantly test to see if "a beat happened".
    // Serial.println("♥  A HeartBeat Happened ! "); // If test is "true", print a message "a heartbeat happened".
    int myBPM = pulseSensor.getBeatsPerMinute();  // Calls function on our pulseSensor object that returns BPM as an "int".
    // "myBPM" hold this BPM value now.
    Serial.print("BPM: ");                        // Print phrase "BPM: "
    Serial.print(myBPM);                        // Print the value inside of myBPM.
    Serial.println(" A HeartBeat Happened ! ");
  }
  delay(20);                    // considered best practice in a simple sketch.
}
float analogTemp() {
  vout = analogRead(sensor);
  vout = (vout * 500) / 1023;
  return vout; // Storing value in Degree Celsius

}

Do all devices share a common ground?

This may be a hardware problem (eg wrong/no capacitors etc). Can you please post your schematic.

Yes they share the same ground .Here is the scheme

I used this pulse sensor


text:
Program an lcd display with 12 pins
I have a screen just like this (is the datasheet). My question is,
Can I use it to an Arduino board?

you probably can use it ... it is unknown what the user experience will be like ... you have not included a link to the actual datasheet

Can you tell me how, I don't know if exists any library for this type of screen. This is the only datasheet that I found. I tried to find more information's about it  and zero success.

first, you have to find a datasheet for the LCD control IC that is used in that display

Can be this ones ? https://imgur.com/a/e5DD9U4

The datasheet is here, it provided sufficient info to experiencing with. But it probably not worth the effort to write the library.


text:
Arduino Fio and Solar Pairing
I'm creating a weather station and want the station to be completely power independent. I'm using the Arduino Fio (https://www.arduino.cc/en/pmwiki.php?n=Main/ArduinoBoardFio) and have estimated the power requirements of the station to be an average of 273 mAh / day with a max load of .06A. I'm pretty sure I'll use the 850 mAh battery (https://www.sparkfun.com/products/13854) but need to know if a solar panel will work to charge the battery. Based on my current home location, I have about 3 hours of good sun per day during the winter.
The Arduino Fio has a Mini USB that seems like its sole purpose is to charge the battery but will a solar panel work or is the Fio designed to have that be a more regulated power supply? If so, will this 2W Panel (https://www.voltaicsystems.com/2-watt-panel) be compatible with the Fio to charge the battery and suite my needs.
Thanks for the help

The open circuit voltage of that panel (7.7V) is above the absolute maximum rating of the MCP73831. So when the battery is full, the voltage coming from the panel will be too high.

Note that Arduinos typically use linear voltage regulators (After a quick search I couldn't tell if the MCP73831 does or not. Linear regulators waste power by converting excess voltage to heat. You could both increase the efficiency of your setup and solve the over-voltage problem mentioned by Gerben by using a switching 3.3V supply and feeding the 3.3V pin on your MCP73831 directly.

Also note that Lithium Polymer cells require special charging circuits. You can't just trickle-charge them like you can lead-acid cells. Quoting the docs for the battery you linked: "These batteries require special charging. Do not attempt to charge these with anything but a specialized LiPo charger."


text:
cannot upload my program to arduino uno
I bought new Uno yesterday, i made my programme, and i compile it. it was good compiled. however, when i upload the programme to my Uno, it cannot be uploaded and there was a message like this
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x1b
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.
Help me please

so, did you read the troubleshooting web page?

Yes of course i did

Make sure u have selected the right COM port
Make sure nothing is connected to the pin 0 and 1 in arduino

This happens because the Arduino IDE could not find Arduino Board Connected to the system.


text:
Python Arduino Serial Communication Speed
Background : Im controlling serial manipulator using Arduino Uno with Servo Shield. Servo work at 20 ms, so i would like to send command atleast every 2.5ms. Command sent from PC.
I send 8 bytes of data from my python code on PC at 250k Baudrate. If i send it every 25 ms, my robot could respond and everything works fine. But if i send every 2.5 ms, my system wont work.
Here my arduino code,
#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>

Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();
int x,temp;

int sudutT0(long int p)
{
  int u = 3600+((405*p)/180);
  return u;
}

void setup() {
  Serial.begin(250000);
  Serial.println("Joint 2 Test!");
  pwm.begin();
  pwm.setPWMFreq(50);

  Wire.setClock(1000);
  for (uint8_t pin=0; pin<16; pin++)
  {
  pwm.setPWM(pin, sudutT0(90),4095);
  }
  pwm.setPWM(3, sudutT0(150), 4095);
}

void loop() {
    if(Serial.available() == 8){
      if(Serial.read() == 0xF5)
      {
        //Joint 1
      temp = Serial.read();
      x = sudutT0(temp);
      pwm.setPWM(0,x,4095);
      // Joint 2 Servo
      temp = Serial.read();
      x = sudutT0(temp);
      pwm.setPWM(1,x,4095);
      x = sudutT0(180-temp); //810 - theta
      pwm.setPWM(2,x,4095);
      //Joint 3 - 6, Gripper
      for(uint8_t u = 3; u<8; u++)
      {
        temp = Serial.read();
        x = sudutT0(temp);
        pwm.setPWM(u,x,4095);
      }
      //delay(100);
      }
    }
}

Is there anything that i miss, that make my system could not respond if i send signal every 2.5 ms?

Is there a reason you need to update it 400 times a second? All of the code takes time. It takes ~0.2 ms just to send the 8bytes at 250k, then you have to process the data.  I would suspect that all that is taking longer then 2.5 ms and so by the time you read again, you have more then 8 bytes in the buffer, and eventually it overflows. I would try decreasing from 25ms to 24 and re-test, then reducing again. you may be able to find the lower limit of what will work reliably. This is assuming there is a need for it to update faster then 40 times a second, if not then just stay at 25ms.

@ChadG Actually i wanna apply control theory about multirate sampling time, and i just realize i made a mistake.. i didnt need to make it 2.5ms now. And thank you for explaining why my robot couldn't respond.. could u put ur answer at answer section, because u explain why my robot not responding. Thx

All of the code takes time. It takes ~0.2 ms just to send the 8bytes at 250k, then you have to process the data. I would suspect that all that is taking longer then 2.5 ms and so by the time you read again, you have more then 8 bytes in the buffer, and eventually it overflows. I would try decreasing from 25ms to 24 and re-test, then reducing again. you may be able to find the lower limit of what will work reliably. This is assuming there is a need for it to update faster then 40 times a second, if not then just stay at 25ms


text:
I2C between two arduinos
I have 4 gyro sensors that communicate to arduino uno using I2C and then arduino uno sends the data to arduino mega.
I was wondering if I could use i2c for this purpose or if I should look for other methods.
gyro sensor used in the project:
https://www.pololu.com/product/2129/resources

Sure, the Mega can be an I2C slave, too. Is there a reason, why you are using a Mega and an Uno, instead of just the Mega?

ok so the arduino uno can be both a slave and a master. thanks
yes, I will be adding a bunch of analog sensors to the project later and I don't have enough unused I/O pins on the Mega to connect them to, so I'm using 2 boards.

Both master and slave is not adviserable. The I2C protocol has multi master support,  but the Wire library does not implement this. If the gyro sensors use I2C and you already considered to use I2C between the Uno and Mega, why don't you connect the gyro sensors to the Mega? They will only use the 2 I2C pins, that you already planned in, since they are all I2C sensors.

thats better thank you!


text:
Optimizing code to use less Flash Memory and SRAM
I'm trying to reduce my sketch size and managed to reduce both SRAM and Flash memory.
From:
1570 SRAM - 32144 Flash memory
To:
644  SRAM - 19458 Flash memory

This are what I've done so far:
✓ Enabling LTO
✓ Using PROGMEM
✓ Dropping string and using char
✓ Dropping bootloader
✓ Using port manipulation
✓ Using registers to declare pins output/input
✓ Removing/Optimizing/Combining; unnecessary/repeated codes in the sketch
Using EEPROM is not an option for me.
What else i can do to take optimization one or two step further?

ArduinoIDE is designed to be easy and not fast. To really optimise your code switch to AtmelStudio and write logic on registry level. ArduinoIDE loads many libraries out of box. Some of them are probably unnecessary in your sketch.

Change the compiler optimization levels. I looks like you can do that within the code, though I've done it by changing the boards.txt file in the past.

Also use the right type for (global) variables. Use byte instead of int for variables whose values are always between 0 and 255.

What you can do in addition to the items you mentioned:
SRAM reduction

Use the smallest amount of data type for integers, e.g. use an 8 bit data type instead of the default integer, this saves you one byte for every variable. See remark below about types. I made my own types (if not existing) for int32_t, uint32_t, int16_t, uint16_t, int8_t and uint8_t and always use the smallest possible.
Use unsigned instead of signed for types that cannot be negative. This might save you one byte if you can prevent using an unsigned byte instead of a signed int because a value can be in range [128..255]. The same for unsigned int instead of signed long.
Use bit fields if you use multiple booleans inside a struct or class. Make sure the bit fields are declared consecutively.
Pack data in smart structures ... I.e. if you have two variables, where one can be 0..7 and another can also be 0..7, store this together using bit fields (in combination with boolean to bit field above).
Prevents float/doubles (see KIIV's comment below), instead:
Instead of using a float, multiply the value by the needed accuracy and store it in an integer (if you don't need high accuracy and it fits in the integer type).
In case you need a lot of strings to be stored, and those strings do not have characters above 128, you can save 1 bit per byte, of course this means quite some programming work to handle 7 bits 'ASCII' characters.
The same, if you have to store a lot of values that can be e.g. 0 to 50, you can use 6 bits instead of 8 bits; you cannot use bit fields, but you can make a smart array and program your own get/set functions to access the 6 bit values.
If you use libraries which declare big buffers, try to minimize those buffers, this might cause to copy them and manually change them yourself.
Prevent your own buffers to be made global, instead use them as a local variable temporarily when you need them. If you have two of such buffers, you don't have both buffers allocated at the same time; note however, that during execution, that buffer still needs space (so you have to calculate or make a guess/estimation what the maximum stack size will be).

Flash Reduction

Don't use duplicated code blocks, but make functions with parameters to differ between the differences of the duplicated code.
Instead of lookup tables, create a function that calculates it (if possible). Of course the gain depends on the length of the lookup table and the length of the function.
Instead of debugging strings, use numbers.

Both SRAM/Flash Reduction

Split your application over multiple MCUs, of course this adds some kind of communication protocol (UART, I2C, SPI).

It's more like: Don't use floats/doubles on architectures without hardware FPU (pretty much just some Cortex M3/M4 boards have it). And for example on AVR based arduinos is double just an alias for float.

@KIIV Thanks for the comment, didn't know the aliases were the same.k

You can also change to a processor with more SRAM, such as 16kbytes in Atmega1284P.  I use that chip in many Arduino-based projects. Dual hardware serial ports,128K flash, 16K sram, and 32 IO.

@CrossRoads I didn't took hardware solutions into account (because of the OP not wanting EEPROM, which is more or less equal than using another MCU). Too bad they don't make a (cheap) Arduino with that MCU, I think the 2 KB SRAM is really a limit for many projects. I'm now making mine with a Mega and using an external EEPROM for storage. I was thinking about an external SPI RAM but I try to make my project without that.

Yep, China is not offering '1284P based boards like they do for Uno, Nano, and Promini. I sell boards, but I get my parts from Digikey & Mouser, so there is some markup there, but it ensures I get parts from a known good supply.

@CrossRoads I guess that's better, but for me a Mega will do. I wish I could make the entire project with STM32's, but I found out my knowledge is lacking to get a fast progress, so I stick with simple Arduino's until I'm ready to use some STM32's.

I'm having flashbacks to my early days as a C programmer in the 80's.
Some thoughts in addition to all of the excellent advice already given ...

Depending on how much data your application uses, you may want to
read / write data to an SD card (or other external storage).
While there is a certain amount of
overhead for the libraries, the payoff is you then have virtually
unlimited storage.  This is the equivalent of how we used to store
data on 5 1/4" diskettes back in the old days.
Avoid static variables whenever possible.
Keep the scope of a variable as small as possible.
As a philosophy you should consider unsigned char to be your
default data type and only 'upgrade' to a bigger footprint when your
code requires.

Re “use dynamic memory as much as possible”: You should probably be more specific. When hearing “dynamic memory”, most would think malloc(), which is something to be avoided if you can. I guess you mean “automatic allocation”, i.e. local variables not qualified as static.

Re “re-use variables if you don't need them at the same time”: −1, as this is terrible advice! Please, refrain from encouraging such horribly bad practice. It may have been a reasonable optimization 30 years ago, but since at least 20 years, it has become quite difficult to find a compiler dumb enough to not do this optimization itself. Trust your compiler, and write clear code. Or ditch the compiler if you managed to find one that is that bad.

Funny, keeping scope as small as possible is mutualy exclusive with reusing variables. Reusing variables is also error prone, but maybe little bit less error prone than variable declaration and initialization later (often later than it's used)

Agreed with feedback, updated my answer to reflect that.