text:
Running 5v and 12v strips together?
I want to run 5v and 12v strips and halos together, i read that with the 12v strips, give 12v to the strip but the data is always 5 volts, and tie the ground to the ground of the 5v controller?
I use SP105E bluetooth controllers off ebay, and i use a 10/20a 12v to 5v buck converter to get me to 5v as i use my lights in vehicle accessories so thats why i dont have a power supply or anything.
So would i just take the 12v strip, run the +12v to the +12v then data to the data wire and tie the 12v strip ground to the 5v ground on the controller/step down converter?

They aren't a lot of addressable led strips that use 12Volt. Are you sure that's what you have. PS don't use a 12V transformer for halogen bulbs to power led strips. Those transformers don't give a nice stable 12V, as halogen bulbs don't care if the voltage fluctuates or spikes.

In electronics, 99% of the time you will need to tie all the grounds together for a common ground. So yes, the - of the 12v strip needs to be connected to the - of the 5v strip.

Yes im sure they are 12v addressable strips. i have 5v and 12v, ws2811 and ws2812b. i dont know about a halogen transformer? but im using a step down buck converter very commonly used in automotive LEDs, which is where all my led work is based, also ive never really had any stability issues with these step downs, hopefully it doesn't start.

Please explain what halos are. In my opinion a halo is a titanium protection bar for f1 racing drivers. 12v led strips are often used for aquarium lights. Sometimes they have dc-dc converters included in the strips. There is no problem with 12v and 5v led strips to the same arduino or to the same bluetooth controller, but we like to see a drawing of all the wiring. This is the arduino section. Is there a hidden arduino somewhere?

Halo is a ring, a circle, a circle of leds. There is no arduino in this setup, just the SP105e controller and the strips/circle rings. I didnt know where else to ask about 5v/12v leds and wiring other than this forum because everyone seems to use the 5v addressable LEDs which is why its in this section.
I now have wired a 5v and 12v strip together and they work, however now my issue seems to be the blue and green colors are backwards, when i select green, the 5v strip is green and the 12v is blue or vice versa, and the same when i go to blue, however red is red on both.

here is a sketch of the wiring http://i63.tinypic.com/30lcsnn.png


text:
(Arduino Uno) Is my code for a follow the sun project valid? We want the motor to stop when both photoresistors have the same amount of light
int RlightPin=0;  //pin for right Photoresistor
int LlightPin=1;  //pin for left Photoresistor
int TranslateAnalogR=0;
int TranslateAnalogL= 1;
#include <Servo.h> //Servo library.
int pos=90; //Declare and initialize the variable pos.
int servoPin=9; //Servo connected to pin 9
int servoDelay=10; //Time motor waits before working again.
Servo myArms; //Servo object called myArms

void setup() {
Serial.begin(9600); //Start serial communication.
pinMode(7,OUTPUT);
pinMode(servoPin,OUTPUT);
myArms.attach(servoPin);

}

void loop() {

Serial.println(analogRead(RlightPin));   //Write the value of the right photoresistor to the serial monitor.
TranslateAnalogR=analogRead(RlightPin); //Read the right photoresistor value

Serial.println(analogRead(LlightPin));    //Write the value of the left photoresistor to the serial monitor.
TranslateAnalogL=analogRead(LlightPin);  //Read the left photoresistor value

if(TranslateAnalogR=TranslateAnalogL){        //If Photoresistor Value is above 355 the motor will stop
myArms.write(pos); // sets the servo position according to the scaled value
delay(servoDelay);// waits for it to get to the position

}

if(TranslateAnalogR=!TranslateAnalogL && TranslateAnalogR>TranslateAnalogL) { //If Photoreistor R is not equal to L and higher than L move until equal
for (pos=0; pos>=40; pos=pos+1)  {
  myArms.attach(servoPin);
  myArms.write(pos); //send servo to pos
  if(TranslateAnalogR=TranslateAnalogL){
  myArms.detach();}
}
}

if(TranslateAnalogL=!TranslateAnalogR && TranslateAnalogL>TranslateAnalogR){    //If Photoresistor L is not equal to R and higher than R move until equal
for (pos=0; pos>=40; pos=pos-1){
   myArms.attach(servoPin);
   myArms.write(pos); //send sevo to pos
   if(TranslateAnalogL=TranslateAnalogR){
   myArms.detach(); }

}
}

}

Does it compile? Does it work?

TranslateAnalogR=TranslateAnalogL should be TranslateAnalogR==TranslateAnalogL (== is equals; = is assignment).  In TranslateAnalogR=!TranslateAnalogL && TranslateAnalogR>TranslateAnalogL you don't need the first part. If one value is bigger than the other they can't be the same. So the first part is superfluous.

for (pos=0; pos>=40; pos=pos-1){ doesn't do anything (yet).

run it and test using a flashlight (torch)

There are many issues with this code:
pinMode(7,OUTPUT);

What is this pin for? Why do you set it to OUTPUT and then never
actually output anything? If the pin is in use, you should declare a
constant for it, like
const int fooPin = 7;

and then use the constant instead of the bare number 7.
Serial.println(analogRead(RlightPin));   //Write the value of the right photoresistor to the serial monitor.
TranslateAnalogR=analogRead(RlightPin); //Read the right photoresistor value

analogRead() is a slow function, and it is quite inefficient to do the
analog to digital conversion twice. You can instead
TranslateAnalogR = analogRead(RlightPin);
Serial.println(TranslateAnalogR);

As a matter of style, I would remove the comments. Commenting code is
generally considered a good practice, as long as the comments tell
something non obvious, like giving the “big picture” or the rationale
for doing something in a particular way. Paraphrasing in English what
the code already says in C++ is useless.
Serial.println(analogRead(RlightPin));   //Write the value of the right photoresistor to the serial monitor.
//...
Serial.println(analogRead(LlightPin));    //Write the value of the left photoresistor to the serial monitor.

You won't know what value corresponds to the left and what value
corresponds to the right. I would instead do something like:
Serial.print("L: ");
Serial.print(TranslateAnalogL);
Serial.print(", R: ");
Serial.println(TranslateAnalogR);

Then:
if(TranslateAnalogR=TranslateAnalogL){        //If Photoresistor Value is above 355 the motor will stop

You mean ==.
if(TranslateAnalogR=!TranslateAnalogL && TranslateAnalogR>TranslateAnalogL) { //If Photoreistor R is not equal to L and higher than L move until equal

The first test is redundant. If R>L, then obviously R≠L.
    for (pos=0; pos>=40; pos=pos+1)  {
        myArms.attach(servoPin);
        myArms.write(pos); //send servo to pos
        if(TranslateAnalogR=TranslateAnalogL){
            myArms.detach();
        }
    }

This is a very contrived way of searching the optimum. Normally you
attach the servo once and keep it attached all the time. Then you adjust
the position until you see the same illumination on both LDRs. This way
you keep track of the correct position and you need not redo the whole
angle scan every time. Also, this will not work for three reasons:

You mean TranslateAnalogR==TranslateAnalogL rather than
TranslateAnalogR=TranslateAnalogL
TranslateAnalogR and TranslateAnalogL are not updated within the
loop, you need to explicitly perform an analog read.
The loop will run too fast for the servos to follow the requested
positions.

Later:
    for (pos=0; pos>=40; pos=pos-1){

The loop is backwards. You probably mean
    for (pos=40; pos>=0; pos=pos-1){

Here is my take at this, completely untested:
#include <Servo.h>

// Pinout.
const int PIN_LDR_R = 0;  // right photoresistor
const int PIN_LDR_L = 1;  // left photoresistor
const int PIN_SERVO = 9;  // servo

const int SERVO_DELAY = 20; // time motor waits before working again

int pos = 90; // servo position in degrees
Servo servo;  // servo object

void setup() {
    Serial.begin(9600);
    pinMode(PIN_SERVO, OUTPUT);
    servo.attach(PIN_SERVO);
}

void loop() {
    // Read and report light levels.
    int level_L = analogRead(PIN_LDR_L);
    int level_R = analogRead(PIN_LDR_R);
    Serial.print("L: ");
    Serial.print(level_L);
    Serial.print(", R: ");
    Serial.println(level_R);

    // Adjust the servo position.
    if (level_R > level_L && pos < 180)
        ++pos;
    if (level_R < level_L && pos > 0)
        --pos;

    // Update the servo.
    servo.write(pos);
    delay(SERVO_DELAY);
}

A few things worth noting:

Constants are qualified as const (it helps the compiler optimize and
catch bugs) and spelled in full caps (a common stylistic convention).
The servo position is adjusted step by step, one degree per loop
iteration. No need to perform a full scan every time.
The program does not do anything special when the light levels are
equal, because in that case there isn't actually much to do.
I increased the delay between servo updates to 20 ms, as
the serial communication alone can take close to 19 ms per
iteration.
You may want to add some hysteresis in order to avoid the servo
jitter when it has found the optimum.

source: Stack Exchange

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

sort: votes


text:
Calculate the Li-Po Battery Level in ESP-Wroom-02
I am very new to micro controller and circuits. I am not at all with this field. But trying to create a home project where I have a device image attached below.

This is 18650 Lipo battery powered device. Here I want to calculate the battery level. After doing some research on google I found that I need to have Voltage Divider which I think I already included in this with 220k ohms and 100k ohms

People are using different ways to calculate it. Which I found in few examples. Which I am not able to understand at all, that what formula or values they are referring to calculate it.
if someone can help to understand that will be helpful. Here is how I am coding it which I saw somewhere on internet itself.
      #include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
//#include "DHTesp.h"

#define DHT_PIN       16

//SSID and Password of your WiFi router
const char* ssid = "Asus";
const char* password = "Xmv02488!!**";

ESP8266WebServer server(80); //Server on port 80

/***************************************************************
 * SETUP
 **************************************************************/
void setup(void){
  Serial.begin(115200);
  WiFi.mode(WIFI_STA);

  WiFi.begin(ssid, password);     //Connect to your WiFi router
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  //If connection successful show IP address in serial monitor
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());  //IP address assigned to your ESP

  server.on("/", handleRoot);      //Which routine to handle at root location

  server.begin();                  //Start server
  Serial.println("HTTP server started");

  pinMode(LED_BUILTIN, OUTPUT);
  pinMode(A0, INPUT);

}
/***************************************************************
 * LOOP
 **************************************************************/
void loop(void){
  server.handleClient();          //Handle client requests

}

/***************************************************************
 * This function converts IPAddress struct to a String
 **************************************************************/
String IpAddress2String(const IPAddress& ipAddress)
{
  return String(ipAddress[0]) + String(".") +\
  String(ipAddress[1]) + String(".") +\
  String(ipAddress[2]) + String(".") +\
  String(ipAddress[3])  ;
}

/***************************************************************
 * This rutine is exicuted when you open its IP in browser
 **************************************************************/
 void handleRoot() {
  IPAddress ip_address = WiFi.localIP();
  String ip_str = IpAddress2String(ip_address);

  int nVoltageRaw = analogRead(A0);
  float fVoltage = (float)nVoltageRaw * 0.00486;

  float fVoltageMatrix[22][2] = {
    {4.2,  100},
    {4.15, 95},
    {4.11, 90},
    {4.08, 85},
    {4.02, 80},
    {3.98, 75},
    {3.95, 70},
    {3.91, 65},
    {3.87, 60},
    {3.85, 55},
    {3.84, 50},
    {3.82, 45},
    {3.80, 40},
    {3.79, 35},
    {3.77, 30},
    {3.75, 25},
    {3.73, 20},
    {3.71, 15},
    {3.69, 10},
    {3.61, 5},
    {3.27, 0},
    {0, 0}
  };

  int i, perc;

  perc = 100;

  for(i=20; i>=0; i--) {
    if(fVoltageMatrix[i][0] >= fVoltage) {
      perc = fVoltageMatrix[i + 1][1];
      break;
    }
  }

  server.send(200, "text/plain", "Hello from esp8266!\n\rIP: " + ip_str +
    ".\n\rTemp: " + "NO" +
    ", Hum: " + "NO" +
    "\n\r" + "NO" +
    "\n\r" + "Voltage: " + fVoltage +
    "\n\r" + "Charge: " + perc + '%');
}

This is a copied code. Where I am not sure about where they got the this formula and how they got the value of 0.00486
I copied this code from different source references. But I hope this will help you to understand the issue.
Any suggestions will be helpful!
Thank you! (In advance)

The biggest problem with the internet is the number of people that think they know what they are doing, but in reality have no idea, but still feel the need to post tutorials about that which they know nothing of .. chances are 0.00486 was either the result of "trial and error", or a case of "chinese whispers" .. code copied and copied and copied again, and somewhere along the line, there was a typo, or two, or three ... and you end up with purple monkey dishwasher (Simpsons reference)

The problem with LiPo batteries is that the discharge curve is very flat.  Here's an example:

As you can see, for about 95% of the life of the battery there is very little change in voltage.  You can't just take the voltage between "full" and "empty" and get a percentage from that. Instead you have to map points along that curve to different percentages.
The simplest way is to just have a set of percentages that you are interested in - every 5% as in the code you have above. Then you say "If the voltage is above this value then it's 100%. If it's above this next value down it's 95%. If it's above the next value down then it's 90%". etc.
The array fVoltageMatrix contains that mapping.  For 100% the voltage must be 4.2V or greater.  For 95% it must be 4.15V or greater. And so on.
If we take those voltage values from the array and plot them on a graph they look like this:

As you see that looks kind of similar. Quite flat, with a sudden drop off.
The code that gets the percentage charge simply reads the value from the ADC and converts it to a voltage by multiplying it by 0.004861, then it steps through the array one element at a time. The first time it finds one that fails the test "This percentage's threshold is less than the voltage" makes it take the previous one in the list as the percentage.  Personally, I think that's backwards and a bad way of doing it.  Instead, it should be the first one that passes the test "The voltage is greater than or equal to this percentage's threshold" that should be taken.  I'd rewrite the loop like this:
perc = 0;

for(i=0; fVoltageMatrix[i][0] > 0; i++) {
  if(fVoltage >= fVoltageMatrix[i][0]) {
    perc = fVoltageMatrix[i][1];
    break;
  }
}

1 The number 0.00486 is the number of volts applied to the input to give a 1 from the ADC. Incidentally, if I am using the right figures, I calculate it should be 0.003125.  1 * (1/1024) gives 0.000976563 (that's 1 volt maximum range on the ADC, multiplied by one bit - a 1024th since it's 10 bit resolution on the ESP8266). Multiply that by the ratio of the resistors ((R1 + R2)/R2) which is 3.2, and that gives 0.003125. To compress it, you get:  x = (R1 + R2) / R2 * 1/1024 = 320000 / 100000 * 0.000976563 = 0.003125
However, my numbers could be wrong...

Thank you so much for such a detailed explanation. It helped to understand a lot. Here if I use this float fVoltage = (float)nVoltageRaw * 0.0041015625; and I get a voltage reading of 4.2 which is awesome. I added a 100k ohms resister to the A0 to positive of my battery. Which makes a lot of sense now! :)

Another problem you can run into is that a lot of the A/D converters use the VCC as a voltage reference. Which means that as your input voltage drops (what you are trying to measure) the reference voltage also drops which means the values you are recording will not appear to change or at least will not give an accurate reference.

One problem I have with the ESP8266 is the crappy results from the A/D converter. There are a number of hoops that you need to go through for the planets to align in order to get consistent readings. See  Fluctuating ADC with stabilized source https://github.com/esp8266/Arduino/issues/2070
The other issue I have is with the assumption that the range of operation of the A/D is 0-1.0 volts and that certainly is not the case.

I calculate it should be 0.003125. 1 * (1/1024) gives 0.000976563
  (that's 1 volt maximum range on the ADC

The above shows how precise our calculations can be but unfortunately the six digits of precision gets thrown out the window if the assumed 1 volt top end has variations of 5%. Unfortunately there are no specifications given as far as the A/D converter in the miniscule spec sheet.
Yes the ESP8266 A/D can be calibrated, and measurements taken under controlled conditions. But make sure that you do the required work and verify the results under all operating conditions before you trust your results.

Below you can find the digital density meter I made for beer and the software I created for temperature and battery tracking.
1 . This part is the process I did to equalize the voltage coming to the voltage divider to the voltage of the battery.
float fVoltage = (float)nVoltageRaw * 1.23;)
You can calculate and find this value (1.23) according to your voltage divider.
But for some reason the battery status fluctuates a bit
2 . I used 2 BC238 transistors for the sensors and the voltage divider so that the ESP does not consume energy when not reading.voltage only passes when transistors are triggered
3 . float pot = map(a.acceleration.x, yogunlukreset0, yogunlukreset1, 997, 1100 );
This part was used to calibrate the device.

    #include <ESP32Firebase.h>

    #include "I2Cdev.h"
    //#include "MPU6050.h"
    #include <Adafruit_MPU6050.h>
    #include <Adafruit_Sensor.h>

    #include <Wire.h>
    #include "Adafruit_MCP9808.h"

    #define _SSID ""
    #define _PASSWORD ""
    #define REFERENCE_URL ""

     Firebase firebase(REFERENCE_URL);

     Adafruit_MCP9808 tempsensor = Adafruit_MCP9808();
     Adafruit_MPU6050 mpu;
     sensors_event_t a, g, temp;

    #define uS_TO_S_FACTOR 1000000ULL  /* Conversion factor for micro seconds to seconds */
    #define TIME_TO_SLEEP  3600       /* Time ESP32 will go to sleep (in seconds) */

    #define bc1 33
    #define bc2 16

     RTC_DATA_ATTR int bootCount = 0;
     const int potPin = 34;

     #include <Preferences.h>
     Preferences pref;

    namespace{
     float yogunlukreset0;
     float yogunlukreset1;

    }
    void wakeup_reason(){
      esp_sleep_wakeup_cause_t wakeup_reason;
      wakeup_reason = esp_sleep_get_wakeup_cause();

    }

    void setup() {

      Serial.begin(115200);
      delay(100);
      pinMode(bc1, OUTPUT);
      pinMode(bc2, OUTPUT);
      delay(100);
      digitalWrite(bc1, HIGH);
      digitalWrite(bc2, HIGH);
      delay(100);

      Wire.begin();
      WiFi.mode(WIFI_STA);
      WiFi.disconnect();
      delay(1000);
      Serial.println();
      Serial.println();
      Serial.print("Connecting to: ");
      Serial.println(_SSID);
      WiFi.begin(_SSID, _PASSWORD);

      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print("-");
      }

      Serial.println("");
      Serial.println("WiFi Connected");

      Serial.print("IP Address: ");
      Serial.print("http://");
      Serial.print(WiFi.localIP());
      Serial.println("/");

      if (!tempsensor.begin(0x18)) {
      Serial.println("Couldn't find MCP9808! Check your connections and verify the address is correct.");
      while (1);
      }
      if (!mpu.begin()) {
        Serial.println("Failed to find MPU6050 chip");
        while (1) {
          delay(10);
        }
     }

    ++bootCount;

      Serial.flush();
      pref.begin("Relay-State", false);
      yogunlukreset0 = pref.getFloat("namespace", false);
      yogunlukreset1 = pref.getFloat("namespa", false);

    }

    void loop() {

      mpu.setCycleRate(MPU6050_CYCLE_20_HZ);

      mpu.getEvent(&a, &g, &temp);

      tempsensor.wake();

      pref.putFloat("namespace", yogunlukreset0);
      pref.putFloat("namespa", yogunlukreset1);

      float c = tempsensor.readTempC();

      String reset2 = firebase.getString("Data/RT2");

      if (reset2 == "1"){
      String reset0 = firebase.getString("Data/RT0");
      String reset1 = firebase.getString("Data/RT1");
      String reset3 = firebase.getString("Data/RT3");

      if (reset0=="1") {
        yogunlukreset0 = (a.acceleration.x);
        }
      if (reset1=="1") {
        yogunlukreset1 = (a.acceleration.x);
        }

      if (reset3 == "1"){
        pref.clear();
        bootCount = 0;
        }

      }

      if (reset2 == "0"){

      float pot = map(a.acceleration.x, yogunlukreset0, yogunlukreset1, 997, 1100 );

      int nVoltageRaw = analogRead(potPin);

      float fVoltage = (float)nVoltageRaw * 1.23;

      float fVoltageMatrix[22][2] = {
        {4150, 100},
        {4130, 95},
        {4110, 90},
        {4080, 85},
        {4040, 80},
        {4010, 75},
        {3970, 70},
        {3930, 65},
        {3890, 60},
        {3850, 55},
        {3810, 50},
        {3760, 45},
        {3710, 40},
        {3660, 35},
        {3610, 30},
        {3550, 25},
        {3490, 20},
        {3430, 15},
        {3370, 10},
        {3320, 5},
        {3270, 0},
        {0, 0}
      };

      int i, perc;

      perc = 100;

      for(i=20; i>=0; i--) {
        if(fVoltageMatrix[i][0] >= fVoltage) {
          perc = fVoltageMatrix[i + 1][1];
          break;
        }
      }

      firebase.setFloat("Data/YG", pot);
      firebase.setFloat("Data/TM", c);
      firebase.setFloat("Data/SYC", bootCount);
      firebase.setFloat("Data/VOLT", fVoltage);
      firebase.setFloat("Data/ORAN", perc);

      digitalWrite(bc1, LOW);
      digitalWrite(bc2, LOW);

      wakeup_reason();
      esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR);
      esp_deep_sleep_start();
      delay(50);
      }

    }

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


text:
Mega attachInterrupt on pins 18 or 19 require EIFR bit set first (to clear it)?
Experimenting with external interrupts on a Mega. Pins 2 and 3 work with standard
attachInterrupt(digitalPinToInterrupt(iPin),ISR,FALLING);
coding and call my ISR. With pins 18 and 19 I had to add
EIFR = 4;

for pin 19, and
EIFR = 8;

for pin 18 before calling attachInterrupt(...) to get them to work. Why?
BTW, I'll add this table that I filled in by trial and error for anyone interested in Atmel (AVR) external interrupt numbers to Arduino external interrupt numbers (I won't list the AVR chip pin numbers)
AVR INT      5 .  4 .  3 .  2 .  1 .  0
EIFR (Dec)  32 . 16 .  8 .  4 .  2 .  1
Arduino Pin  3 .  2 . 18 . 19 . 20 . 21
Arduino INT  1 .  0 .  5 .  4 .  3 .  2

I know writing a 1 to the EIFR bit for the appropriate interrupt clears the interrupt. When I reset the Arduino without clearing interrupts on pins 2 and 3 it's fine. If I don't clear 18 and 19 after a reset, it throws the interrupt right away. (Yes, I should OR the EIFR with the bit I want to change but I'm just playing) Didn't try 20 and 21 because I'm using them for comm.

It's not that pins 18 or 19 are faulty, you are just lucky the other ones worked.
As I mention on my page about interrupts* you are recommended to always write 1 to the appropriate EIFR bit before enabling interrupts because it (the interrupt condition) may have been set in the past.
I checked the source for attachInterrupt in the file WInterrupts.c and there is no mention of the EIFR register, therefore attachInterrupt never affects that register.

* Also see my answer: How do interrupts work on the Arduino Uno and similar boards?

Wow! I know where I'll be spending the next few hours. Thanks!


text:
How to use ESP8266 with Google API for GPS as well as controlling Arduino pins
I am working on IoT based project and I want to control the device using mobile App. Everything works fine, I can switch the load and get the status back on mobile app, but I want to use my ESP8266 as a GPS using google API.
I have googling many many times but people work with standalone ESP8266 as a GPS using google API.
Here there are the two github project for Standalone ESP8266 as GPS:

Google GeoLocation API wrapper for Arduino MKR1000, ESP8266 and ESP32
Google Geolocation API for fetching location on ESP8266 board without using any GPS hardware

My Question is: how can I use my ESP8266 for IoT application (Controlling the Arduino pins) as well as GPS module using Google API?
In my case, I need to use an Arduino Mega/Uno because much more sensors were used in this project which I not mentioned here.
I attached my code, its working perfect, means I controlled the Arduino pins and Arduino send the status using ESP8266 on my mobile App.
String server = ""; //variable for sending data to webpage
boolean No_IP = false; //variable to check for ip Address
String IP = ""; //variable to store ip Address
char data;
char values = 'c';
int flag = 1;

 void setup()
{
Serial.begin(9600);
Serial1.begin(9600);
wifi_init();
delay(200);
showIP();

}

    void loop()
{
  delay(50);
  String temp = "";
while(Serial1.available()) // Check the Esp Serial
{
  temp = Serial1.readString(); // Read the String from Esp Serial
  Serial.println(temp);
  delay(50);
}
if ((temp.substring(11) == "a" or temp.substring(11) == "A") and flag == 1) // If "a" or "A" received
{
  digitalWrite(13,HIGH); // Load conected on pin 13 ON
  Serial.println("Char received High");
  flag = 0;
  sendData("Light On");
  delay(1000);
}

else if ((temp.substring(11) == "a" or temp.substring(11) == "A") and flag == 0)
{
  digitalWrite(13,LOW); // Load conected on pin 13 OFF
  Serial.println("Char received Low");
  flag = 1;
  sendData("Light Off");
  delay(1000);
}
else
{

}

delay(200);

} // Void loop End

These are the functions which is used to established the connection.
Note: I used the ESP 8266 in Station mode
Check in void wifi_init() function,
`
void findIp(int time1) //check for the availability of IP Address
{
  int time2 = millis();
  while (time2 + time1 > millis())  {
    while (Serial1.available() > 0)    {
      if (Serial1.find("IP has been read"))      {
        No_IP = true;
      }
    }
  }
}

void showIP()//Display the IP Address
{
  IP = "";
  char ch = 0;
  while (1)
  {
    Serial1.println("AT+CIFSR");
    while (Serial1.available() > 0)
    {
      if (Serial1.find("STAIP,"))
      {
        delay(1000);
        Serial.print("IP Address:");
        while (Serial1.available() > 0)
        {
          ch = Serial1.read();
          if (ch == '+')
            break;
          IP += ch;
        }
      }
      if (ch == '+')
        break;
    }
    if (ch == '+')
      break;
    delay(1000);
  }
  Serial.print(IP);
  Serial.print("Port:");
  Serial.println(80);
}

void establishConnection(String Serial1and, int timeOut) //Define the process for sending AT Serial1ands to module
{
  int q = 0;
  while (1)
  {
    Serial.println(Serial1and);
    Serial1.println(Serial1and);
    while (Serial1.available())
    {
      if (Serial1.find("OK"))
        q = 8;
    }
    delay(timeOut);
    if (q > 5)
      break;
    q++;
  }
  if (q == 8)
    Serial.println("OK");
  else
    Serial.println("Error");
}

void wifi_init() //send AT Serial1ands to module
{

  establishConnection("AT", 100);

  establishConnection("AT+CWMODE=1", 100);
  establishConnection("AT+CWQAP", 100);
  findIp(5000);
  if (!No_IP)
  {
    Serial.println("Connecting Wifi....");
    establishConnection("AT+CWJAP=\"SSID\",\"PASSWORD\"", 7000);        //provide your WiFi username and password here
  }
  else
  {
  }
  Serial.println("Wifi Connected");
  // showIP();
  establishConnection("AT+CIPMUX=1", 5000);
  establishConnection("AT+CIPSERVER=1,80", 7000);
}

void sendData(String server1)//send data to module
{
  int p = 0;
  while (1)
  {
    unsigned int l = server1.length();
    Serial.print("AT+CIPSEND=0,");
    Serial1.print("AT+CIPSEND=0,");
    Serial.println(l + 2);
    Serial1.println(l + 2);
    delay(100);
    Serial.println(server1);
    Serial1.println(server1);
    while (Serial1.available())
    {
      Serial.print(Serial.read());
      if (Serial1.find("OK"))
      {
        p = 11;
        break;
      }
    }
    if (p == 11)
      break;
    delay(100);
  }
}

Is it possible to use ESP8266 for IoT applications as well as GPS module using google API?

@Juraj problem is that How to GPS values (long and lat) get using google API?. because in the above I mention, #include "ESP8266WiFi.h" used in first link and others, and in the second link #include <WifiLocation.h> is used. Both are not compatable with Arduino mega. these libraries are used with NodeMCU and ESP8266 standalone.....

sorry. you use AT commands. hard to see in you snippets for what platform the code is. then start to code for the esp8266. put the networking part and location in the esp8266 and exchange data with Mega over Serial

@Juraj I can't understand your comment, have you any solution, so please can you share code snippet on answer?. that how ESP 8266 works the above functionality and also getting the GPS location from google API and then exchange with Arduino with Serial communication ?

the google api uses https, so SSL encryption. I don't know about an AVR + esp8266 solution for that with firmware in esp8266. you must write your own sketch for the esp8266 to do the location with google api

@Juraj I think you guide me on right path, I still trying multiple ways, and let you know......Thanks


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:
How do I keep track of the time passed in this code? (PCR machine)
I am desperate need of help with my code. It is meant to be a biology project (a pcr machine) and I struggle with inplementing a time tracker. Everytime the cyclus goes to a function, I need it to save that exact time, and then lt it run for a certain amount of time (this variable is given in a parameter). So help is really really appreciated.
//variabelen

#include <Adafruit_MAX31855.h>

int maxSO =  4;
int maxCS = 5;
int maxSCK = 6;

Adafruit_MAX31855 thermocouple(maxSCK, maxCS, maxSO);

int fan = 9; //connected to transistor base
int temp;
int tempMin = 18;   //variable to check if the thermocouple is connected
int tempMax = 100;   //never exceed this temperature
int fanSpeed;
int RelayP = 3; //still got to check if it is 3 or 4
int cyclusamount = 3; //still got to add a button

//cyclussen op één rij
float DENTEMP = 94;
float ANTEMP = 62;
float EXTEMP = 72;

//tijden op een rij
unsigned int INITDENTIME = 53000;
unsigned int DENTIME = 33000;
unsigned int ANTIME = 33000;
unsigned int EXTIME = 33000;
unsigned int ENDEXTIME = 42000;

unsigned long timer1 = 0;
unsigned long timer2 = 0;
double temp;
double MaxTempIncrease = 2;

//int cycles = 0;
int phase = 0;
int a = 0;
int g = -1;
int phaseOfCyclus = 0;
int timesArray[] = [33000, 33000, 33000];
int tempsArray[] = [94, 62, 72];
int cycluscounter = 0;

const unsigned long startTime;
unsigned long startMillis;

void setup() {
  Serial.begin(9600);
  delay(500);
  pinMode(fan, OUTPUT);
  digitalWrite(fan, LOW);
  pinMode(RelayP, OUTPUT);
  digitalWrite(RelayP, LOW);
  delay(5500);
}

void loop() {
  //eerst is er een delay, na de delay zal a springen op a=1
if(a == 0) {
    delay(1000);
    a++;
  }

//wanneer a=1 geldt dan zal de temperatuur stijgen naar 94 graden, wanneer dit is bereikt wordt  a=2 en phaseOfCyclus=1
else if(a == 1){
     raiseTemp(DENTEMP);
  }

//wanneer a=2 geldt dan zal de temperatuur stabiel worden gehouden (dus 94 graden) voor de initiatie-stap duur, dat is ongeveer rond de 4minuten
//wanneer deze tijd is verstreken dan wordt a=3 (en phaseOfCyclus=1 (nog steeds))
else if(a == 2) {
    holdTemp(DENTEMP, INITDENTIME);
  }

else if(a == 3) {

//De eerste fase van één cyclus in de PCR machine begint met 94 graden voor 30 seconden.
//de functie raiseTemp heeft 1 parameter en die wordt verkregen door het eerste getal uit de tempsArray
//Is dit volbracht, dan wordt phaseOfCyclus=2
if(phaseOfCycles = 1) {
  raiseTemp(tempsArray[1];
}

//de temperatuur wordt dan weer stabiel gehouden, de twee parameters geven de tijdsduur en de temperatuur van de fase waarin de cyclus van de pcr machine zich bevind
//is dit volbracht en was phaseOfCyclus=2, dan wordt phaseofcyclus=3
else if (phaseOfCyclus = 2) {
  holdTemp(tempsArray[1], timesArray[1]; //hoort 0

}

//dan zal de temperatuur afkoelen tot een bepaalde temperatuur, als dit is volbracht -> als phaseofcyclus=3 dan wordt phaseofcyclus=4
else if (phaseOfCyclus = 3) {
  cooldown(tempsArray[2]; //hoort 1
}

//de temperatuur wordt weer stabiel gehouden, voor 30 seconden en als phaseofcyclus is 4 dan phaseofcyclus=5
else if (phaseOfCyclus = 4) {
  holdTemp(tempsArray[2], timesArray[2]; //hoort 1

}

//dan zal de temperatuur verder afkoelen tot een bepaalde temperatuur, als dit is volbracht -> als phaseofcyclus=5 dan wordt phaseofcyclus=6
else if (phaseOfCyclus = 5) {
  cooldown(tempsArray[3]; //hoort 2
}

//de temperatuur wordt weer stabiel gehouden, voor 30 seconden en als phaseofcyclus is 5 dan phaseofcyclus=6
//bij één hele cyclus zal holdtemp 3x worden aangeroepen, elke keer als dit dus 3x gebeurt dan zal de cyclusamount +1 in hoeveelheid toenemen
//als de cyclusamount niet gelijk is aan het aantal cyclussen dat iemand wil uitvoeren dan zal -> phaseofCyclus = 1
//is dit wel groter of gelijk aan het aantal cyclussen dat iemand wil uitvoeren dan zal -> a =4  (als a = 3 en phaseofcyclus = 6)
else if (phaseOfCyclus = 6) {
  holdTemp(tempsArray[3], timesArray[3]; //hoort 2
}}

//dan zal de extending temperatuur stabiel worden gehouden en als de tijd is verstreken dan zal a = 5 worden en zal de lcd zeggen dat de cyclus is volbracht
else if (a == 4) {
   holdTemp(EXTEMP, 42000);
  }
else if(a == 5) {
  digitalWrite(fan, LOW);
  digitalWrite(RelayP, LOW);
  Serial.println("Cyclus completed");
}
}

void raiseTemp(double y) {
  double prevTemp = thermocouple.readCelsius();
  temp = thermocouple.readCelsius();

if (temp < tempMin) {
   Serial.println("is the thermocouple connected???");
  }

while (temp < y) {
    int waittime = min(650, ((650*(y-temp))));
    digitalWrite(RelayP, HIGH);
    delay(waittime);
    digitalWrite(RelayP, LOW);
    temp=thermocouple.readCelsius();

if(temp >= y) {
    if(phaseOfCyclus = 1) {
      phaseOfCyclus = 2;
      a = 3;
    }
    else if (phaseOfCyclus = 0){
      phaseOfCyclus++;
      a = 2;
    }
      // break; //wat doet dit precies?
    }

if((y-temp) < 1) {
      do  {
        prevTemp = temp;
        delay(250);
        temp = thermocouple.readCelsius();
      }
      while(temp > prevTemp);
    }

if(temp >= TempMax)
     break;

else {
      prevTemp = temp;
   }

   while ((temp-prevTemp) >= MaxHeatIncrease) {
     prevTemp = temp;
     Serial.print("HEATING UP TOO FAST! ");
     delay(1000);
     temp = thermocouple.readCelsius();
     Serial.println(temp);
   }

   while(temp >= y) {
     delay(1000);
     Serial.print("DANGER DANGER DANGER");
     Serial.println(temp);
   }
}}

void holdTemp(double phaseTemp, double duration) {
  g++;
  z = phaseTemp;

  startMillis = millis();
  unsigned long whatitneedstobe = startTime + duration;
  //startMillis < whatitneedstobe

  if(timegone < duration){
        temp = thermocouple.readCelsius();
      if(temp < z) {
        digitalWrite(RelayP, HIGH);
        delay(90);
        digitalWrite(RelayP, LOW);
      }
      else if (temp > (z+0.5)) {
        digitalWrite(fan, HIGH);
        delay(90);
        digitalWrite(fan, LOW);
        //or
        //fanSpeed = map(temp, tempMin, y, 32, 255);
        //analogWrite(fan, fanSpeed);
      }
     delay(210);
     timegone = millis() - startTime;
     }

  else {
    if(phaseOfClus = 1) {
      a = 3;
    }
    else if(phaseOfCyclus = 2) {
      phaseOfCyclus = 3;
    }
    else if(phaseOfCyclus = 4) {
      phaseOfCyclus = 5;
    }
    else if(g == 3) {
    g = 0;
    cycluscounter++;
    if(cycluscounter < cyclusamount) {
      a = 3;
      phaseOfCyclus = 1;
    }
    else(cycluscounter >= cyclusamount {
      a = 4;
    }
  }
  else if(a = 4) {
    a = 5;
  }
    }
  }

void cooldown(double c) {
  unsigned long startTime = millis();
while ((temp = thermocouple.readCelsius()) > (minTemp+0.75)) {
    digitalWrite(fanPin, HIGH);
    delay(300);
   }
   digitalWrite(fanPin, LOW);
if(thermocouple.readCelsius() == c){
  if(phaseOfCyclus = 3) {
    phaseOfCyclus = 4;
  }
  else if(phaseOfCyclus = 5) {
    phaseOfCyclus = 6;
  }
}
}

I am logged in now, but can't change what I have put inside the question. I meant: I am in desperate need of help with my code. It is a biology/electronics project (a pcr machine) and I struggle with implementing a time tracker in the code. I want that Everytime the cyclus goes to a holdtemp(), the time when it reaches the code gets saved and then let the code run for a certain amount of time (that certain amount of time is giving in a parameter). Help and advice is much appreciated.

Please request merging your accounts. That will give you access to your original post.  See: https://stackoverflow.com/help/merging-accounts

Lines like  holdTemp(tempsArray[1], timesArray[1]; //hoort 0 have bad syntax/missing parentheses.   /// In holdTemp(), what's the difference/intention between startMillis and startTime?

If you want the holdTemp() function to run for a specified duration,
you can write it like this:
void holdTemp(double phaseTemp, unsigned long duration) {
    unsigned long start_time = millis();
    while (millis() - start_time < duration) {
        // whatever...
    }
}

Note that if you use delay() inside the function, the time spent in it
may get longer than the requested duration, by as much as the duration
of the delay.


text:
Seeed CAN Shield - Not receiving extended CAN-Message
I want to receive an extended CAN-Message. I send a extended CAN-Message, but nothing happens. Maybe somebody have an idea what the problem is..
It works with a standard CAN-Message.
Thanks in advance.
// demo: CAN-BUS Shield, send data
// loovee@seeed.cc

#include <mcp_can.h>
#include <SPI.h>

// the cs pin of the version after v1.1 is default to D9
// v0.9b and v1.0 is default D10
const int SPI_CS_PIN = 9;

MCP_CAN CAN(SPI_CS_PIN);                                    // Set CS pin

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

    while (CAN_OK != CAN.begin(CAN_250KBPS))              // init can bus : baudrate = 250k
    {

        CAN.init_Mask(0,1,0);
        CAN.init_Filt(0,1,0);

        Serial.println("CAN BUS Shield init fail");
        Serial.println(" Init CAN BUS Shield again");
        delay(100);
    }
    Serial.println("CAN BUS Shield init ok!");
}

unsigned char len = 0;
unsigned char buf[30];

void loop()
{
    CAN.readMsgBuf(&len, buf);    // read data,  len: data length, buf: data buf
    unsigned long canId = CAN.getCanId();
    Serial.println("-----------------------------");
    Serial.print("Get Data from ID: 0x");
    Serial.println(canId, HEX);
    Serial.println("Data content:");
    for(int i = 0; i<len; i++) // print the data
    {
        Serial.print(buf[i]);
        Serial.print("\t");
    }
    Serial.println("-----------------------------");
}

What happens if you remove the filter and the mask?

It change nothing.

Maybe this discussion can help you: https://github.com/Seeed-Studio/CAN_BUS_Shield/issues/39

Unfortunately, I found this discussion, but nothing changed.

How do you send the message? With the same Can-shield on a different Arduino? If yes, can you post code of the sender? I assume you don't have any other device to verify, if the extended frame is actually sent to the bus?

I read a CAN communication from an other device. So I don't have the code of the decide. I only know, that the Baudrate is 250k and it is using extended CAN messages. I want to read with the Arduino Uno the CAN communication.


text:
Double precision floating point operations using Arduino
Today we were programming something in university which dealt with really large numbers (even larger than unsigned long) and we had to create a code that broke the  numbers into an array and performed operations on them.
I know that an Arduino is an 8 bit MCU, but I was wondering if similar approaches could be used to do 32 bit double precision floating point operations (or even better,  i.e quad precision, etc) using the Arduino (e.g. create a quad precision calculator or similar applications).
I know it sounds silly or similar to a brute force method, but I'm really curious if it's possible to do such things.

Anything is possible if you have the programming skills. Natively the highest precision Arduino supports is float. Anything more precise you will have to code your own support for from scratch. Or there's Nick Gammon's Big Number library for massive integer use.

Note also that double precision is actually 64 bits (with 52+1 bits in the mantissa). For integers, avr-gcc natively supports int64_t and uint64_t.

The source code for float handling in AVR could be a starting point. The compiler back-end for AVR might need changing so that true double literal numbers could be used in sketches. https://github.com/vancegroup-mirrors/avr-libc/tree/master/avr-libc/libm/fplib

Thanks everyone. I'm a bit busy but I'll try to come up with some sort of code myself. I'll ask more details if I couldn't figure something on my own, thanks.


text:
Connecting TFT Display MI0283QT-9A to ESP32
I have purchased a MI0283QT-9A TFT display (https://download.mikroe.com/documents/add-on-boards/other/display/tft-proto/tft-proto-manual-v200.pdf) which is
driven by the ILI9341 display controller.
I've managed to find the following board specification: http://pub.ucpros.com/download/tft_320_240_mi0283qt_9a_v1_3_spec.pdf
First of all, the pins are named differently from all the examples I can find for connecting it to my ESP32 microcontroller. For example, the TFT specs describe:
33 SDO Serial Output Signal
34 SDI Serial Input Signal
35 RD Read execution control pin
36 WRX(D/CX) Write execution control pin ; Serial Register select s Signal
37 D/CX(SCL) Register select signal; Serial Interface Clock
38 CSX Chip Select Signal
39 TE Tearing effect out pin synchronize MPU to frame writng

But this Adafruit ILI9341 example (https://github.com/adafruit/Adafruit_ILI9341/blob/master/examples/graphicstest/graphicstest.ino) talks about CS, DC, MOSI, CLK, RST, and MISO.
I think these map as follows, can anyone confirm that?
ESP32 = TFT
--------------
DC    = RS
CLK   = WR, although maybe it should connect to DC???
CS    = CSX
MOSI  = SDI
RST   = RST
MISO  = SDO

I'm really unsure about the first two!
Second, in the PDF it refers to note 1 on page 11:

So as far as I can tell, I need to set the voltage high/low on the four IM* pins, depending upon the interface I want to use. So the second question is which interface does the Adafruit ILI9341 library use?

The wiring depends on what mode you are using the board in - which mode you select from the table of modes you show (what settings you give to IM0-IM3).

It sounds like you want a 4-wire 8-bit serial SPI compatible interface.  To get that you have to set the IMx pins to the right state to enable that interface.  That means:

IM0 = LOW
IM1 = HIGH
IM2 = HIGH
IM3 = HIGH

You can hard-wire those to GND for LOW and +3.3V for HIGH.
That will then configure it to work in the right mode for you, where it gives you access to the following pins:
| Display  | ESP32   | Function                    |
|----------|---------|-----------------------------|
| SCL (RS) | SCK     | Serial clock                |
| SDI      | MOSI    | Serial data Master -> Slave |
| SDO      | MISO    | Serial data Slave -> Master |
| D/CX (WR)| DC      | Data / Command register sel |
| CSX      | CS      | Chip Select (Active Low)    |
| RST      | RST     | Reset                       |

what does "active low" mean, next to CS?

is the RST pin on the ESP32, the EN pin, or some pin of my choice?

It means that the input is considered "activated" when it receives a LOW signal. I.e., the chip is activated when you apply LOW to that pin.

RST and DC are pins of your choice. They are just GPIOs to control the screen.

thanks for the help. I still have a problem with SCL and DCX: according to the specs: TFT Pin36: WRX//D/CX) Write execution control pin ; Serial Register select s Signal; TFT Pin37: D/CX(SCL)  Register select signal; Serial Interface Clock.   none of those names are on TFT board. but we do have RS = Register Select => so DC is the RS pin. that means SCL/SCK must be the WR pin. ok, ill check that.

forget the above comment.  Thanks for the help. I still have a problem with SCL and DCX: according to the specs: TFT Pin36: WRX//D/CX) Write execution control pin ; Serial Register select s Signal; TFT Pin37: D/CX(SCL)  Register select signal; Serial Interface Clock.   There is no pin on the board with the name D/CX(SCL), but there is one called RS and one called WR. So I guess WR is the DC and RS is the clock?

Map the pins using the schematic.  Pin 36 is DC in serial mode. That's LCD-WR# on the board (WR). Pin 37 is SCL in serial mode. 37 is RS on the board. So DC -> WR and SCK -> RS. The board is really labelled from a 16-bit 8080 interface perspective.

OK, I started using the SPI pins of the ESP32 rather than GPIO pins. DC/WR=12; SCK/RS=18; CS=15; SDI/MOSI=23; RST=14; MISO/SDO=19. the board now flickers, although it doesnt show what it supposed to. and the program now outputs non-zero values: Display Power Mode: 0xFF; MADCTL Mode: 0xE0; Pixel Format: 0xFF; Image Format: 0xFF; Self Diagnostic: 0xFF. see also https://github.com/espressif/arduino-esp32/blob/master/docs/esp32_pinmap.png

The IM0 pin was unplugged from gnd => stuck it back in, and now it works perfectly. thanks!!!

Excellent.  There's not much I haven't learned about TFTs over the years ;)

Same (TFT proto board) tested Arduono DUE.
Pins IM1-3 HI, IM0 LO. (4-wire 8-bit data serial interface)
SDI - MOSI, SDO - MISO,RS - CLK, RD - HI, WR - D9, CS - D10, Reset - Reset (D8)
Driver UTFT myGLCD (ILI9341_S5P, MOSI, SCK, 10,8,9);
or
// For the Adafruit shield, these are the default.
#define TFT_DC 9
#define TFT_CS 10
Adafruit_ILI9341 tft = Adafruit_ILI9341 (TFT_CS, TFT_DC);

Backlight needs resistor!


text:
Arduino MKR GSM 1400 SSL client example fails to connect
I am using the GsmSSLWebClient example which comes with the MKRGSM library.
The original example works just fine, I get the arduino ascii logo. But when I change the URL the arduino doesn't get any answer:
//char server[] = "arduino.cc";
//char path[] = "/asciilogo.txt";
char server[] = "wepardi.fi";
char path[] = "/robots.txt";

Starting Arduino web client.
connecting...
connected
GET /robots.txt HTTP/1.1
Host: wepardi.fi
Connection: close

disconnecting.

From Firefox https://www.wepardi.fi/robots.txt is displayed correctly.
I tried also some other sites, and from some of them I get the ascii file content correctly, and from some others not.
Something wrong with my settings?
Prints from debug mode:
connecting...

...
AT+USECMNG=0,0,"VeriSign_Class_3_Public_Primary_Certification_Authority_G5",1239
>
+USECMNG: 0,0,"VeriSign_Class_3_Public_Primary_Certification_Authority_G5","cb17e431673ee209fe455793f30afa1c"

OK
AT+USOCR=6

+USOCR: 0

OK
AT+USOSEC=0,1,0

OK
AT+USECPRF=0,0,1,4,"www.wepardi.fi"

OK
AT+USOCO=0,"www.wepardi.fi",443

ERROR

+UUSOCL: 0
AT+USOCL=0

ERROR
connected
GET /robots.txt HTTP/1.1
Host: www.wepardi.fi
Connection: close

disconnecting.

Command
    AT+USOCO=0,"www.wepardi.fi",443
fails
GsmWebClient (no SSL) example works fine with any hosts I have tried.

in browser you enter www.wepardi.fi and in arduino only wepardi.fi

I finally found a solution to this problem. Disabling certificate validation in MKRGSM library makes the SSL connection succeed also to this site. In MKRGSM/src/GSMClient.cpp I changed
//     MODEM.sendf("AT+USECPRF=0,0,1,4,\"%s\"", _host);
       MODEM.sendf("AT+USECPRF=0");

to use modem factory settings. I still don't know what was the problem with the certificates.
Thanks to everyone who tried to help with this.

The problem you have is that of redirection.
You connect to wepardi.fi and request the file /robots.txt from that host. It immediately tells you "Ok, but that file is actually on www.wepardi.fi/robots.txt. Go get it from there.
But it won't.
You have to go direct to the source.
Here's a trace:
GET /robots.txt HTTP/1.1
Host: wepardi.fi
Connection: close

HTTP/1.1 302 Found
Date: Tue, 08 Jan 2019 14:26:51 GMT
Server: Apache/2.4.6 (CentOS) OpenSSL/1.0.2k-fips PHP/7.0.32
Strict-Transport-Security: max-age=63072000; includeSubdomains;
X-Powered-By: PHP/7.0.32
Location: https://www.wepardi.fi/
Cache-Control: max-age=1296000
Expires: Wed, 23 Jan 2019 14:26:51 GMT
Content-Length: 0
Connection: close
Content-Type: text/html; charset=UTF-8

And when you change to www.wepardi.fi:
GET /robots.txt HTTP/1.1
Host: www.wepardi.fi
Connection: close

HTTP/1.1 200 OK
Date: Tue, 08 Jan 2019 14:27:49 GMT
Server: Apache/2.4.6 (CentOS) OpenSSL/1.0.2k-fips PHP/7.0.32
Strict-Transport-Security: max-age=63072000; includeSubdomains;
X-Powered-By: PHP/7.0.32
X-Robots-Tag: noindex, follow
Link: <https://www.wepardi.fi/wp-json/>; rel="https://api.w.org/"
Cache-Control: max-age=300
Expires: Tue, 08 Jan 2019 14:32:49 GMT
Content-Length: 67
Connection: close
Content-Type: text/plain; charset=utf-8

User-agent: *
Disallow: /wp-admin/
Allow: /wp-admin/admin-ajax.php
read:errno=0

Thanks, but still I don't get the file content: Starting Arduino web client.
connecting...
connected
GET /robots.txt HTTP/1.1
Host: www.wepardi.fi
Connection: close
disconnecting.

Can you get any sort of feedback to the request?


text:
Voltage meter ADC + serial: Bytes lost during communication
I want to make a simple digital voltage monitor. So I have a sketch:
void setup() {
  Serial.begin(115200);
}

void loop() {
  int val = analogRead(A4);     // read the input pin
  val = 1;
  byte buf[4];
  buf[0] = 0;
  buf[1] = 0;
  buf[2] = val & 255;
  buf[3] = (val >> 8) & 255;
  Serial.write(buf, 4);             // report voltage value
}

When I tried to read serial buffer on PC host, I noticed that sometimes 1 byte can be lost, which lead to shifts and headache. How should the streaming be done?

PS.

host os: win7 x64;
language: c/c++
com port library: CSerial

Loop is as follows:
typedef int32_t sample_t;
while (true) {
    int nBytesRead = serial.ReadData(lpBuffer, bufSize * sizeof(sample_t));
    size_t numRead = nBytesRead / sizeof(sample_t);
    if (numRead > 0)
        std::cout << "read: " << numRead << " samples\n"; // Calculate average here!
}

Either by printing it as simple ASCII, or by wrapping the values in a proper packet format with DLE.

@Majenko What is a "proper DLE packet"? I cannot find any reference on what DLE could stand for.

Data Link Escape. Your problem is you don't know where the data starts. You need a properly formed header with preamble, and a way of making bytes that appear in the data not appear to be a header byte. Or just use ASCII which restricts the valid data bytes to a very limited range.

@Majenko I thought i can prefix each values with 0xAAAA (like ethernet preamble stuff), then put a length field, then append postfix 0x5555 that means "transmission is done", and check if data length equals actual length - then is a valid packet.

That's the right kind of idea, yes. However you have to ensure that 0xAA or 0x55 never appear in your data. And that's where DLE comes in.

For example, replace 0xAA with 0xFF 0x0A then interpret that sequence at the receiver as 0xAA. Of course, 0xFF has to itself be escaped - as 0xFF 0xFF for example.

So at the receiver, if you see 0xFF then throw it away - but treat the next incoming character as something special.

@Majenko arduino 10-bit adc readings cannot exceed 1023. so these both cannot appear in data. i can even better place there 0xFFFF, 2 bytes length, 2*length bytes payload

One could. For example you may end up with 0xAA 0xAA 0x02 0x01 0x55 0x55 0x55

@Majenko so need to eliminate ending of a packet, replace it with length?

However, by the time you have done all this, your packet is now bigger than, for example, 1F3\n which would suffice.  That's just 4 bytes maximum (less if the value < 256) - the size of just your pre- and postambles.

@Majenko You mean Serial.println(val, HEX); and parsing that on host?

That would give you \r\n as the ending - wasting a byte. Serial.print(val, HEX); Serial.print("\n"); saves that one byte (if you care).  Then, yes, parse it on the host (which is simple enough).

The easiest way is to send the integer as ascii and do a atoi or atol on the pc. A '\n' or 'etx' at the end should be enough. If you want to be 100% sure, then a 'stx' at the begin and perhaps a checksum just before the '\n' or 'etx'. No HEX, but just Serial.print(val) for the data. The cable between the pc and the arduino is not a serial cable but a usb cable. A byte getting lost is almost impossible, something else is wrong.

@Majenko, That byte saved alot, now i am getting 5ksps instead of 3.5! Summing them up for a second and getting average leads to quite precise 16~20 bit voltmeter

@Jot It is solved, trouble was that i recieved data with 0 or 1 byte shift, and we found a simple way of solving it. sending via base-10 ascii would lead to poorer performance than sending hex

@xakepp35 For higher baudrates, you can try a arduino leonardo or micro. They have usb connected to the microcontroller itself and the communication is with usb speed because there is no real serial port. What about calculating the average in the arduino?

@Jot you think it will increase sampling rate (e.g better noise floor?) how much analogReads per second could it call? I have mega2560. How do i tie that to seconds in arduino? I need 1 measure per second, as precise as possible. Also summing up several thousand of samples would overflow 16bit integers.

The arduino mega has a 10-bits adc. Everything (linearity, noise, and so on) matches those 10 bits. I think a good start is an external 16-bits adc: https://www.adafruit.com/product/1085

@Jot when you sum up multiple samples, random noise is attenuated (If i sum up 16 samples, I could get at most 3 or 4 bits of extra precision, because random noise inside each sample will cancel itself out, and real DC data would properly sum up)

@xakepp35 yes, I always use the average of a number of samples to read dc voltages. But the linearity does not increase and that would be needed for a voltage meter. The overall precision requires a better adc than 10-bits.

@Jot for a 50 amps 220V wattmeter i calculated that i require 16 bit adc, to stay cool and precise less than 0.5W. Can i connect many 16-bit adc to single arduino board?

@xakepp35 The adafruit ADS1115 module has 4 analog inputs and 4 of those modules can be connected to a single i2c bus. For a wattmeter, what is the sample rate that you need? With many channels a adc with spi bus might be better, since the i2c bus is slow.

@Jot I need to measure up to 50a shunt, with precision more than "0.5W error per day"

With help in a comments I've managed to deal with the task myself.
First of all, as @Majenko pointed out, I was dealing with some multi-byte data. So I need some control character, that separates packets. I choose hex output with '\n' delimeter as control character - that served good. I was able to read 3.5 to 5k packets per second (with voltage reading) from serial on the host.
Second improvement, credited to @Jot, is to stack some sequential values right in arduino, before sending.
Alongside with increasing sampler frequency that could be very good.
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))

void setup() {
  sbi(ADCSRA, ADPS2);
  cbi(ADCSRA, ADPS1);
  cbi(ADCSRA, ADPS0);
  Serial.begin(115200);
}

void loop() {
  int val = 0;
  for( int i = 0; i < 32; ++i )
    val += analogRead(A0);
  Serial.print(val, HEX);
  Serial.print("\n");
}

at the host recieve side, some simple conversion could be done:
#include "Serial.h"
#include <iostream>
#include <fstream>
#include <string>
#include <ctime>

// sample to voltage
double s2v(int sample) {
    return 5.0 * (static_cast<double>(sample) / 1024);
}

int main() {
    std::ofstream ofs("test.csv", std::ios::out | std::ios::ate);

    size_t comPort = 3;
    size_t baudRate = 115200; // 57600;

    CSerial serial;
    if (serial.Open(comPort, baudRate))
    {
        std::cout << "COM" << comPort << " opened @" << baudRate << "bit/s\n";

        // serial recv buffer
        size_t bufSize = 1048576;
        auto lpBuffer = new char[bufSize];

        // accumulator
        size_t nVals = 0;
        int nAcc = 0;

        // timer
        __time64_t destTime;
        __time64_t destTime2;
        _time64(&destTime);

        while (true) {
            SleepEx(10, false); // care of 100% cpu core usage, poll serial port lazily
            size_t nBytesRead = serial.ReadData(lpBuffer, bufSize * sizeof(lpBuffer[0]));

            //parse buffer:
            size_t cvtPtr = 0;
            for (size_t i = 0; i < nBytesRead; ++i) {
                if (lpBuffer[i] == '\n') {
                    try {
                        lpBuffer[i] = '\0';
                        auto val = std::stoi(lpBuffer + cvtPtr, nullptr, 16);
                        nAcc += val;
                        nVals++;
                    }
                    catch (...) {
                        // ignore, or warn that serial recieved junk/empty packet
                    }
                    cvtPtr = i + 1;
                }
            }

            //check if doom had come!
            _time64(&destTime2);
            if ((destTime2 - destTime) > 0) {
                auto fVoltage = ( s2v(nAcc) / 32 ) / nVals;
                std::cout << fVoltage << "\t(" << nVals << " ksps)\n";
                ofs << destTime << "," << fVoltage << "," << nVals << "\n";
                if((destTime % 30 ) == 0) // care of disk, write only once in 30 seconds
                    ofs.flush();
                destTime = destTime2;
                nVals = 0;
                nAcc = 0;
            }
        } // while
    } // if opened
    return 0;
}

That gives voltmeter with high precision, about ±0.5mV, that is updated every second.
Also! It was stated about 10bit adc, 5.0V/1024 = 4.88mV, but i got some subthreshold oscillations in vivo, adding samples up. So you are wrong, noise can be attenuated and resolution can be artificially pumbed up, in a trade for increased sampling time. Here is 14bit ADC built on top of 10bit ADC: . Its photovoltaic cell in a dark street, oscillations are caused by cars' front lights. Timescale is 1000 seconds per grid div

Don't you mean +-5mV? Because 5V / 1024 (10 bit) is about 4.9mV

@chrisl I mean i got 3-4 bits more resolution that was specified for arduino 10-bit ADC.


text:
Calculate burden resistor value of current transformer and measure ac current with arduino
I Want to measure AC current with current transformer but i dont know exact value of burden resistor or calculation formula...i want to measure current of borewell pump. company specified pump as 1.5Hp power.

There is no "You need X resistor for Y transformer". The resistor you choose depends on what current range you are working with and what voltage range you want that to be expressed as.
That transformer is a 100:5 (or more properly a 20:1) ratio.  That means for every 20A going through it you get 1A out.
That output current is then passed through a burden resistor and you measure the voltage across that resistor.
If you are, for example, working with sensing up to 1A current then the maximum current you'd get out of it would be 1/20A, or 50mA.  If you want that to be expressed reliably within the range of a 5V ADC then you would:

Work from the mid-range of the ADC as 0V to give ±2.5V (assuming AC)
Calculate the resistor that gives 2.5V across it when 50mA is passed through it
Pick the next-lowest common resistor value.
Reverse the calculation to get the voltage range you now have.

In this example, R=V/I, so 2.5/0.05 = 50Ω.  50Ω resistors aren't common, but 47Ω ones are, so you'd pick that.
Then reversing it gives V=IR = 0.05 * 47 = ±2.35V
Give it a 2.5V offset to the ADC and you can now read points on a sinewave between 0.15V and 4.85V at 1A sensed current.

Thanks for answer..I want to measure about 5 to 6 amps of current with this transformer. Then what value of resistor is required for this??

Have you tried doing the maths?

What if you want to measure the whole 5 amps. With the 5v from Arduino its giving me 1 ohm. Is there a power rating I need to worry about in the burden resistor?


text:
Command through Serial monitor does not properly work in Arduino
I am executing a function in Arduino by giving String input to the serial monitor.
The issue here is when I enter SHOW$, the function showData() works but when I enter the same SHOW$, it doesn't gets called.
I want to call the function showData() every time i enter the SHOW$ text into the serial console.
My question here is to what mistake I am doing here, and what is the solution for this.
String strReq = "";
char inChar = 0;

void setup() {

  Serial.begin(9600);

}

void loop() {

  while (Serial.available())
  {
    inChar = Serial.read();

    if (inChar == '$') {

     Serial.println(" Received String :");
     Serial.print(strReq);

     if (strReq.equalsIgnoreCase("SHOW"))
       showData();

     Serial.flush();
     strReq = "";

    } else {

      strReq = strReq + inChar;
    }
  }
}

void showData() {
  Serial.print("Showing Information");
}

how is line ending set in Serial Monitor? it is possible that the second time you add line end characters from previous input to strReq

both NL & CR is set

then the second input is "\r\nSHOW" and this is not equal to SHOW

right because next time it is printing with new line.. how to solve this.?

one option is to ignore control caracters when reading. else if (inChar >= 32) {

what other option is there. because there are too many strings i am comparing in original code.
actually serial data output doesn't matter to me. I am turning LED on and off on this command , it is not executing in the second time as explained in the question.

Do you know what Serial.flush() does?

@Majenko, flush waits until tx buffer is empty

@Juraj I'm not asking you. I know you know. Looking at the code I am thinking the java bee thinks it works how it did in pre-Arduino 1.0.0.

you could turn off the line ends in Serial Monitor

You could also use a real terminal emulator instead of the POS Serial "monitor".

@Majenko, sorry. I overlooked the flush() in OP's code

@Juraj If the OP assumed it worked how it used to (clears the RX buffer contents) then the code would work as expected.

The solution was to use String.trim() function.
Thanks guys for giving a quick reply on the question.

The root of your problem seems to be not knowing what Serial.flush() does.
It pre-Arduino 1.0.0 times Serial.flush() used to clear any data in the serial's RX buffer. It would throw it away.  In your code that would throw away the line ending \r\n that is sent along with the command.
However in Arduino 1.0.0 it was changed to instead block execution until all bytes had been sent out of the Serial TX buffer.  This was deemed more useful, and a replacement to the original functionality is very easy to implement if needed.
This change was not widely documented, but it is mentioned in the manual:

Waits for the transmission of outgoing serial data to complete. (Prior to Arduino 1.0, this instead removed any buffered incoming serial data.)

So with Serial.flush() acting like it does in current versions, you would get a different string the second time around.  You would see:
SHOW$
\r\nSHOW$
\r\nSHOW$

and so on.
You have come up with a "fix", which uses String::trim() to discard any leading and trailing non-printable characters, which removes the line-endings from your subsequent strings.  However it would be far better to ignore them in the first place and not need to do the trimming.
The simplest way would be to only add characters to your string if they are printable:
if (inChar == '$') {
 Serial.println(" Received String :");
 Serial.print(strReq);
 if (strReq.equalsIgnoreCase("SHOW"))
   showData();
 Serial.flush();
 strReq = "";
} else if (inChar >= ' ') { // << Only add if a space or above
  strReq = strReq + inChar;
}

A simple change, but one which then means you're not having to add the extra processing of trimming unwanted characters from the string.


text:
2.8 inch tft LCD displays / Max Brightness / Startup White Screen / mirror text for Head Up Display Usage
hi does anyone know how to
1) set Max Brightness
2) change the start up splash screen from being white to black
3) how to change settings so that text can be mirrored so when display is reflected into mirror or glass window the text reflects onto the mirror / glass so that it is readable
The code from the sketch may answer some of your tecnical question re the environment i am working with
#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_TFTLCD.h> // Hardware-specific library

#define LCD_CS A3 // Chip Select goes to Analog 3
#define LCD_CD A2 // Command/Data goes to Analog 2
#define LCD_WR A1 // LCD Write goes to Analog 1
#define LCD_RD A0 // LCD Read goes to Analog 0

can be done w/hjardware usually, PWM'ing the backlight. 2 is just whatever the demo code does, there's no std splash screen. 3. you'll have to modify the gfx lib or use a custom font.

1) set Max Brightness

You set the brightness of the backlight (usually) using PWM.

2) change the start up splash screen from being white to black

That's not a splash screen. That's just the back light being on before the screen is initialised. Just don't turn on the back light until you need it.

3) how to change settings so that text can be mirrored so when display is reflected into mirror or glass window the text reflects onto the mirror / glass so that it is readable

Either do it in software (tricky) or look at the MADCTL (many have it called that) register in the datasheet.  The library probably won't support it, but it's part of how it deals with display rotation, so you could examine that function and compare it with what's in the datasheet (hint: 180° rotation is actually flipping both the X and Y axis).

Thanks for the answers above. Sorry this is all very new to me

Thanks for the answers above. Sorry I dont have an electronics / component background please excuse the nievety.
Answer 1 above,
what is PWM and where do i find it and how do i use it to achieve point 1 objective
Answer 2 Above
So how do i turn offf the backlight as the uit backlight lights up as soon as power is connected even when the LCD is not connected to the processor, so i assume its not using the code to initally turn the back light on given there is no arduio processing any code yet the backlight is on
Answer 3
Where do i find the MADCTL  in order to alter it

Majenco i really do appreicate your assistance so far. I was hoping t find a graphics driiver option so i could code the reverse / mirror flip. I am looking to add an gyro to the unit so that if the unit is flipped so it faces driver not windscreen  (opposite to  default position the code detects this from gyro output & then changes the aspect of code being displayed so its readable by driver. Same logic to be applied if the driver wants it placed upside down form the default position so that power connector was on left side not right side (allowing for left / right hand drive)

PWM: Pulse Width Modulation. Involves turning an output on and off very rapidly with varying ratios of on-to-off times to simulate an analog output. Control the pins that have ~ by them with analogWrite().

How you control the back light depends on what shield you are using.

For MADCTL read the datasheet for the TFT screen on your chosen shield.

the 2.8 tft lcd qr4 5265s01 g3/2 TP28017

This one? https://www.adafruit.com/product/1651


text:
Encoder code using interrupts design question
I have an Arduino Mega 2560, an Omron Optical encoder with an Index (360 steps), a 60 led NeoPixel ring (no Clk wire) and another Arduino Uno.
Here is my question, I have some code written that works with the Arduino Mega and optical encoder outputting decently to the serial monitor for diagnostic purposes.
When I add the additional code to run the Neopixel ring I get a terrible response on the ring.  I have tried the NeoPixel and FastLED libraries with the same terrible success.  It even states in their documentation that they don't work well with interrupts.  I started thinking about sending the 3 digit output to a Direct Pin output from the Mega to be read by another Mega/Uno to run the Neopixel Ring and a 4x20 LCD screen. Does anyone else have any ideas on this.  Below is my code for the Mega and the Encoder.
    // Wiring connections for my encoder:
    // Brown : VCC = 5V
    // Blue + Shield : 0V = GND
    // Black : ENCODER0PINA, Pin 18
    // White : ENCODER0PINB, Pin 17
    // Orange : ENCODER0PINI, Pin 19

    #define ENCODER0PINA         18      // this pin needs to support interrupts
    #define ENCODER0PINB         17      // no interrupt required
    #define ENCODER0PINI         19      // this pin needs to support interrupts

    // variables modified by interrupt handler must be declared as volatile
    volatile long encoder0Position = 0;
    volatile long interruptsReceived = 0;
    volatile byte INTFLAG1 = 0;

    // track last position so we know whether it's worth printing new output
    long previousPosition = 0;

    void setup()
    {
      // inputs
      pinMode(ENCODER0PINA, INPUT);
      digitalWrite(ENCODER0PINA, HIGH);  // turn on pullup resistor
      pinMode(ENCODER0PINB, INPUT);
      digitalWrite(ENCODER0PINB, HIGH);  // turn on pullup resistor
      pinMode(ENCODER0PINI, INPUT);
      digitalWrite(ENCODER0PINI, HIGH);  // turn on pullup resistor

      // interrupts
      attachInterrupt(5, onInterrupt, RISING);  // encoder track A on interrupt 3 - pin 18
      attachInterrupt(4, onReset, RISING);  // encoder Index track on interrupt 4 - pin 19

      // enable diagnostic output
      Serial.begin (115200);
      Serial.println("Ready.");
    }

    void loop()
    {
      // only display position info if has changed
      if (encoder0Position != previousPosition )
      {
        Serial.println(encoder0Position, DEC);

        previousPosition = encoder0Position;
      }
    }

// interrupt function needs to do as little as possible

void onInterrupt()
{
  // read both directional inputs
  int a = digitalRead(ENCODER0PINA);
  int b = digitalRead(ENCODER0PINB);

  if (a == b)
  {
    // b is leading a (counter-clockwise)
    encoder0Position--;
    if (encoder0Position < 0)
    {
      encoder0Position = ((encoder0Position + 360) % 360);
    }
  }
  else
  {
    // a is leading b (clockwise)
    encoder0Position++;
    if (encoder0Position >= 360)
    {
      encoder0Position = ((encoder0Position - 360) % 360);
    }
  }
}

void onReset()
{
  // read Index input
  int i = digitalRead(ENCODER0PINI);
  if (i == 1)
    {
  encoder0Position = INTFLAG1;
    }
}

i would use the ESP32, which can drive the WS2812b in hardware using the IR remote control functionality, and had a whole 2nd core if that's somehow not good enough. Also, try to avoid analogRead() in the ISR, that takes quite some time, and with 360 clicks, you're going to be quite busy with any kind of rapid twisting.

Will the ESP32 be good for taking the 3 digit integer reading from the encoder to other devices as well?  My complete goal would be to use the ESP32 for the 60 NeoPixel Ring, monitoring signal strength (0 to 5 V, pin input) and output some results to a 4x20 LCD screen.  Lastly rectifying the 3 digit reading from the encoder with the ultimate compass from AdaFruit.?

yes, it would be great for that, being hundreds of times faster and dozens of times more memory, with many hardware-accelerated interfaces to reduce core resource usage. might also grab a few level-shifters; sometimes the ESP32 doesn't like 5v devices, though many, such as neopixels, work fine as-is...


text:
Question about controlling servos with PWM while being able to accurately read the current from a sensor
Hi I am hoping to design a custom board ATMEGA32u4 with practically a Arduino leonardo bootloader. I plan to control up to 12 servos while being able to read back the current sensor voltage of an INA169 current sensor on voltage changes. The  voltage reading will be read back into a digital pin through an ADC controlled by a  multiplexer. The question is am I able to manage all the current sensing on all 12 servos properly with this setup? or should I use a faster controller that act as a master to do the data collection from the current sensor while the ATMEGA32u4 focus on controlling the servos? I plan to store this data too, so is this the right way of doing things?

a digital output would be better, like the ina219. expect some noise, but it should still be able to give you a rough idea or identify stuck motors.

@dandavis I think previously was using the INA219 for current sensing but can't remember why my partner and me instead choose the 169 over the 219(i think we plan to have an current sensor each on the high side of every servo and wasn't sure if the I2C protocol was fast enough or if there were enough addresses to control 12 of them.). I think the purpose was to use the current sensor to have better control of those cheap micro servos 9g by reading back it current draw and potentiometer reading.


text:
SIM900/Arduino UNO R3 serial communication not working
For some reason I cannot establish serial connection between the two devices. The shield is connected to the network because my number can be called, but I cannot send it any commands via the serial.
I tried several ways to wire it up:
shield rx&tx (the ones that require female jumper) to 7 & 8 of arduino, declaring 7 & 8 in the serial.
shield pins 7 & 8 (they have (serial) as label) to 7 & 8 of arduino, declarting 7 & 8 in the serial.
shield rx&tx the little holes to 7 & 8 of arduino, declaring 7 & 8 in the serial.
Tried even different pins other than 7 & 8. None worked.
I'm powering the shield with 12v transformator that can provide up to 3Ah and the arduino is connected to laptop.
Any suggestions ?
Here's the code:
#include <SoftwareSerial.h>

//Create software serial object to communicate with SIM900
SoftwareSerial mySerial(7, 8); //SIM900 Tx & Rx is connected to Arduino #7 & #8

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

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

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

  mySerial.println("AT"); //Handshaking with SIM900
  updateSerial();

  mySerial.println("AT+CMGF=1"); // Configuring TEXT mode
  updateSerial();
  mySerial.println("AT+CMGS=\"+ZZxxxxxxxxxx\"");//change ZZ with country code and xxxxxxxxxxx with phone number to sms
  updateSerial();
  mySerial.print("Last Minute Engineers | lastminuteengineers.com"); //text content
  updateSerial();
  mySerial.write(26);
}

void loop()
{
}

void updateSerial()
{
  delay(500);
  while (Serial.available())
  {
    mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
  }
  while(mySerial.available())
  {
    Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port
  }
}

And also, why are there so many RX/TX on the shield ? I see RXD/TXD and RX/TX.

What shield? A link to the product please.

https://www.amazon.com/SODIAL-Quad-Band-Modules-Development-Arduino/dp/B077953H5P there you go friend

To make everything work fine with this exact code and wiring from the lastminuteengineers, you need to change the jumper (black plastic piece) position in J11. it has to connect the pins D8(RX) and D7(TX), which are the pins at the top of the yellow plate, to the two pins in the middle of the yellow plate.

And also, why are there so many RX/TX on the shield ? I see RXD/TXD and RX/TX.

There aren't.  There is only one of each. They just have them in multiple convenient places.
J11 selects the pins to use on the shield. Make sure that is set to D7 and D8. You then use pins D7 and D8 on the shield. Normally that would be mounted directly onto an Arduino and you would just use those pins in your code.
However, if you want to attach it to something that doesn't have an Arduino UNO footprint you can solder wires to the TX/RX pins in the J10/J17 "UART" header. That ignores the J11 jumpers, which only pertain to using the Arduino UNO shield headers.
As to why you can't communicate, my guess is:

You have 9600 baud in your code:

mySerial.begin(9600);

However, on the Amazon product you linked to:

The factory default setting for the GPRS Shield UART is 19200 bps 8-N-1. (Can be changed using AT commands).

Using 19200 instead of 9600 should improve matters somewhat.

It doesn't improve anything. I've tried ALL the rates. If there was a mismatch, I'd at least see some squares or other strange shapes, but I don't see anything on the serial at all!

Does your shield have jumpers on J11? The picture shows them missing.

Compare it to the one shown in this tutorial: https://randomnerdtutorials.com/sim900-gsm-gprs-shield-arduino/

I pulled out all the wires so I   could take a picture.
https://imgur.com/a/jhpzyI7
That's how j11 and j12 look. I've tried plugging females to the pointy ones. The tutorial above has some jumper caps that I have no idea what they are.
edit: I took a closer look and itseems mine are not in the same position, but I never thought these could be plugged out and replugged in, lol. That's the first thing I am going to try after work. Could you explain about those ?

Looks like its set right. Just plug it direct into your arduino. No need for wires.

The middle pair of pins are  tx and rx. the outer pairs of pins connect to the headers. The jumpers just link the two.

No, mine is not the same as the toturial. I just made them just like in the tutorial, copied the code and STILL AT wont respond!
I've also tried stacking them together.

I still haven't resolved my issue. Any other help would be greatly appreciated!
I'm also up for a video talk if this is what it takes. I absolutely want to run this.


text:
RN4678 Bluetooth doesn't respond
I am facing very basic level issue with RN4678. I purchased a module from https://www.mikroe.com/rn4678-click
I want to simply communicate with it through serial port.  To do that I connected it to PC by usb to TTL. Whatever I send, I don't get any response from module.  Then parallely I paired it with mobile phone and on successful connection, from  Android app terminal I tried the same and nothing happened.  If I send something from PC, I get it on mobile but reverse doesn't work.    And the main issue is Module doesn't respond at all.   I tried 3modules as well.
Help would be appreciated.

Have you made sure that your USB to TTL is implementing flow control on the UART. An option is to delete the CTS/RST in RN configuration and try two wire UART to eliminate CTS/RTS option


text:
Unsure how to get pressure data from MCP3424
I am having trouble reading data from an MCP3424 chip, specifically the one from this website:
https://uk.rs-online.com/web/p/general-purpose-adcs/6696086/
I have a pressure transducer that connects to the MCP3424 chip. The chip is then connected to a NodeMCU 1.0. Schematics are attached.
The pressure transducer comes from here:
https://www.edwards.com/gb/devices/pressure-monitoring/transducer?WT.ac=eu_truwave
It is run into a 9-pin VGA adapter
I am new to this kind of stuff, and I do not know what code is needed on the NodeMCU to read the data coming in from the pressure transducer via the MCP3424 chip. My code currently contains code from here:
https://github.com/bersch/MCP3424
My code is set to upload the error message I am getting from the MCP3424 to a spreadsheet so I can read the error. The error I get is "i2c". I am not sure what that means. I have tried contacting the author of the code but I have not received a response in a few weeks. I simply want to read the pressure I am getting from the pressure transducer from the MCP3424 chip.
Some useful information about the MCP3424 chip can be found here:
http://ww1.microchip.com/downloads/en/DeviceDoc/22088b.pdf
If anyone can provide any guidance, code, or helpful advice, that would be extremely appreciated.
Link to my post on the arduino forum, which includes my code, is here:
https://forum.arduino.cc/index.php?topic=588831.0
Thank you.

my bet is on a wrong I2C address. run the I2C scanner sketch and adjust any hard-coded value on the sensor demo sketch once you identify the module. If it doesn't show up un the scanner, try adjusting the wires.

I ran the i2c scanner and all I get is a bunch of unknown errors at every address...what does this mean about the board?

It means it's hooked up to the MCU wrong, you forgot the I2C pullups (sometimes they can be ignored, sometimes not) or it doesn't have enough voltage/current. It's possible the module or board is defective, but that's a lot rarer than user error.


text:
noisy output lines when waking up from a sleep
Using code similar to these examples from AVR
https://www.microchip.com/webdoc/AVRLibcReferenceManual/group__avr__sleep.html
my program causes my Adafruit Feather 32u4 to often sleep. When the firmware has nothing to do it will sleep about 75% of the time. Typically after several hours of operation there will be corruption on the LCD display. The elapsed time to the corruption is not deterministic.
When it sleeps or wakes up from sleep I believe the processor sends garbage to the LCD module via the SPI (serial) lines. I have no oscilloscope to observe this but the problem seems to be removed if I comment out the sleep code.
A description of the Adafruit ST7565 LCD module is at this link
https://www.adafruit.com/product/250.
My Arduino setup code relevant to sleeping is this:
cli(); // atomic operation begins here
WDTCSR = bit(WDCE) | bit(WDE); // enter a very brief change mode
WDTCSR = bit(WDP2); // prescaler without reset mode, 1001 means 8 seconds, 0101 means 0.5 seconds, 0100 means 0.25 seconds, 0011 means 0.125 seconds
WDTCSR = bit(WDIE); // use interrrupt mode because we do not want an WDT triggered reset
sei(); // global interrupt enable
set_sleep_mode(SLEEP_MODE_PWR_DOWN);

My sleep code in the Arduino loop is adapted from the AVR webpage and is invoked if the firmware is not busy, is as follows:
cli(); // atomic operation begins here
sleep_enable();
sei();
sleep_cpu();
sleep_disable();

The watchdog ISR for when it wakes up is an empty function, as follows:
ISR(WDT_vect) // need this to avoid a reset
{ // no code here
}

I have a little bit of other evidence that some lines are uncontrolled when the processor wakes up. The evidence comes from my rotary encoders. I see false encoder activity sometimes when the processor wakes up and I eliminated this problem by putting some "debounce code" in the watchdog ISR. I also make sure the encoder lines use the processor's internal pull-up resistors. Note that I already have debounce code for the encoders for the purpose of doing actual debouncing of the activity of actually touching the encoders. The additional "debounce code" in the watchdog ISR is for the situation in which I am not even touching the encoders but the processor is waking up and the lines are noisy. The encoder "debounce code" is not shown in the watchdog ISR code snippet because it's not relevant to my LCD problem.
The pull-up and debounce remedy for encoder input lines is not applicable to my LCD problem because the LCD involves output lines.
Edit: I tried to solve it by setting high the active low chip select of the LCD before sleep and then reverting the line upon waking up (in the watchdog ISR). This had the effect of making the display very sluggish. I update the display once per second and it seemed to be updating only once every 2 or 3 seconds. I have not analyzed whether my "direct intervention" is incompatible with the Adafruit library for this LCD.
The LCD library: https://github.com/adafruit/ST7565-LCD
The boards are as pictured. The encoder board has 2 encoders wired up and 2 encoders unused. The encoder board sits on a 3mm thick piece of foam and is clamped to the desk. The breadboard is attached to the desk via the double sided foam tape that seems to be standard on this item.

Addendum: Given Nick Gammon's answer, I will run with the following to see if the problem is eliminated. Since the corruption is not deterministic, it may take many hours or days before I form an opinion.
  cli(); // atomic operation begins here
  WDTCSR = bit(WDCE); // enter a brief change mode
  WDTCSR = bit(WDIE) | bit(WDP2); // 1001=8s, 0101=0.5s, 0100=0.25s, 0011=0.125s
  sei(); // global interrupt enable
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);

After less than 10 hours there was corruption on the LCD. I will test with the following.
  cli(); // atomic operation begins here
  WDTCSR = bit(WDCE) | bit(WDE); // enter a brief change mode
  WDTCSR = bit(WDIE) | bit(WDP2); // 1001=8s, 0101=0.5s, 0100=0.25s, 0011=0.125s
  sei(); // global interrupt enable
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);

The above still failed after several hours.

WDTCSR = bit(WDCE) | bit(WDE); // enter a very brief change mode
WDTCSR = bit(WDP2); // prescaler without reset mode, 1001 means 8 seconds, 0101 means 0.5 seconds, 0100 means 0.25 seconds, 0011 means 0.125 seconds
WDTCSR = bit(WDIE); // use interrrupt mode because we do not want an WDT triggered reset

Your code above is not doing a WDT interrupt every 0.25 seconds as you appear to be wanting, because you assign (not OR) in the third line. That means WDP0/WDP1/WDP2?WDP3 will all be zero which means the watchdog will fire every 16 ms.

This had the effect of making the display very sluggish.

I'm not totally surprised, if you interrupt every 16 ms.

I have a little bit of other evidence that some lines are uncontrolled when the processor wakes up.

The lines should remain what they were set to when the processor sleeps. It wouldn't be very useful to sleep if the processor started outputting random junk while asleep. I can't comment further as I can only see part of your code.

Thank  you. My comment will be an addendum to the question.

You were likely correct to say that the problem was not caused by sleeping. By shortening the wires to the display I was able to run for over 50 hours without seeing display corruption and 50 hours is unprecedented.


text:
append a String on ArduinoJson Object value
I've a json string request coming from server and I convert it into json object
  StaticJsonBuffer<500> jsonStaticBuffer;
  JsonObject& root = jsonStaticBuffer.parseObject(String(msg));
  String reqId;
  String reqData;
  root["requestid"].printTo(reqId);
  root["data"].printTo(reqData);

I need to populate another char json string initiated at the beginning
const char response[] = "{\"response\": {\"requestid\":, \"data\":}}";

such that I need to write requestid into the response::requestid and data into response::data + ACK/NAK . here is how i've tried;
  DynamicJsonBuffer jsonDynResponse;
  JsonObject& jsonResponse = jsonDynResponse.parseObject(response);
  String out;
  if (ACK) {
      jsonResponse["response"]["requestid"] = root["requestid"];
      jsonResponse["response"]["data"] = root["data"] + " ACK"; //THIS DOESN'T WORKS
      jsonResponse.printTo(out);
  } else {
      jsonResponse["response"]["requestid"] = reqId;
      jsonResponse["response"]["data"] = reqData + " NAK";
      jsonResponse.printTo(out);
  }

I know this will definitely not work root["data"] + " ACK" because we can't combine const char with String. But this reqData + " NAK"; resulted in "\"data\" NAK"". How can I concate root["data"] into another String ?
Thank you in advance :)

String(root["data"]) + " ACK"?

Tried that already, I get exit status 1 call of overloaded 'String(ArduinoJson::Internals::JsonObjectSubscript<const char*>)' is ambiguous

perhaps you need to create a String variable, do things with it, and then jsonResponse["response"]["data"] = whateverYourStringVariableIsCalled;

The things that I want to do with the string is append ACK/NAK on whatever is in root["data"]. Which I am not able to do.


text:
Upload data to MAX 7219
I have the following code to write data on MAX7219 for light up a 8x8 LED Matrix:
for (i = 0; i < 8; i++)
{
    CLK = LOW;
    DIN = temp & MSBIT >> i;
    CLK = HIGH;
}

The thing is, sadly, I just know that the code line (DIN = temp & MSBIT >> i;), must be exactly like that, otherwise the LED´s won't show the expected, but I don't understand how it works...
Please, I really need explanation because I'm stuck....
Note: variable "temp" is always a hexadecimal number like 0x20, and "MSBIT" = 0x80.

Please, post complete code.

You have to send 16 bits to load data.  The first 8 are the register the data goes into, 0 to 15, the next 8 are the data to be displayed. Registers 1-8 are the data that gets displayed, the others are used to set up: intensity, display test, normal/shutdow, decode/no decode mode, and number of digits/columns connected (such as 4 digits, or 8 for an 8x8 matrix).
In Arduino, I use hardware SPI to send data to MAX7219 - SCK, MOSI, and SS.
digitalWrite (ssPin, LOW);
SPI.transfer(addressRegister); // 0 to 15
SPI.transfer(dataToLoad);
digitalWrite (ssPin, HIGH);

Do that for each register. The control registers only need to be written once. In Arduino, that is usually in setup().  Intensity might be changed later for brightness (0 to 15 as valid data).
In loop(), use the above to update your display for the 8 display data registers (1-8).

SPI default speeds of 4 MHz, MSBFIRST, SPI Mode 0 do not need to be changed.


text:
Fujitsu FMC-16LX(MB90F387) Pulse Sensor BPM formula displaying only 96BPM
#include "_ffmc16.h"
#include "extern.h"
#include "monitor.h"

void initLCD();
void delay();
void instCtrl4(unsigned char data);
void display(unsigned char temp);
void display1(unsigned char pulse, int counter);
void decoder(int newtemp);
void instCtrl(unsigned char data);
void dataCtrl(char data);

#define RS IO_PDR2.bit.P24
#define RW IO_PDR5.bit.P53
#define E IO_PDR5.bit.P52
#define LCD IO_PDR2.byte
#define BUZZER IO_PPGC23.bit.PEN1

unsigned char AD_DATA, temperature, bpm;
int count = 0, counter=0;
int UpperThreshold = 518;
int LowerThreshold = 490;
int IgnoreReading = 0;
int FirstPulseDetected = 0;
    unsigned char FirstPulseTime = 0;
    unsigned char SecondPulseTime = 0;
    unsigned char PulseInterval = 0;
    unsigned char BPMResult;

void main()
{
    __set_il(7);
    __EI();

    IO_DDR2.byte = 0x1F;
    IO_DDR5.bit.D53 = 1;
    IO_DDR5.bit.D52 = 1;

    IO_ADER.bit.ADE3 = 0;
    IO_ADER.bit.ADE2 = 0;

    //BUZZER
    IO_PPGC23.bit.PE1=0x01;
    IO_PPG23.byte=0x00;
    IO_PRL23.byte.PRLL3=0xFA;
    IO_PRL23.byte.PRLH3=0xFA;

    initLCD();
    instCtrl(0x84);
    dataCtrl('T');
    dataCtrl('E');
    dataCtrl('M');
    dataCtrl('P');
    dataCtrl('E');
    dataCtrl('R');
    dataCtrl('A');
    dataCtrl('T');
    dataCtrl('U');
    dataCtrl('R');
    dataCtrl('E');
    dataCtrl(':');

    instCtrl(0x99);
    dataCtrl('P');
    dataCtrl('U');
    dataCtrl('L');
    dataCtrl('S');
    dataCtrl('E');
    dataCtrl('R');
    dataCtrl('A');
    dataCtrl('T');
    dataCtrl('E');
    dataCtrl(':');

    while(1)
    {
    counter++;

    IO_DDR5.bit.D55 = 0;    /* PORT5 DDR set(AD1) */
    IO_ICR03.byte = 0x00;   /* A/D INT level set */
    IO_ADCSH.bit.BUSY = 0;  /* ADC stop */
    IO_ADER.byte = 0x02;    /* ADC input enable, ch-1 */
    IO_ADCSL.byte = 0xAD;   /* ADC mode set */
    IO_ADCRLH.byte.ADCRH = 0xF8;    /* set 8bit-AD, comp.176cycle, sample.128cycle */
    IO_ADCSH.bit.INTE = 1;  /* interrupt enable */
    IO_ADCSH.bit.STRT = 1;  /* start ADC */

        display(AD_DATA);

        /*if(temperature>38)
        {
            BUZZER=0x01;
        }
        else if(temperature<34)
        {
            BUZZER=0x01;
        }
        else
        {
            BUZZER=0x00;
        }*/

    IO_DDR5.bit.D54 = 0;    /* PORT5 DDR set(AD1) */
    IO_ICR03.byte = 0x06;   /* A/D INT level set */
    IO_ADCSH.bit.BUSY = 0;  /* ADC stop */
    IO_ADER.byte = 0x10;    /* ADC input enable, ch-1 */
    IO_ADCSL.byte = 0xA4;   /* ADC mode set */
    IO_ADCRLH.byte.ADCRH = 0xF8;    /* set 8bit-AD, comp.176cycle, sample.128cycle */
    IO_ADCSH.bit.INTE = 1;  /* interrupt enable */
    IO_ADCSH.bit.STRT = 1;  /* start ADC */
        display1(AD_DATA, counter);
    }
}

void delay()
{
    for(count=0; count<1000;count++)
    {
    }
}

void initLCD()
{
    delay();
    instCtrl4(0x03);
    delay();
    instCtrl4(0x03);
    delay();
    instCtrl4(0x03);
    delay();
    instCtrl4(0x02);
    delay();
    instCtrl(0x28);
    instCtrl(0x08); //off
    instCtrl(0x01); //clear
    instCtrl(0x06); //entry mode: increment or shift mode
    instCtrl(0x0C); //display on; cursor on;blink on
    instCtrl(0x01);
}

void instCtrl4(unsigned char data)
{
    LCD = data;
    RS = 0;
    RW = 0;
    E =1;
    delay();
    E =0;
}

void display(unsigned char temp)
{
    temperature = (temp * 500) / 255;
    instCtrl(0xC8);
    decoder((temperature/10)%10);
    decoder(temperature%10);
    dataCtrl(0xDF);
    dataCtrl('C');
}

void display1(unsigned char pulse, int counter)
{

    /*if(pulse > UpperThreshold && IgnoreReading == 0)
    {
        if(FirstPulseDetected == 0)
        {
          FirstPulseTime = counter;
          FirstPulseDetected = 1;
        }
        else
        {
          SecondPulseTime = counter;
          PulseInterval = SecondPulseTime - FirstPulseTime;
          FirstPulseTime = SecondPulseTime;
        }
        IgnoreReading = 1;
      }

      // Heart beat trailing edge detected.
      if(pulse < LowerThreshold)
      {
        IgnoreReading = 0;
      }

      BPMResult = (1 / PulseInterval) * (60000);*/

      //bpm= pulse; /* default n ??*/

    instCtrl(0xD9);
    decoder((BPMResult/100)%10);
    decoder((BPMResult/10)%10);
    decoder(BPMResult%10);
    dataCtrl('B');
    dataCtrl('P');
    dataCtrl('M');
}

void decoder(int newtemp)
{
    switch(newtemp)
    {
        case 0:
            dataCtrl('0');
            break;
        case 1:
            dataCtrl('1');
            break;
        case 2:
            dataCtrl('2');
            break;
        case 3:
            dataCtrl('3');
            break;
        case 4:
            dataCtrl('4');
            break;
        case 5:
            dataCtrl('5');
            break;
        case 6:
            dataCtrl('6');
            break;
        case 7:
            dataCtrl('7');
            break;
        case 8:
            dataCtrl('8');
            break;
        case 9:
            dataCtrl('9');
            break;
    }
}

void instCtrl(unsigned char data)
{
    LCD=data>>4;
    RS =0;
    RW=0;
    E=1;
    delay();
    E=0;
    LCD=data;
    RS=0;
    E=1;
    delay();
    E=0;
}

void dataCtrl(char data)
{
    LCD=data>>4;
    RS=1;
    RW=0;
    E=1;
    delay();
    E=0;
    LCD=data;
    RS=1;
    E=1;
    delay();
    E=0;
}

__interrupt void ADC_int(void)
{
    IO_ADCSH.bit.INT = 0;       //interrupt flag clear
    AD_DATA = IO_ADCRLH.DATA8;  //A/D conversion interrupt vector
}

/* Vector Table */
#pragma section INTVECT, locate=0xfffc00
#pragma intvect _start      0x8     0x0 /* Reset Vector */
#pragma intvect ADC_int     18      /* AD converter vector */

what is your question?

Agreed, if you don't actually ask anything, then what replies do you expect to receive?

Can you check my code.. because my Pulse Sensor Formula is only displaying 96BPM

@jsotola Do you have a formula for pulse sensor?

what pulse sensor?  .... a quick google search reveals that the MB90F387 is a fujitsu microcontroller and FMC-16LX is a cable that is used to program the MB90F387 ..... the whole thing is not even related to an Arduino .... either way, as far as i can tell, you have provided no information about the sensor

@jsotola I am using this sensor https://www.google.com/search?q=pulse+rate+sensor&rlz=1C1CHBF_enPH810PH810&source=lnms&tbm=isch&sa=X&ved=0ahUKEwixxYWv1uLfAhUMdt4KHb3aApIQ_AUIDigB&biw=1437&bih=652#imgrc=Vm-dILTaaC0WuM: I already displayed the values but I can't get the exact BPM because of my formula.. yes I know its not related to arduino but they are both microcontroller