text:
esp32-cam publish image to mqtt
I want to publish image capture through ESP32-CAM to MQTT. Have following code :
#include "WiFi.h"
#include "esp_camera.h"
#include "esp_timer.h"
#include "img_converters.h"
#include "Arduino.h"
#include "soc/soc.h"           // Disable brownour problems
#include "soc/rtc_cntl_reg.h"  // Disable brownour problems
#include "driver/rtc_io.h"
#include <StringArray.h>

#include <PubSubClient.h>
#include <base64.h>
#include <libb64/cencode.h>

// Replace with your network credentials
const char* ssid = "####";
const char* password = "####";

// Add your MQTT Broker IP address, example:
const char* mqtt_server = "###.cloudmqtt.com";
const int mqtt_port = 11073;
const char* mqtt_user = "###";
const char* mqtt_password = "###";

#define SLEEP_DELAY 10000 //Delay ofr 10 Sec
#define FILE_PHOTO "/photo.jpg"

// OV2640 camera module pins (CAMERA_MODEL_AI_THINKER)
#define PWDN_GPIO_NUM     32
#define RESET_GPIO_NUM    -1
#define XCLK_GPIO_NUM      0
#define SIOD_GPIO_NUM     26
#define SIOC_GPIO_NUM     27
#define Y9_GPIO_NUM       35
#define Y8_GPIO_NUM       34
#define Y7_GPIO_NUM       39
#define Y6_GPIO_NUM       36
#define Y5_GPIO_NUM       21
#define Y4_GPIO_NUM       19
#define Y3_GPIO_NUM       18
#define Y2_GPIO_NUM        5
#define VSYNC_GPIO_NUM    25
#define HREF_GPIO_NUM     23
#define PCLK_GPIO_NUM     22

//#define ESP32_CLIENT_ID = WiFi.macAddress()
//const char* esp_client_id = WiFi.macAddress()
WiFiClient mqttClient;
PubSubClient client(mqttClient);

const int LED_BUILTIN = 4;

void setup_camera() {
      // Turn-off the 'brownout detector'
      WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0);

      // OV2640 camera module
      camera_config_t config;
      config.ledc_channel = LEDC_CHANNEL_0;
      config.ledc_timer = LEDC_TIMER_0;
      config.pin_d0 = Y2_GPIO_NUM;
      config.pin_d1 = Y3_GPIO_NUM;
      config.pin_d2 = Y4_GPIO_NUM;
      config.pin_d3 = Y5_GPIO_NUM;
      config.pin_d4 = Y6_GPIO_NUM;
      config.pin_d5 = Y7_GPIO_NUM;
      config.pin_d6 = Y8_GPIO_NUM;
      config.pin_d7 = Y9_GPIO_NUM;
      config.pin_xclk = XCLK_GPIO_NUM;
      config.pin_pclk = PCLK_GPIO_NUM;
      config.pin_vsync = VSYNC_GPIO_NUM;
      config.pin_href = HREF_GPIO_NUM;
      config.pin_sscb_sda = SIOD_GPIO_NUM;
      config.pin_sscb_scl = SIOC_GPIO_NUM;
      config.pin_pwdn = PWDN_GPIO_NUM;
      config.pin_reset = RESET_GPIO_NUM;
      config.xclk_freq_hz = 20000000;
      config.pixel_format = PIXFORMAT_JPEG;

      if (psramFound()) {
        config.frame_size = FRAMESIZE_UXGA;
        config.jpeg_quality = 10;
        config.fb_count = 2;
      } else {
        config.frame_size = FRAMESIZE_SVGA;
        config.jpeg_quality = 12;
        config.fb_count = 1;
      }
      // Camera init
      esp_err_t err = esp_camera_init(&config);
      if (err != ESP_OK) {
        Serial.printf("Camera init failed with error 0x%x", err);
        ESP.restart();
      }
  }

// Capture Photo and Save it to SPIFFS
void capturePhoto( void ) {
  camera_fb_t * fb = NULL; // pointer
  bool ok = 0; // Boolean indicating if the picture has been taken correctly

  // Take a photo with the camera
  Serial.println("Taking a photo...");

  fb = esp_camera_fb_get();
  if (!fb) {
    Serial.println("Camera capture failed");
    return;
  }

  Serial.print("Heap Size : ");
  Serial.println(ESP.getFreeHeap());
  //Serial.println(fb->format);
  Serial.print("fb len : ");
  Serial.println(fb->len);
  Serial.print("base64 encode expected len : ");
  Serial.println(base64_encode_expected_len(fb->len) + 1);
  String base64image = base64::encode(fb->buf, fb->len);
  Serial.print("base64 image : ");
  Serial.println(base64image);
  esp_camera_fb_return(fb);
}

void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  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.println(WiFi.localIP());
}

void reconnect() {
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    if (client.connect("ESP32Client", mqtt_user, mqtt_password)) {
      Serial.println("connected");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}

void setup() {
  Serial.begin(115200);
  setup_camera();
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
  setup_wifi();
  client.setServer(mqtt_server, mqtt_port);
}

// the loop function runs over and over again forever
void loop() {
  Serial.println("PSRAM found: " + String(psramFound()));
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
  capturePhoto();
  if (!client.connected()) {
    reconnect();
  }
  client.loop();
  delay(SLEEP_DELAY);
}

This prints following to console
Connecting to ####
...
WiFi connected
IP address : 192.168.1.247
PSRAM found: 1
Taking a photo...
Heap Size : 187548
fb len : 135966
base64 encode expected len : 181289
base64 image : -FAIL-

Update Feb 15 :
I tried following code
void setup() {
  Serial.begin(115200);
}

// the loop function runs over and over again forever
void loop() {
  Serial.println("PSRAM found: " + String(psramFound()));
  Serial.print("Total heap: ");
  Serial.println(ESP.getHeapSize());
  Serial.print("Free heap: ");
  Serial.println(ESP.getFreeHeap());
  Serial.print("Total PSRAM: ");
  Serial.println(ESP.getPsramSize());
  Serial.print("Free PSRAM: ");
  Serial.println(ESP.getFreePsram());
}

which printed
PSRAM found: 1
Total heap: 378748
Free heap: 352836
Total PSRAM: 4194252
Free PSRAM: 4194252

These are the board settings
Board : AI Thinker ESP32 CAM
Latest board package :

I tried wit following board settings as well
Board : ESP32 Dev Module
Upload Speed : 921600
CPU Frequency : 240 MHz
Flash Frequency : 80 MHz
Flash Mode : QIO
Flash Size : 4MB
Partition Scheme : Default 4MB with spiffs
Core Debug Level : Verbose
PSRAM : Enabled
which also gives me following output
[D][esp32-hal-psram.c:47] psramInit(): PSRAM enabled

Connecting to ###
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 0 - WIFI_READY
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 2 - STA_START
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 4 - STA_CONNECTED
[D][WiFiGeneric.cpp:337] _eventCallback(): Event: 7 - STA_GOT_IP
[D][WiFiGeneric.cpp:381] _eventCallback(): STA IP: 192.168.1.247, MASK: 255.255.255.0, GW: 192.168.1.1
.
WiFi connected
IP address : 192.168.1.247
PSRAM found: 1
Taking a photo...
Heap Size : 187260
fb len : 101157
base64 encode expected len : 134877
base64 image : -FAIL-

From this output it looks like PSRAM is enabled. How can I use it for base64 encoded image ?
Also tried to add byte* psdRamBuffer = (byte*)ps_malloc(500000); mentioned at https://thingpulse.com/esp32-how-to-use-psram/ but didn't help.
I have this ESP32-CAM
Update :
I got following working, but it crashes for framesize_t resolution_ =FRAMESIZE_QXGA; that's why not able to capture 2 Megapixel picture.
#include "WiFi.h"
#include "esp_camera.h"
#include "esp_timer.h"
#include "img_converters.h"
#include "Arduino.h"
#include "soc/soc.h"           // Disable brownour problems
#include "soc/rtc_cntl_reg.h"  // Disable brownour problems
#include "driver/rtc_io.h"
#include "SPIFFS.h"
#include "base64.h"
#include <PubSubClient.h>

// Replace with your network credentials
const char* ssid = "xxxxx";
const char* password = "xxxxx";

// Add your MQTT Broker IP address, example:
const char* mqtt_server = "xxxx.cloudmqtt.com";
const int mqtt_port = 1883;
const char* mqtt_user = "xxxx";
const char* mqtt_password = "xxxxx";

//topic name
const char* mqtt_TopicName = "/devices/esp32/data";

framesize_t resolution_ = FRAMESIZE_QVGA;

//use this delay 1000==1 second
#define SLEEP_DELAY 60000 //Delay ofr 60 Sec
#define FILE_PHOTO "/photo.jpg"

// OV2640 camera module pins (CAMERA_MODEL_AI_THINKER)
#define PWDN_GPIO_NUM     32
#define RESET_GPIO_NUM    -1
#define XCLK_GPIO_NUM      0
#define SIOD_GPIO_NUM     26
#define SIOC_GPIO_NUM     27
#define Y9_GPIO_NUM       35
#define Y8_GPIO_NUM       34
#define Y7_GPIO_NUM       39
#define Y6_GPIO_NUM       36
#define Y5_GPIO_NUM       21
#define Y4_GPIO_NUM       19
#define Y3_GPIO_NUM       18
#define Y2_GPIO_NUM        5
#define VSYNC_GPIO_NUM    25
#define HREF_GPIO_NUM     23
#define PCLK_GPIO_NUM     22

//#define ESP32_CLIENT_ID = WiFi.macAddress()
//const char* esp_client_id = WiFi.macAddress()
WiFiClient mqttClient;
PubSubClient client(mqttClient);

const int LED_BUILTIN = 4;

void setup_camera() {
      // Turn-off the 'brownout detector'
      WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0);

      // OV2640 camera module
      camera_config_t config;
      config.ledc_channel = LEDC_CHANNEL_0;
      config.ledc_timer = LEDC_TIMER_0;
      config.pin_d0 = Y2_GPIO_NUM;
      config.pin_d1 = Y3_GPIO_NUM;
      config.pin_d2 = Y4_GPIO_NUM;
      config.pin_d3 = Y5_GPIO_NUM;
      config.pin_d4 = Y6_GPIO_NUM;
      config.pin_d5 = Y7_GPIO_NUM;
      config.pin_d6 = Y8_GPIO_NUM;
      config.pin_d7 = Y9_GPIO_NUM;
      config.pin_xclk = XCLK_GPIO_NUM;
      config.pin_pclk = PCLK_GPIO_NUM;
      config.pin_vsync = VSYNC_GPIO_NUM;
      config.pin_href = HREF_GPIO_NUM;
      config.pin_sscb_sda = SIOD_GPIO_NUM;
      config.pin_sscb_scl = SIOC_GPIO_NUM;
      config.pin_pwdn = PWDN_GPIO_NUM;
      config.pin_reset = RESET_GPIO_NUM;
      config.xclk_freq_hz = 20000000;
      config.pixel_format = PIXFORMAT_JPEG;

      if (psramFound()) {
        config.frame_size = resolution_  ;// FRAMESIZE_UXGA;
        config.jpeg_quality = 10;
        config.fb_count = 1;
      } else {
        config.frame_size = FRAMESIZE_SVGA;
        config.jpeg_quality = 12;
        config.fb_count = 2;
      }
      // Camera init
      esp_err_t err = esp_camera_init(&config);
      if (err != ESP_OK) {
        Serial.printf("Camera init failed with error 0x%x", err);
        ESP.restart();
      }
  }

void publishTelemetryFromFile() {
  File file = SPIFFS.open("/b64image.txt", FILE_READ);
  if (!file) {
    Serial.println("There was an error opening the file for read");
    return;
  } else {
    Serial.println(String(file.size())+ "Byte");

  }

  char* data = (char*)heap_caps_malloc(file.size()+1, MALLOC_CAP_8BIT);
  if (data == NULL)
    Serial.println("Can not malloc memory");

  int i=0;

  //while(file.available()){
  for (i=0;i<file.size();i++){
    data[i] = file.read();

  }

  delay(10);

  //client.publish_P( mqtt_TopicName,"qwertyuiopasdfghjkl;zxcvbnm,", true);
  Serial.print( "Published to MQTT " + String(mqtt_server) + " server.." );
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  boolean Status=client.publish_P( mqtt_TopicName, (const uint8_t*)data, file.size(), true);
  Serial.println(String(Status? "Successfully":"Error") );

  free(data);
  file.close();
}

void capturePhoto( void ) {
   // Retrieve camera framebuffer
  camera_fb_t * fb = NULL;
  uint8_t* _jpg_buf = NULL;
  esp_err_t res = ESP_OK;
  size_t frame_size = 0;
  Serial.print("Capturing Image ..");

  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  fb = esp_camera_fb_get();
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
  if (!fb) {
    Serial.println("Camera capture failed");
    res = ESP_FAIL;
  } else {
    Serial.println("Done!");
    Serial.println(String("Size of the image...")+String(fb->len));

    {

      if(fb->format != PIXFORMAT_JPEG){
        Serial.println("Compressing");
        bool jpeg_converted = frame2jpg(fb, 80, &_jpg_buf, &frame_size);
        esp_camera_fb_return(fb);
        fb = NULL;
        if(!jpeg_converted){
          Serial.println("JPEG compression failed");
          res = ESP_FAIL;
        }
      } else {
        frame_size = fb->len;
        _jpg_buf = fb->buf;
        Serial.print("Size of the base64 encoded image...");

        my_base64_encode(_jpg_buf,fb->len,String("Sat Mar 28 11:47:01 EDT 2020") );
        esp_camera_fb_return(fb);
        publishTelemetryFromFile();

      }
    }
  }
  if (res != ESP_OK) {
 //   ESP_LOGW(TAG, "Camera capture failed with error = %d", err);

    return;
  }

 }

void setup_wifi() {
  delay(10);
  // We start by connecting to a WiFi network
  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.println(WiFi.localIP());
}

void reconnect() {
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    if (client.connect("ESP32Client", mqtt_user, mqtt_password)) {
      Serial.println("connected");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}

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

  //byte* psdRamBuffer = (byte*)ps_malloc(500000);
  setup_camera();
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
  setup_wifi();
  client.setServer(mqtt_server, mqtt_port);
   if (!SPIFFS.begin(true)) {
    Serial.println("An Error has occurred while mounting SPIFFS");
    return;
  }
}

// the loop function runs over and over again forever
void loop() {
  Serial.println("PSRAM found: " + String(psramFound()));

  capturePhoto();

  if (!client.connected()) {
    reconnect();
  }

  client.loop();
  delay(SLEEP_DELAY);
}

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

As you can see here, the definition of the return value for esp_camera_fb_get() is
typedef struct {
    uint8_t * buf;              /*!< Pointer to the pixel data */
    size_t len;                 /*!< Length of the buffer in bytes */
    size_t width;               /*!< Width of the buffer in pixels */
    size_t height;              /*!< Height of the buffer in pixels */
    pixformat_t format;         /*!< Format of the pixel data */
} camera_fb_t;

..
camera_fb_t* esp_camera_fb_get();

..

typedef enum {
    PIXFORMAT_RGB565,    // 2BPP/RGB565
    PIXFORMAT_YUV422,    // 2BPP/YUV422
    PIXFORMAT_GRAYSCALE, // 1BPP/GRAYSCALE
    PIXFORMAT_JPEG,      // JPEG/COMPRESSED
    PIXFORMAT_RGB888,    // 3BPP/RGB888
    PIXFORMAT_RAW,       // RAW
    PIXFORMAT_RGB444,    // 3BP2P/RGB444
    PIXFORMAT_RGB555,    // 3BP2P/RGB555
} pixformat_t;

Meaning that fb->buf and bf->len hold the raw data in the format specified by pixformat_t. Aka this is not a "string", these are raw bytes, which you can still base64-encode perfectly fine.
So for the base64 library
    static String encode(const uint8_t * data, size_t length);

it already accepts the right data type and you can do
  fb = esp_camera_fb_get();
  ..
  //will be allocated on the heap. Takes about 4/3 of the input size, so basically it doubles your memory requirements
  String imgDataB64 = base64::encode(fb->buf, fb->len);
  //add to a JSON object wit the metadata width, height and format so that it can be decoded

You should output the fb->format value to check what format the data is, and add this and the width & height information so that the image may be constructted on the other side. Beware high memory requierements since the base64 encoding basically creates a new buffer to store the base64 representation of it. That may be optimized by writing the framebuffer data into an initially bigger buffer which is then transformed in-place. But that would have to be changed at the image driver level.

I have updated question with somewhat working code.

If it is still not working for you try below code it's working for me:

 int image_buf_size = 4000 * 1000;
 uint8_t *image = (uint8_t *)ps_calloc(image_buf_size, sizeof(char));

 size_t length=fb->len;

 size_t olen;

 Serial.print("length is");

 Serial.println(length);
 int err1= mbedtls_base64_encode(image, image_buf_size, &olen, fb->buf, length);

 Serial.println(err1);

 String img((const __FlashStringHelper*) image);

 Serial.println(img);
 //msg1=img;

I got error: 'mbedtls_base64_encode' was not declared in this scope     int err1= mbedtls_base64_encode(image, image_buf_size, &olen, fb->buf, length);

Include base64 C source File and C header source File in you sketch as it is given at link

#include "mbedtls/base64.h"


text:
Publish chipid to mqtt using ESP32-CAM
I have been trying to push the data of temp, humidity, and pressure from a sensor to MQTT using ESP 32Cam, and was able to do using the following code:
pressure = bme.readPressure();

//Convert the value to a char array
char preString[16];
dtostrf(pressure, 1, 2, preString);
Serial.print("Pressure: ");
Serial.println(preString);
client.publish("esp32/pressure", preString);

When I started off with the following code for getting the mac address:
chipid=ESP.getEfuseMac();//The chip ID is essentially its MAC address(length: 6 bytes).
Serial.printf("ESP32 Chip ID = %04X",(uint16_t)(chipid>>32));//print High 2 bytes
Serial.printf("%08X\n",(uint32_t)chipid);//print Low 4bytes.

But when I tried to publish the Chip id, that I was getting on the serial monitor, to the MQTT, an error came up with this:
call of overloaded 'String(uint64_t)' is ambiguous
Here's my code that I tried:
char macValue[16];
String(ESP.getEfuseMac()).toCharArray(macValue,16);
client.publish("esp32/ChipID", macValue);

You would be better off formatting it nicely instead of relying on String...
char macValue[17]; // Don't forget one byte for the terminating NULL...
uint64_t mac = ESP.getEFuseMac();
sprintf(macValue, "%016x", mac);
client.publish("esp32/ChipID", macValue);

However, I'm not certain that sprintf can cope with a 64 bit value like that directly. If not, you can split it:
char macValue[17]; // Don't forget one byte for the terminating NULL...
uint64_t mac = ESP.getEFuseMac();
uint32_t hi = mac >> 32;
uint32_t lo = mac;
sprintf(macValue, "%08x%08x", hi, lo);
client.publish("esp32/ChipID", macValue);

since a MAC address is 6 bytes long, you only need 12 hex digits, so macValue[13] is enough and either %012x or %04%08x as the sprintf format

source: Stack Exchange

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

sort: votes


text:
Making Serial act as an interrupt
I am trying to make a program to control a stepper motor with serial inputs, and in writing a function to jog it, I am having trouble figuring out how to make a serial input stop the loop that steps the motor without making the time per step inconsistent.  Is there a way where I can have a new serial input act like an interrupt and break any loop that's in progress.
void jog() {
  if(input[1] == 0) sd.setDirection(0);
  else sd.setDirection(1);
  while(true){
    if(Serial.available() > 0) break;
    sd.step();
    delayMicroseconds(10);
  }
  sd.setDirection(0);
}

Right now I have this (I'm using a Pololu library that defines the steps), but for some reason this does nothing or at least moves so slow it's imperceptible (a single step only moves the motor 0.007 degrees).  It moves the motor very smoothly if I delete if(Serial.available() > 0) break; but then I can't stop it.
void loop() {
  getData();
  switch(input[0]){
    case 'r':
      Serial.write('r');
      ramp();
      break;
    case 'c':
      Serial.write('c');
      cycle();
      break;
    case 'j':
      //Serial.write('j');
      jog();
      break;
    default:
      break;
  }
}
void getData(){
if(Serial.available() > 0){
  for(int i = 0; i < 200; i ++){
    input[i] = 0;
  }
  for(int i = 0; i < Serial.available(); i++){
    input[i] = Serial.read();
    Serial.print(input[i]);
  }
}
Serial.flush();
//Serial.print(input[0]);
}

This is the relevant code that calls jog()

Please show us a complete working example, that shows your problem, not only one function. Can it be, that there is still data on the Serial buffer, when you enter the jog() function? In that case it would exit directly

It does not have anything in the buffer when it starts.  Post updated with full code.

How do you know, that there is nothing in the Serial buffer, when you enter the jog() function? You don't check for this.
I think your problem is actually in your getData() function. The for loop
for(int i = 0; i < Serial.available(); i++){

might not work as you think, because i increases in every loop iteration while Serial.available() decreases in every iteration. So you actually read less data, than is available on the buffer. For example let's assume, that you have 2 Bytes on the buffer. Serial.available() returns 2. In the first for loop iteration i is 0, while Serial.available() is 2. When you read from the Serial buffer in the iteration, Serial.available() decreases to 1 (since you removed one byte from the buffer by reading it). At the end of the iteration, the for loop will increase i by 1 (due to the i++). Now in the condition of your for loop, you have 1 < 1 (because both i and Serial.available() are 1), thus the for loop will exit without any further iterations. But you still have 1 Byte left in the buffer, that you didn't read.
As I read from the documentation of Serial.flush() (though the documentation is notoriously bad) and from this question, I see, that it will only wait until the output buffer is emptied by the interrupt routines. It does nothing with the input buffer. So you still have data in your RX buffer after this line.
That means, that you really have data in your RX buffer, when you get into the jog() function. Thus it will directly exit without doing any step.

To solve the issue, you should first correct your getData() function to read all the available data from the RX buffer. You can change your for loop like this:
for(int i = 0; Serial.available() > 0 && i < INPUT_BUFFER_SIZE; i++){

This will loop until the RX buffer is empty (when Serial.available() returns 0) or until your input[] array is full (Please add a constant or a define for the input buffer size. Maybe you already have it. You didn't include the full code. But I guess it is 200).
After the for loop, you can empty the buffer by reading from it, until there is nothing left (Please see the linked question for that). You can even do this at the start of your jog() function. This ensures, mostly, that no data is in the buffer at the start of the jog() function (mostly, because the timing of data reception could be, that you receive a byte between the emptying of the RX buffer and the loop. Little probability, but not impossible).
Though - as Nick Gammon states in the linked answer - it is not the best way to empty the RX buffer and use every serial input as interrupt (sometimes you don't have exact control, when exactly the data is received). A better solution is to implement a message protocol, where the end of a full message is marked with a special character. Then you read from serial, until a full message is received (you can even do this non-blocking, so that you can do other things until the message is complete), and only then act upon the message. This would need bigger changes in your code. You would have to rewrite your getData() function and then remove all blocking code from the sketch (for example all delays) and work with non-blocking code instead (for example using the micros() function. The principle is explained in the BlinkWithoutDelay example, that comes with the Arduino IDE (though it uses millis() instead of micros() it is the same principle). You would call the jog() function repeatedly, which would only do a step, if it is time to do one. In the meantime the rest of the code can receive new messages. This makes you more flexible and independent of the exact timing of data reception. Since this would be a big rewrite of your code, you have to decide yourself, if you want to go this way, or stay with the simpler and more imperfect solution.

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


text:
Issue connecting heartbeat & temperature sensor on arduino uno but working individually
So the code is working individually for temperature sensor and for heartbeat sensor but  when i combine it together it shows wrong values
for the temperature sensor
I'm using lm35 temperature sensor and powering by USB
#include <LiquidCrystal.h>

const int rs = 13, en = 12, d4 = 11, d5 = 10, d6 = 9, d7 = 8;
LiquidCrystal lcd(13, 12, 11, 10, 9, 8);

int pulsePin = A0;

int blinkPin = 5;                // pin to blink led at each beat

// Volatile Variables, used in the interrupt service routine!
volatile int BPM ;                   // int that holds raw Analog in 0. updated every 2mS
volatile int Signal;                // holds the incoming raw data
volatile int IBI = 600;             // int that holds the time interval between beats! Must be seeded!
volatile boolean Pulse = false;     // "True" when User's live heartbeat is detected. "False" when not a "live beat".
volatile boolean QS = false;        // becomes true when Arduoino finds a beat.

static boolean serialVisual = true;   // Set to 'false' by Default.  Re-set to 'true' to see Arduino Serial Monitor ASCII Visual Pulse

volatile int rate[10];                      // array to hold last ten IBI values
volatile unsigned long sampleCounter = 0;          // used to determine pulse timing
volatile unsigned long lastBeatTime = 0;           // used to find IBI
volatile int P = 512;                      // used to find peak in pulse wave, seeded
volatile int T = 512;                     // used to find trough in pulse wave, seeded
volatile int thresh = 525;                // used to find instant moment of heart beat, seeded
volatile int amp = 100;                   // used to hold amplitude of pulse waveform, seeded
volatile boolean firstBeat = true;        // used to seed rate array so we startup with reasonable BPM
volatile boolean secondBeat = false;      // used to seed rate array so we startup with reasonable BPM

const int sensor = A5;
int tempc ;
float vout;

void setup()
{
  vout =analogRead(sensor);
  pinMode(sensor,INPUT);
  pinMode(blinkPin,OUTPUT);         // pin that will blink to your heartbeat!
  Serial.begin(9600);             // we agree to talk fast!
  interruptSetup();                 // sets up to read Pulse Sensor signal every 2mS
                                  // IF YOU ARE POWERING The Pulse Sensor AT VOLTAGE LESS THAN THE BOARD VOLTAGE,
                                    // UN-COMMENT THE NEXT LINE AND APPLY THAT VOLTAGE TO THE A-REF PIN
                                    //   analogReference(EXTERNAL);
 lcd.begin(16, 4);
 lcd.clear();
}

//  Where the Magic Happens
void loop()
{

lcd.setCursor(0,0);
lcd.print(" T in c = ");
lcd.print(tempc);
lcd.setCursor(0,1);

delay(100);
   serialOutput();

  if (QS == true) // A Heartbeat Was Found
    {
      // BPM and IBI have been Determined
      // Quantified Self "QS" true when arduino finds a heartbeat
      serialOutputWhenBeatHappens(); // A Beat Happened, Output that to serial.
      QS = false; // reset the Quantified Self flag for next time
      tempc=(vout*500)/1023;

    }

  delay(20); //  take a break
}

void interruptSetup()
{
  // Initializes Timer2 to throw an interrupt every 2mS.
  TCCR2A = 0x02;     // DISABLE PWM ON DIGITAL PINS 3 AND 11, AND GO INTO CTC MODE
  TCCR2B = 0x06;     // DON'T FORCE COMPARE, 256 PRESCALER
  OCR2A = 0X7C;      // SET THE TOP OF THE COUNT TO 124 FOR 500Hz SAMPLE RATE
  TIMSK2 = 0x02;     // ENABLE INTERRUPT ON MATCH BETWEEN TIMER2 AND OCR2A
  sei();             // MAKE SURE GLOBAL INTERRUPTS ARE ENABLED
}

void serialOutput()
{   // Decide How To Output Serial.
 if (serialVisual == true)
  {
     arduinoSerialMonitorVisual('-', Signal);   // goes to function that makes Serial Monitor Visualizer
  }
 else
  {
      sendDataToSerial('S', Signal);     // goes to sendDataToSerial function
   }
}

void serialOutputWhenBeatHappens()
{
 if (serialVisual == true) //  Code to Make the Serial Monitor Visualizer Work
   {

     int din ;
      din = analogRead(4);

     Serial.print(BPM);
     Serial.print(", ");
     Serial.print(tempc);
     Serial.print(", ");
     Serial.print(din);
     Serial.print(", ");

     Serial.println();
     lcd.setCursor(0,2);
     lcd.print("Heart-Beat Found ");
     lcd.setCursor(6,3);
     lcd.print(BPM);
     delay(100);
     lcd.clear();
   }
 else
   {
     sendDataToSerial('B',BPM);   // send heart rate with a 'B' prefix
     sendDataToSerial('Q',IBI);   // send time between beats with a 'Q' prefix
   }
}

void arduinoSerialMonitorVisual(char symbol, int data )
{
  const int sensorMin = 0;      // sensor minimum, discovered through experiment
  const int sensorMax = 1024;    // sensor maximum, discovered through experiment
  int sensorReading = data; // map the sensor range to a range of 12 options:
  int range = map(sensorReading, sensorMin, sensorMax, 0, 11);
  // do something different depending on the
  // range value:
}

void sendDataToSerial(char symbol, int data )
{
   Serial.print(symbol);
   Serial.println(data);
}

ISR(TIMER2_COMPA_vect) //triggered when Timer2 counts to 124
{
  cli();                                      // disable interrupts while we do this
  Signal = analogRead(pulsePin);              // read the Pulse Sensor
  sampleCounter += 2;                         // keep track of the time in mS with this variable
  int N = sampleCounter - lastBeatTime;       // monitor the time since the last beat to avoid noise
                                              //  find the peak and trough of the pulse wave
  if(Signal < thresh && N > (IBI/5)*3) // avoid dichrotic noise by waiting 3/5 of last IBI
    {
      if (Signal < T) // T is the trough
      {
        T = Signal; // keep track of lowest point in pulse wave
      }
    }

  if(Signal > thresh && Signal > P)
    {          // thresh condition helps avoid noise
      P = Signal;                             // P is the peak
    }                                        // keep track of highest point in pulse wave

  //  NOW IT'S TIME TO LOOK FOR THE HEART BEAT
  // signal surges up in value every time there is a pulse
  if (N > 250)
  {                                   // avoid high frequency noise
    if ( (Signal > thresh) && (Pulse == false) && (N > (IBI/5)*3) )
      {
        Pulse = true;                               // set the Pulse flag when we think there is a pulse
        digitalWrite(blinkPin,HIGH);                // turn on pin 13 LED
        IBI = sampleCounter - lastBeatTime;         // measure time between beats in mS
        lastBeatTime = sampleCounter;               // keep track of time for next pulse

        if(secondBeat)
        {                        // if this is the second beat, if secondBeat == TRUE
          secondBeat = false;                  // clear secondBeat flag
          for(int i=0; i<=9; i++) // seed the running total to get a realisitic BPM at startup
          {
            rate[i] = IBI;
          }
        }

        if(firstBeat) // if it's the first time we found a beat, if firstBeat == TRUE
        {
          firstBeat = false;                   // clear firstBeat flag
          secondBeat = true;                   // set the second beat flag
          sei();                               // enable interrupts again
          return;                              // IBI value is unreliable so discard it
        }
      // keep a running total of the last 10 IBI values
      word runningTotal = 0;                  // clear the runningTotal variable

      for(int i=0; i<=8; i++)
        {                // shift data in the rate array
          rate[i] = rate[i+1];                  // and drop the oldest IBI value
          runningTotal += rate[i];              // add up the 9 oldest IBI values
        }

      rate[9] = IBI;                          // add the latest IBI to the rate array
      runningTotal += rate[9];                // add the latest IBI to runningTotal
      runningTotal /= 10;                     // average the last 10 IBI values
      BPM = 60000/runningTotal;               // how many beats can fit into a minute? that's BPM!
      QS = true;                              // set Quantified Self flag
      // QS FLAG IS NOT CLEARED INSIDE THIS ISR
    }
  }

  if (Signal < thresh && Pulse == true)
    {   // when the values are going down, the beat is over
      digitalWrite(blinkPin,LOW);            // turn off pin 13 LED
      Pulse = false;                         // reset the Pulse flag so we can do it again
      amp = P - T;                           // get amplitude of the pulse wave
      thresh = amp/2 + T;                    // set thresh at 50% of the amplitude
      P = thresh;                            // reset these for next time
      T = thresh;
    }

  if (N > 2500)
    {                           // if 2.5 seconds go by without a beat
      thresh = 512;                          // set thresh default
      P = 512;                               // set P default
      T = 512;                               // set T default
      lastBeatTime = sampleCounter;          // bring the lastBeatTime up to date
      firstBeat = true;                      // set these to avoid noise
      secondBeat = false;                    // when we get the heartbeat back
    }
  sei();
                                 // enable interrupts when youre done!
}// end isr

Code seems to lack a repeating update of tempc via
vout =analogRead(sensor);

An alternative might be changing the line for setting tempc to be
tempc=(int) (analogRead(sensor) * 500.0f/1023.0f);

thanks for your answer, I'm still a newbie can you please explain more?

Add that vout = line between QS = false; and tempc = and let me know if issue still persists.  Basically you have to update vout before you calculate tempc from it.  analogRead is a one shot read on the pin.

Thanks, I'll try and keep you updated

sorry for the late response,I've tried your suggestions but unfortunately I didn't get any result.I think the problem is due to the interrupts()  or timer2 instructions because when I add cli() (disable interrupt) before vout=analogRead(sensor); the temperature give me the right value  but the pulse sensor stop working . thats what I'm getting currently https://www.youtube.com/watch?v=dBPKmYd08U8 thanks

If the provided source is cut down to the lines that have to do with the temperature, it is just this. If you try this sketch it should behave equally "wrong":
const int sensor = A5;
int tempc;
float vout;

void setup()
{
    vout = analogRead(sensor);
    pinMode(sensor, INPUT);
}

void loop()
{
    lcd.print(tempc);
    tempc = (vout * 500) / 1023;
}

In loop() the value of tempc is printed before it is re-calculated from vout.
But vout is written to just one time in setup().
So the "wrong" values you are talking about are always the same value which was measured at start-up time. (You did not mention what is wrong.)

Note: Like documented in the Arduino's library reference, there is no need to set a pin to INPUT mode because it's the default.

I read your comment on @Abel's answer and even watched your video. Since it's not clear what you did I can't say anything why you have jumping values now. (Please write some prose and show the new code in your question the next time.)
If we apply his advice the source will look like this. I removed the setting of the pin mode (see above) and made the sequence of instructions in loop() more logical.
const int sensor = A5;
int tempc;
float vout;

void setup()
{
}

void loop()
{
    vout = analogRead(sensor);
    tempc = (vout * 500) / 1023;
    lcd.print(tempc);
}

This sketch will show the current temperature tracking the actual value. If not you have another problem independent of the interrupt and the heartbeat sensor.

Additional notes:

analogRead() returns an int. You assign it to a float so here is an implicit conversion.
This float is fine because you do the mapping "by hand." If you'd use map() it could be an int.
The result of the mapping expression is of type float and you assign it to an int. Here is another implicit conversion which removes the fractional part. This is OK because of the accuracy of the measurement.

Now to your assumption that the interrupts disturb the measurement of the temperature.
From the source I don't see any reason. So you might like to proceed like this:

Comment everything that has to do with the heartbeat acquisition, including the timer interrupt. You can do this with /* … */ or #if 0-#endif-pairs. The former can't be "stacked" and the latter need their own lines.
Check whether the temperature is tracked OK.

If yes, proceed.
If no, your temperature circuitry is faulty in some way. A schematic and a photo (edit your question for this) could be helpful for us. Don't proceed until this is solved.

The timer and its interrupt service routine is actived again but will execute nothing.
Check whether the temperature is OK.

If yes, proceed.
If no, I'm out of ideas for the moment.

Re-enable the heartbeat acquisition.
Check whether the temperature is OK.

If yes, proceed.
If no, I'm out of ideas for the moment.

Problem solved.

Why do you compute tempc only after you print out the value in serialOutputWhenBeatHappens`? You also forgot to read the temperature continuously.
Here is how I would do it:
void loop()
{
  // read the sensor before it is printed on the LCD
  vout  = analogRead( sensor );

  // here I'm not sure what you are computing
  // you map the sensor voltage to a range from 0°C to 500°C
  // do you measure the heartbeat and temperature of a dragon? ;-)
  // this formula is the same as yours
  tempc = ( vout / 1023.0 ) * 500.0;

  // I would also clear the LCD before I write to it
  lcd.clear();

  lcd.setCursor( 0, 0 );
  lcd.print( "T in c = " );
  lcd.print( tempc );
  lcd.setCursor( 0,1 );

  // There is no need to slow down the loop here.
  // let it run ...
  // delay(100);

  serialOutput();

  // A Heartbeat Was Found
  if (QS == true)
  {
     // BPM and IBI have been Determined
     // Quantified Self "QS" true when arduino finds a heartbeat
     // A Beat Happened, Output that to serial.
     serialOutputWhenBeatHappens();

     // reset the Quantified Self flag for next time
     QS = false;
  }

  // take a break (Why?)
  // delay(20);
}


text:
How do I download a sketch to an Arduino semi-permanently?
I will be working with Arduino(s), and I would like to find a way to download the sketches to the board semi permanently, in a way that I can remove the USB from the board, apply power, and still have the Arduino execute the code
I am planning to use Mega2960, Uno, and Nano. If there are any differences between the uploading process,
please let me know.
P.S., I am using boards produced by Elegoo, not by Arduino, if that makes a difference.

But... that is basically what happens when you press the "upload" button... it programs your compiled code into the board.

When I unplugged the Mega, it stopped functioning, although it still had power from a 9v battery. I also tried hitting the reset button.

Then you either have something in your code or circuit that is broken.

Oh well... I currently don’t have access to the code currently, as the Mega was at a Robotics Club that I visit.

@Nutmeg, your post is what is called an XY problem ... you asked for help with what you think is a solution to an observed problem, instead of asking for help with the actual observed problem

@jsotola, what caused it to be an XY problem?

as i said, you did not ask for help with the problem that you observed (Mega stopped functioning) ... you asked about making the sketch semi-permanent (misguided solution to the problem)

A 9V block battery should never be used with an Arduino board. It is only meant for low power applications and cannot provide enough current. So I guess the code stops working, because the Mega does not have enough power and browns out

Oh, ok. The kit I was using from Elegoo just came with the kit.

Download the Arduino software (IDE, or Integrated Development Environment).

In our case, we only need to download and run Windows Installer and follow the pop up instructions.  When asked if you want to install the Arduino driver, just press Yes.

Connect your Arduino Nano board to your computer.

In this step, Windows should automatically find the proper Arduino driver and install it, and your Nano board should be ready to use.  If not, please refer to the above mentioned instruction for details on installing the drivers.  Some compatible Nano boards such as DCCduino manufactured by a Chinese company use different USB-to-Serial chips so they require to install different drivers, but the installation should be quite straight forward once you have downloaded the proper drivers from internet.

Launch the Arduino application.
Open the blink example.

Open the LED blink example sketch: File > Examples > 01.Basics > Blink.
For those who are not familiar with Arduino sketch, a sketch is simply a program with various instructions telling Arduino board what to do.

Select your board.

You’ll need to select what type of Arduino board you are using.  In our case, simply select Tools > Board > Arduino Nano w/Atmega328.

Select your serial port

You also need to select the serial device of the Arduino board: Tools > Serial Port.  Usually the port number will be COM3 or higher (COM1 and COM2 are usually reserved for hardware serial ports). To find out, you can disconnect your Arduino board and re-open the menu; the entry that disappears should be the Arduino board. Reconnect the board and select that serial port.

Upload the program to Nano board

Now, simply click the “Upload” button in the environment. Wait a few seconds – you should see the RX and TX leds on the board flashing. If the upload is successful, the message “Done uploading.” will appear in the status bar.
A few seconds after the upload finishes, you should see the pin 13 (L) LED on the board start to blink (in orange). If it does, congratulations! You’ve gotten Arduino up-and-running.
Disconnect from your computer and connect to a power supply to see the blinking light.


text:
Make a Jack-Bluetooth Module for the car
I'm making a Jack-Bluetooth module so that I can send music to the car (or other devices w/ Jack plug) without an internal Bluetooth module in the car.
https://habr.com/en/post/456182/ says that I need around 44 kHz of sampling frequency to get high quality sound. Is there a BT module on the market w/ these specs?
Audio Recording using Arduino BT module says that the HC-05 HC-06 HC-07 are not good enough.
If there are no such cases, I think I should consider buying an Arduino that has an built-in BT/WiFi module or I can buy such a BT transmitter but beats the fun.

Just buy a small bluetooth audio receiver. There's fun, there's torture, and then there's trying to make your own bluetooth audio receiver. It's just not worth the effort, even if you enjoy torture.

There is no way you will do it with a bluetooth "module" to an Arduino. You need: * A arduino with builtin bluetooth. * An Arduino with an I2S interface and high quality CODEC. * A lot of skill in programming and an in-depth knowledge of Bluetooth audio protocols.


text:
Random analog input
I'm trying to build a midi controller that takes the input from a photoresistor and a reed switch anemometer and outputs midi signal.
I've constructed the circuit as in the diagram below but when I test the inputs I receive only random numbers from analog input 3. I get a clear signal on A5.
I'm confused as to what's going on. I've seen other solutions to this problem mention the circuit not being grounded properly but as far as I can see I have the correct grounding.

220Ω is incredibly small for your inputs. 10K is better. Especially for the LDR.

Could you post a picture of your setup? The schematic looks fine, so there might be an error in your wiring, maybe.

Often problems are code, hardware or both. Can you please post your code? (Edit your question to do that. Indent it with Ctrl+K so it looks nice).

Thanks for the input guys. Originally I was finding that my circuit, which i had soldered myself, was not working. I rebuilt it on a bread board and it is working fine now, must have been an issue with my soldering!

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


text:
problem using GSM shield and GPS shield in one Arduino UNO R3
i try to program use the GSM shield Arduino with Arduino UNO i did it successfully but after that i try to use GPS shield but when i add the #include  for the program i got the error
#include <GSM.h>
#include <TinyGPS.h>
#include <SoftwareSerial.h> // when i add that one i got the output eroor
// PIN Number for the SIM
#define PINNUMBER ""

i got this error out put
Arduino: 1.6.6 (Mac OS X), Board: "Arduino/Genuino Uno"

libraries/SoftwareSerial/SoftwareSerial.cpp.o: In function `__vector_3':
/Applications/Arduino.app/Contents/Java/hardware/arduino/avr/libraries/SoftwareSerial/SoftwareSerial.cpp:227: multiple definition of `__vector_3'
libraries/GSM/GSM3SoftSerial.cpp.o:/Applications/Arduino.app/Contents/Java/libraries/GSM/src/GSM3SoftSerial.cpp:499: first defined here
libraries/SoftwareSerial/SoftwareSerial.cpp.o: In function `SoftwareSerial::read()':
/Applications/Arduino.app/Contents/Java/hardware/arduino/avr/libraries/SoftwareSerial/SoftwareSerial.cpp:392: multiple definition of `__vector_4'
libraries/GSM/GSM3SoftSerial.cpp.o:/Applications/Arduino.app/Contents/Java/libraries/GSM/src/GSM3SoftSerial.cpp:487: first defined here
libraries/SoftwareSerial/SoftwareSerial.cpp.o: In function `SoftwareSerial::read()':
/Applications/Arduino.app/Contents/Java/hardware/arduino/avr/libraries/SoftwareSerial/SoftwareSerial.cpp:392: multiple definition of `__vector_5'
libraries/GSM/GSM3SoftSerial.cpp.o:/Applications/Arduino.app/Contents/Java/libraries/GSM/src/GSM3SoftSerial.cpp:487: first defined here
collect2: error: ld returned 1 exit status
exit status 1
Error compiling.

  This report would have more information with
  "Show verbose output during compilation"
  enabled in File > Preferences.

It appears the GSM library has its own conflicting copy of SoftwareSerial, and not necessarily a matching version unless you're lucky.
Not sure how well this would work but you can try removing the library reference to SoftwareSerial, and fiddle about to use the GSM library's SoftwareSerial.

Indeed, if both peripherals are serially connected, the "only one instance" restriction of the software serial library may be a problem.  Alternate libraries could be considered, but most likely an ATmega-based Arduino is not the best platform.   A GSM module with integrated GSM could be another choice.

True that; my solution almost definitely won't result in 2 separate serial streams, which are likely needed.  This page may be of interest (alternate libraries) http://www.ernstc.dk/arduino/tinycom.html

thanks , i used SerialGSM.h instead the GSM library i can receive message but when i send the message not send it :(

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


text:
Corrupted characters with an OLED displaying thermocouple output
I'm super new to Arduinos but I'm learning as I go. I'm in the first stages of a small temperature control project and so far I've been able to display the output of a MAX31855 thermocouple breakout board on 124x64 spi OLED through my Arduino micro.
My problem is that the characters of the temperature are corrupted looking. As I think I understand it, the temperature is changing while it's being written to the display therefore you get overlapping values. I've attached an image of the display.
I've tried making the temp output an integer but that didn't work.
Any input would be greatly appreciated as I'm just banging my head against the wall.
Here's my code:
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_MAX31855.h>
#include <U8glib.h>

//Constructor line for OLED

U8GLIB_SH1106_128X64 u8g(13, 11, 10, 9, 8);  // D0=13, D1=11, CS=10, DC=9, Reset=8

// Default connection is using software SPI, but comment and uncomment one of
// the two examples below to switch between software SPI and hardware SPI:

// Example creating a thermocouple instance with software SPI on any three
// digital IO pins.
#define MAXDO   3
#define MAXCS   4
#define MAXCLK  5

// initialize the Thermocouple
Adafruit_MAX31855 thermocouple(MAXCLK, MAXCS, MAXDO);

// Example creating a thermocouple instance with hardware SPI
// on a given CS pin.
//#define MAXCS   10
//Adafruit_MAX31855 thermocouple(MAXCS);

void draw() {
  double c = thermocouple.readCelsius();
  u8g.setFont(u8g_font_profont29);  // select font
  u8g.setPrintPos(5, 45);  // set position
  u8g.print(c);  // display temperature from MAX31855

}

void setup(void) {

}

void loop() {

  // picture loop
  u8g.firstPage();
  do {

    draw();
  } while (u8g.nextPage());

  // rebuild the picture after some delay
  delay(5000);
}

The U8G2 library saves RAM by drawing the screen in smaller chunks (i.e., a "page").  Because you are taking a reading for each chunk, the temperature can change.  Just pull the reading out of draw and do it once in loop:
double c; // a global variable used in draw and loop

void draw() {
  u8g.setFont(u8g_font_profont29);  // select font
  u8g.setPrintPos(5, 45);  // set position
  u8g.print(c);  // display temperature from MAX31855

}

void loop() {

  c = thermocouple.readCelsius(); // set the global variable once

  // picture loop
  u8g.firstPage();
  do {
    draw();
  } while (u8g.nextPage());

  // rebuild the picture after some delay
  delay(5000);
}

BOOM! Worked like a charm. Much appreciated.


text:
Code for ST7789 NO CS pin - Using XIAO ESP32C3
I am trying to get anything out of this screen except for blackness. The CS pin is present based on the coupling or resistors and capacitors on the back of the display.
I have tried using the Arduino ST7789 fast library, but I am wondering if anyone has gotten that to work in recent times. I first get an error saying no such library for avr/pgmspace. I found a fix to that issue by adding:
 #if (defined(__AVR__))
 #include <avr\pgmspace.h>
 #else
 #include <pgmspace.h>
 #endif

but then I move right to another error saying:
In member function 'void Arduino_ST7789::commonST7789Init(const uint8_t*)':
Arduino15/packages/esp32/hardware/esp32/2.0.11/cores/esp32/Arduino.h:114:70: error: cannot convert 'volatile uint32_t*' {aka 'volatile long unsigned int*'} to 'volatile uint8_t*' {aka 'volatile unsigned char*'} in assignment
 #define portOutputRegister(port)    ((volatile uint32_t*)GPIO_OUT_REG)

I have found nobody else with this issue.
Here is my pinout:

Esp32c3
St7789

GPIO 2
DC

GPIO 3
RES

GPIO 6
SDA

GPIO 7
SCL

3v3
Vcc/Lite

Here is the screen in question and
here is the microcontroller in question
I have also used the normal ST7789 library and substituted -1 for the CS pin, but still black on my display. If anyone can provide any raw code to get this to work or just let me know where to begin on trying new code please let me know.

The library is optimised for AVR chip using some AVR register and assembly code, it is therefore not compatible with ESP32 in the default mode. Add #define COMPATIBILITY_MODE to the first line of your code (before any #include <file> macro to see if it is working. If not, use other library such Adafruit ST7789 library.

I had a blank screen with 1.3 240x240 display (non-CS type) on XIAO BLE.  Solved the problem by ungrounding the CS trace, then running a wire to a defined CS pin on the XIAO.


text:
I am trying to connect the PS3 controller with the Arduino Uno using a USB Host Shield. Getting stuck at 'PS3 Bluetooth Library Started'
I did the research for similar issues and found that I had to enable debug. I did the following attempts:
Changes to settings.h - enabled debugging by change from 0 to 1
Getting the following compiling error:
/Users/BAGHEL/Documents/Arduino/libraries/USB_Host_Shield_2.0-master/usbh_midi.cpp: In member function 'void USBH_MIDI::parseConfigDescr(byte, byte)':
/Users/BAGHEL/Documents/Arduino/libraries/USB_Host_Shield_2.0-master/usbh_midi.cpp:298:63: error: 'PrintEndpointDescriptor' was not declared in this scope
                                 PrintEndpointDescriptor(epDesc);
                                                               ^
/Users/BAGHEL/Documents/Arduino/libraries/USB_Host_Shield_2.0-master/usbh_midi.cpp: At global scope:
/Users/BAGHEL/Documents/Arduino/libraries/USB_Host_Shield_2.0-master/usbh_midi.cpp:421:80: error: no 'void USBH_MIDI::PrintEndpointDescriptor(const USB_ENDPOINT_DESCRIPTOR*)' member function declared in class 'USBH_MIDI'
 void USBH_MIDI::PrintEndpointDescriptor( const USB_ENDPOINT_DESCRIPTOR* ep_ptr )
                                                                                ^
exit status 1
Error compiling for board Arduino/Genuino Uno.

At the risk of stating the bleeding obvious you need to define "PrintEndpointDescriptor()".  I'm sorry but I can't give you a definitive answer to your problem, only generic steps that should solve it.
This almost certainly means you have either missed a include file out or there is a pre-processor flag that is disabling or maybe not enabling that bit of code.
Search through the files in the library and see if there are any pre-processor flags that affect compilation and if so this function.  Have a search on Google for the filename and function name, see that others say.
Another possible solution is look for a readme in the library, or comments in the files that say you need another library including first.  In fact if you are including multiple libraries try changing the order of inclusion.
One last cause could be that the function is within a namespace.  This means you either need to fully qualify the function call (namespace::class::function), or use the horrible using command.


text:
ATTiny85 I2C LCD
My setup is as follows:

Arduino IDE 1.6.11
Arduino Pro Mini as ISP
ATTiny85 1602A LCD with I2C board

The libraries I use are:

TinyWireM (source: https://github.com/adafruit/TinyWireM)
LiquidCrystal_I2C (modified for ATTiny) (source: http://playground.arduino.cc/Code/USIi2c)

The Sketch I use to test with:
#include <TinyWireM.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x3F,16,2);  // set address & 16 chars / 2 lines

void setup()
{

  TinyWireM.begin();                    // initialize I2C lib
  lcd.init();                           // initialize the lcd
  lcd.backlight();
  lcd.clear();  // Print a message to the LCD.
}

void loop()
{
  lcd.setCursor(0, 0);
  lcd.print("Hello World on Attiny85");
  delay(2000);
}

The address is 0x3F, I found this using the scanner sketch, I also tested the LCD using the Arduino Pro Mini directly, it works fine.
The result of this setup is a single line of black blocks. My guess is that the initialization failed in some way. I have tried some things to make it work:

Pull-ups on SDA and SCL
Isolated from Arduino with regulated power supply
Setting contract with the pot meter on the back
reinstall of PC
reinstall of Arduino IDE
1MHz, 8Mhz, TinyCore default and High-Low Tech
Replaced FTDI
Replaced Tiny85
Replaced LCD
Replaced Arduino Pro Mini

Some pictures:

[EDIT]
Final sketch:
#include <TinyWireM.h>                  // I2C Master lib for ATTinys which use USI
// #include <LiquidCrystal_I2C.h>
#include "LiquidCrystal_attiny.h"
LiquidCrystal_I2C lcd(0x27,16,2);

void setup() {

  // Now set up the LCD
  //lcd.begin(16,2);               // initialize the lcd
  pinMode(4, OUTPUT);
  lcd.init();
  lcd.backlight();
  lcd.home ();                   // go home
  lcd.print("Weatherstation");
  lcd.setCursor ( 0, 1 ); // go to position
  lcd.print("BMP180");
  delay(2000);
}
void loop() {
  digitalWrite(4, HIGH);
  delay(100);
  digitalWrite(4, LOW);
  delay(100);
}

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

It looks like you did not connect the SCL line.....
Make sure you're using the correct pins! they default to pin0 for SDA and pin2 for SCL.

Please post further comments in the chat room above. Comments posted here are likely to be deleted.

Just a question, why do you want to use and ATtiny when you can just program any I2C with your Arduino??? P.S. Just trying to learn so no hate for this question please.

no problem, I will skip my usual hate-reply :) Nick may hate-reply for not using the chat box though, haha. I choose the ATTiny over the Arduino because my project will sleep a lot and use a battery 3.7V power source. ATTiny will run for weeks/months vs Arduino for days.

wasted too much time on these devices, trying to get them working, use an earlier ide, caps, pullups, reinstall usb drivers, modified libs yada yada yada.
don't waste your life on these attiny's, use 328Ps with bootloader pre installed for your pcbs.

these days maybe a Pi Pico W running Micropython is the best bang for the buck, if the high power consumption is not an issue

After hours of Googling, I found a blog post by Dimitris Platis where he describes using an ATTiny85 with I2C LCD. I emailed the guy and he replied with a link to his LCD I2C ATTiny library on GitHub. Using this library with the TinyWireM and the right core, it instantly worked.
My final setup is with a 4.7K resistor on SDA and SCL, I will add the final sketch in the original post under [EDIT]. This adventure took me two weeks so I hope it helps someone else some day.
LCD library used: https://github.com/platisd/ATtiny85-LCD-library
TinyWireM used: https://github.com/adafruit/TinyWireM
Core used: https://github.com/vprimachenko/ArduinoTiny

I've spent an hour doing this problem and searched a lot. If you still didn't find the solution by doing this. Pls try to reduce the clock speed from Internal 8 MHz to Internal 1MHz. That way it works mine.

authors: สมพล กริ่งกรับ


text:
Calculating with millis()
The following code works fine until I turn the if (tijd - action >= 500) into if (tijd - action >= 1000)
I wonder why this fails.
If I just loop and print the tijd - action it has no problem with it and runs well beyond 1000.
The Logic Analyzer on the software serial only returns '255' when it fails, I also wonder what that means.
The core I use is this one
The chip I use is an ATtiny85
I run this using the Arduino IDE 1.8.2
[update]
with "start"
Sketch uses 3070 bytes (37%) of program storage space. Maximum is 8192 bytes.
Global variables use 146 bytes (28%) of dynamic memory, leaving 366 bytes for local variables. Maximum is 512 bytes.

with "starting"
Sketch uses 3072 bytes (37%) of program storage space. Maximum is 8192 bytes.
Global variables use 148 bytes (28%) of dynamic memory, leaving 364 bytes for local variables. Maximum is 512 bytes.

script
#include <SoftwareSerial.h>
#include <avr/sleep.h>
#include <avr/wdt.h>

#define TX_PIN 4
#define RX_PIN -1

#ifndef cbi
  #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
  #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

SoftwareSerial mySerial(RX_PIN, TX_PIN);

unsigned long tijd;
unsigned long action = 0;

volatile boolean f_wdt = 1;
ISR(WDT_vect) {
  f_wdt=1;
}

void system_sleep() {
  cbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter OFF

  set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here
  sleep_enable();

  sleep_mode();                        // System sleeps here

  sleep_disable();                     // System continues execution here when watchdog timed out
  sbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter ON
}

void setup_watchdog(int ii) {
  byte bb;
  int ww;
  if (ii > 9 ) ii=9;
  bb=ii & 7;
  if (ii > 7) bb|= (1<<5);
  bb|= (1<<WDCE);
  ww=bb;

  MCUSR &= ~(1<<WDRF);
  // start timed sequence
  WDTCR |= (1<<WDCE) | (1<<WDE);
  // set new watchdog timeout value
  WDTCR = bb;
  WDTCR |= _BV(WDIE);
}

void setup() {
  mySerial.begin(2400);
  mySerial.print("Starting..");
  setup_watchdog(8);
  pinMode(0, OUTPUT);
}

int zie = 0;

void loop() {
  if (f_wdt==1) {
    digitalWrite(0, HIGH);
    tijd = millis();
    mySerial.print(".");
    mySerial.print(tijd - action);
    zie+=1;
    if (tijd - action >= 500) { // fails when set to 1000
      digitalWrite(0, LOW);
      action = tijd;
      mySerial.print("z");
      mySerial.print(zie);
      mySerial.print(".");
      system_sleep();
    }
  }
}

Which ATtiny are you using?

the ATtiny85 is what I use

You mean printing millis() before comparison right, because tijd is fixed at the start..

It looks like there is nothing wrong with your code, which means its not easy to see.  Is it possible to reduce the problem just to its bare essentials and have a loop that prints something every second?

To get to the comparison it takes ~24ms. I expect the Watchdog Timer to interfere with this code, that is why it's not a clear small sample.

@Thijs - Sorry I didn't mean "you need a minimal repeatable example", I meant is it possible to reproduce the problem with just the simple loop, no watchdog, etc.  Unless you think its the watchdog causing this issue.

Does the watch dog reset millis()?  Does the watch dog re-initialise the variables, i.e. action?  I suspect yes, no.  So is it possible action = 500 and (tijd - action)  = 500 and it doesn't run long enough for millis to go past 1499?

You will not be believe this; if I change the string "Starting.." to "Start" it will run fine! This probably has something to do with filling up the RAM of the Tiny, right?

if I change the string "Starting.." to "Start" it will run fine! This probably has something to do with filling up the RAM of the Tiny, right?

That symptom does suggest RAM overflow, in spite of the relatively low RAM use (28%) reported during compilation.
To reduce memory use slightly more, you can move the string "Starting.." to PROGMEM by changing from line 1 below to line 2.
  mySerial.print("Starting..");     // line 1
  mySerial.print(F("Starting.."));  // line 2

To save another handful of RAM bytes, change lines like mySerial.print("."); and mySerial.print("z"); to mySerial.print('.'); and mySerial.print('z');.  That is, you are printing single-character strings; each string has a null terminating byte; instead just print single characters.
References and discussion of the F() macro include 1, 2, 3, 4, 5 and also see  How do I squeeze code to fit onto an ATTiny.  Also, there are some really compact software serial libraries targeted for ATtinies, which may save hundreds of bytes of flash and dozens of bytes of RAM.

I'm not going to disagree but I'd be interested to understand why its happening at such a low threshold.  (unless the values reported are [rubbish])

Adding the F already does the trick. I would like to know why this is a solution. I still have a library to add to this code, I will probably run into the same trouble again..

@CodeGorilla, that I don't know, which is why I say  “does suggest RAM overflow” instead of proving it.  I've seen somewhat larger ATtiny85 programs, and don't know what's wrong here.  Answers to  How do I squeeze code to fit onto an ATTiny might suggest an approach

@Thijs, I added some F() links, but as noted I don't know what's wrong.  Perhaps read the assembly code looking for surprises.


text:
HC06 correct baud rate but missing characters/ no AT commands
I have an issue with the communication between my Serial Monitor and my BT HC06 Module. Iam able to send ascii characters from my phone with BT connection to my local serial monitor. When i send characters from my local serial monitor to my BT module i receive something like this: AT -> U or 3 -> 3
I have this issue since i changed the baud from 9600,0,0 to 9600,0,1
Code:
#include <SoftwareSerial.h>

SoftwareSerial BTSerial(10, 11); // RX | TX

void setup()
{
  pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
  digitalWrite(9, HIGH);
  Serial.begin(9600);
  Serial.println("Enter AT commands:");
  BTSerial.begin(9600);  // HC-05 default speed in AT command more
}

void loop()
{

  // Keep reading from HC-05 and send to Arduino Serial Monitor
  if (BTSerial.available())
    Serial.write(BTSerial.read());

  // Keep reading from Arduino Serial Monitor and send to HC-05
  if (Serial.available())
    BTSerial.write(Serial.read());
}

Sorry, my question was not easy to understand. Your solution had not worked for me.
I found another libary where its possible to add the parity bit:
https://github.com/ledongthuc/CustomSoftwareSerial
This works fine for me.
Thanks for your help :)

If I understand you right: You changed the UART settings on the HC05 module and now you are unable to connect to the HC-06.
You use SoftwareSerial  for the connection as on an UNO you have only one HardwareSerial port. SoftwareSerial only allows to configure the baud rate. There are work arounds https://forum.arduino.cc/index.php?topic=251764 , but you can also write a little sketch that reconfigure your HC06 UART to 9600,0,0 using the HardwareSerial which can be setup to the new parity settings to connect to the HC-06.
Something like this
void setup()
{
  //Serial.begin( 9600, SERIAL_8O1 );
  Serial.begin( 9600, SERIAL_8E1 );

  // I do not setup to 9600,0,0 but to 9600,1,0
  // Because the Arduino use the stop bit set by default.
  Serial.println( "AT+UART=9600,1,0" );
}

void loop() {}

I can not try this program, so it's only an example on hoew to reset your HC-05.
Of cause; before you upload the sketch, you have to connect to HC-05 to the Hardware serial pins (0,1).


text:
Arduino recorder with SD card module
Can any one suggest me best device in cheap rates to record audio in to SD-card and vice versa from the speaker......i want to record audio into the sd card like as feedback from customer

You can buy a mini digital voice recorder on eBay for $5. Why would you waste your time bodging something that won't work well with an Arduino?

But i want to integrate it with my project work any external device will not work for it as i have to use only boards.

You should remove the tags bluetooth and arduino-uno from your question

Sure Removing!!

@Majenko just for my curiosity, why wouldn't this be possible with an Arduino? 44.1 KHz/16 bit/stereo doesn't seem unrealistic for a 16 MHz Arduino MCU.

For decent audio recordings, you need an external (16 or 24 bit, 44.1 KHz or more) ADC with at least two channels (stereo).
To save it to an SD, you can buy a so called SD data logger, they are very cheap. Not all SD cards are compatible so you might have to try several ones. The protocol used is SPI.

OK Michel i will try this!! Thanks for your support :)

You're welcome, good luck with your project (if it helped you, please consider upvoting/accepting an answer).


text:
Finger print scanner using Arduino
Any help is greatly appreciated! Trying to build a small door lock that is controlled by a finger print sensor, (I know it will not be very practical). My issue is with putting the hardware together, I have the sensor connected to the Arduno uno with the green and yellow to pins 2 and 3 respectively, then the red and black to the ground and 5V rail. My issue is not knowing how to go about connecting the adafruit chip to the breadboard as I am going to try to use wifi for this project. Secondly I noticed most people use the adafruit Fingerprint sensor which has the module and mine is just a cheap sensor from amazon and was wondering if it will still be able to work the same? Sorry for all the questions I am very new to this and I apologize for sounding so lost haha, anything helps.

you have not told us what device you actually have ... saying that you connected yellow and green wires does not mean anything specific

You should give us a link to that fingerprint sensor. Or even better: to it's datasheet

sorry my bad, here is the link: https://www.amazon.ca/gp/product/B07TZQ6YTH/ref=ppx_yo_dt_b_search_asin_title?ie=UTF8&psc=1

There doesn't seem to be any information on the internet on how to use this device.   Did it come with any manual or documentation ?

No that is my issue,I am kind of lost now, was hoping I wouldn't have to buy a whole new sensor

please post a clear picture of the backside of the sensor .... make sure that it fills most of the frame

Just uploaded the backside of the sensor, hope the quality is good enough!


text:
Problem uploading Arduino sketch on ESP8266-12e
I have a new Mac OS Sierra installed. I just installed the Arduino IDE and the serial drivers for Mac OS X to make the serial USB port available for esp8266 device
When I try to flash the device through the IDE I have these errors:
Arduino:1.8.3 (Mac OS X), Scheda:"NodeMCU 1.0 (ESP-12E Module), 80 MHz, 115200, 4M (3M SPIFFS)"

Archiving built core (caching) in: /var/folders/vz/qxry2ffs3rnd2xtd557pgcf00000gp/T/arduino_cache_169716/core/core_esp8266_esp8266_nodemcuv2_CpuFrequency_80,UploadSpeed_115200,FlashSize_4M3M_244c37a477ed4ef8a63952f7a6e6a50b.a
Lo sketch usa 222149 byte (21%) dello spazio disponibile per i programmi. Il massimo è 1044464 byte.
Le variabili globali usano 31524 byte (38%) di memoria dinamica, lasciando altri 50396 byte liberi per le variabili locali. Il massimo è 81920 byte.
error: failed reading byte
warning: espcomm_send_command: cant receive slip payload data
error: unslip sequence wrong
warning: espcomm_send_command: can't receive command response header
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

What can I do?

i also try with esptool.py
with this line:
esptool.py --port /dev/tty.SLAB_USBtoUART write_flash 0x00000 /var/folders/vz/qxry2ffs3rnd2xtd557pgcf00000gp/T/arduino_build_657411/Blink.ino.bin 0x40000 /var/folders/vz/qxry2ffs3rnd2xtd557pgcf00000gp/T/arduino_build_657411/Blink.ino.bin
but it keeps "connecting..." forever
then i can't even stop the process

Just curious but what version of Arduino IDE are you running? I think there may be an issue with newer IDE versions and certain libraries.
Also if you found a solution in another Library it would be nice to post a link to it for others.

the problem was just the silabs library. i downloaded the latest version and it's working

I installed another version of the driver from silabs' website and now it's working.

3.x version of ESP8266 libraries
If you're using the most updated version of the ESP8266 "NodeMCU 1.0 (ESP-12E Module)" board then all you need to do is update your Silabs library.
2.x version of ESP8266 libraries
If you're using a 2.x version of the ESP8266 "NodeMCU 1.0 (ESP-12E Module)" board, it is more involved. It comes with a packaged version of pyserial which resolves the wrong versions of the IOKit and CoreFoundation libraries. You will need to edit the pyserial script for your board version manually following the instructions here: https://forum.arduino.cc/t/pyserial-and-esptools-directory-error/671804/5.
An alternative is use the Windows version of the flashing tool provided by Espressif by running it through a Windows emulator or VM. You can find instructions for that here: https://blog.squix.org/2015/05/esp8266-flashing-nodemcu-v10-on-mac-os.html.


text:
Connecting SIM900A GSM/GPRS module Arduino Mega
I have bought the following SIM900A GSM/GPRS module. I need to connect it to an Arduino Mega. Can anyone answer me which pin I need to connect to the Arduino?

GSM modules works on serial protocol. You will have to connect Rx Tx of GSM to Tx Rx of arduino but before that try googling for Interfacing GSM with arduino. Also this question should be migrated to Arduino SE

hai, Thanks for your reply. actually i have tired in searching for the exact board data sheet. there is additional TTL RX,TX and ground can be seen next to the serial port. and there are six pins behind the serial port one set covered by green jack and other two by blue. most of the googling showed we have to remove those jacket to use this module with arduino. but those modules don't have the TTL pins which i have told earlier.

From your pic, it looks like the upper left corner has a jumper with TTL level TX, RX, GND.

hai, thanks. i am also thinking your way. but i am not sure whether it is right or wrong. but if i go for this way do i need to do any changes on the pins behind the serial port which are covered by green and blue jacks. which i mean do i need to remove the jacks..or else any kind of changes...??


text:
Using RFID and fingerprint sensor together
I am using both an RFID and a fingerprint sensor in my project. When running the program, the RFID is detected but the fingerprint sensor is not detected and hence my code is not going forward.
Here is my code
#include <Adafruit_Fingerprint.h>
#include <SoftwareSerial.h>
#include <MFRC522.h>
#include <SPI.h>

#define SAD 10
#define RST 5

MFRC522 nfc(SAD, RST);

uint8_t id;
uint8_t getFingerprintEnroll();
int getFingerprintIDez();

// pin #2 is IN from sensor (GREEN wire)
// pin #3 is OUT from arduino (WHITE wire)
SoftwareSerial mySerial(2, 3);
Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);

void setup() {
  SPI.begin();
  Serial.begin(115200);
  Serial.println("Looking for MFRC522.");
  nfc.begin();
  byte version = nfc.getFirmwareVersion();
  if (! version) {
    Serial.print("Didn't find MFRC522 board.");
    while (1); //halt
  }

  Serial.print("Found chip MFRC522 ");
  Serial.print("Firmware ver. 0x");
  Serial.print(version, HEX);
  Serial.println(".");
  Serial.begin(9600);

  Serial.println("Fingerprint and RFID Test");

  finger.begin(57600);
  if (finger.verifyPassword()) {
    Serial.println("Found fingerprint sensor!");
  } else {
    Serial.println("Did not find fingerprint sensor :(");
    while (1);
  }
}

char abc;

void loop() {
  abc = Serial.read();
  switch (abc) {
    case '1': {
      // enroll method
    }
    break ;
    case '2': {
      // verify method
    }
    break;
    case '3': {
      // rfid method
    }
  }
}

What does happen?

serial monitor is not showing anything. when I run the rfid and fingerprint code individual they both are working correctly but when join them not working

Literally nothing?  Not even Fingerprint and RFID Test in your setup()?

fingerprint and rfid test is working if I write rfid.init() after this code. if I write before fingerprint and rfid test then it shows nothing

Could you replace your code with a minimal, complete, verifiable example, please? You could also edit your question to remove irrelevant information - such as the stuff about the switch statement. Help us to help you.

Get rid of the Serial.begin(9600). You're accidentally changing the Serial baud rate without doing the same in your serial monitor so you'll probably see gibberish, if anything.

ya I deleted the Serial.begin(9600) and it worked

@TisteAndii would you mind turning your comment into an answer?

Get rid of the Serial.begin(9600). You're accidentally changing the Serial baud rate without doing the same in the serial monitor so you'll probably see gibberish, if anything.


text:
SPI communication with Arduino and PGA411-Q1 resolver sensor
I have been trying to implement SPI communication between an Arduino board and a PGA411-Q1 resolver sensor board. I have set up the Arduino SPI settings as indicated on the resolver sensor's datasheet (http://www.ti.com/lit/an/slaa688/slaa688.pdf) - 8MHz sclock, MSB first and SPIMode1.
The communication is done by sending and receiving 32 bits both to and from the Arduino. The bits are distributed as follows.
Outgoing 32bit data frame by Arduino to the sensor:
O-5 bits: Arduino's CRC for data
6-7 bits: Always zero
8-23 bits: Data
24-31 bits: Register address
Incoming 32bit data frame by the sensor to the Arduino:
O-5 bits: Sensor's CRC for data
6-7 bits: SPI communication status
8-23 bits: Data
24-31 bits: Register address
Also, there is mandatory to send and receive a CRC6 code from both the board and Arduino and I have implemented it as well. (I will not be checking the CRC code received by the Arduino board. I will check it later. But I am already sending the CRC code needed by the sensor board).
This is the code written by me:
NOTE: The crc_cal function outputs the crc code from Arduino to the sensor along with the two 'always zero' bits.
#include <SPI.h>
unsigned int crc_cal (unsigned long datin);

 const int ncs = 10;
 unsigned char crc_char = 0x3F;

 void setup() {

  // initalize the chip select pin:
  pinMode(ncs, OUTPUT);
  pinMode(FAULTRES,OUTPUT);
  pinMode(NRESET,OUTPUT);

  // put your setup code here, to run once:
  Serial.begin(9600);

  //NRESET must go from LOW to HIGH
  digitalWrite(NRESET,LOW);
  digitalWrite(NRESET,HIGH);

  //wait at least 5ms to complete diagnostics tests
  delay(10);

  //FAULTRES LOW
  digitalWrite(FAULTRES,LOW);

  // start the SPI library:
  SPI.begin();

 // give the sensor time to set up:
  delay(100);

   }

void loop() {

SPI.beginTransaction(SPISettings(6400000, MSBFIRST, SPI_MODE1));

digitalWrite(ncs, LOW);

byte temp_3 = SPI.transfer(0x41);

byte temp_2 = SPI.transfer(0x0F);

byte temp_1 = SPI.transfer(0x0F);

byte temp_0 = SPI.transfer(crc_char);

digitalWrite(ncs, HIGH);

SPI.endTransaction();

unsigned int angle_raw = 0;
angle_raw = temp_2;
angle_raw = angle_raw << 8;
angle_raw = angle_raw | temp_1;
angle_raw &= 0x3FF;
Serial.println(angle_raw);

int crc = crc_cal(0x410F0F00);
unsigned char crc_char = crc;
crc_char = crc_char & 0x3F;
 delay(100);

 }

     /* CRC6 calculation - optimized for PGA411 */
 unsigned int crc_cal (unsigned long datin)
 {
 unsigned int byte_idx, bit_idx, crc= (0x3F << 2);
 /* byte by byte starting from most significant (3-2-1) */
 for (byte_idx = 3; byte_idx >= 1; byte_idx--)
 {
 /* XOR-in new byte from left to right */
 crc ^= ((datin >> (byte_idx<<3)) & 0x000000FF);
 /* bit by bit for each byte */
 for(bit_idx = 0; bit_idx < 8; bit_idx++)
 {
 crc = crc << 1 ^ (crc & 0x80 ? (0x5B << 2) : 0);
 }
 }
 return(crc >> 2 & 0x3F); /*restore two bit offset */

 }

I have used the code provided in the PGA411-Q1's datasheet (http://www.ti.com/lit/an/slaa688/slaa688.pdf) and it works fine when I check it manually. Some examples for input data frames and their CRC codes can be found in the section 7.5.4 of the datasheet found here http://www.ti.com/lit/ds/symlink/pga411-q1.pdf
As you may notice from the code I am sending the register address which I want data from in the first 8 bits of SPI.transfer. The read address of that register is 0x41.
Next, I'm sending two garbage values as data because this is a read-only register.
Finally, I'm sending the CRC code calculated by the crc_cal function.
All I'm receiving in the serial monitor are zeros and I can't figure out what went wrong. I would appreciate some insight into this.

Why are you sending a CRC value calculated from values that you received? In my understanding you send a CRC value calculated from the values, that you are sending

@chrisl I have fixed it now. Still no change.

Then please update your question with your new code. In the linked application note I see an initialization process. But I don't find point 2 and point 5 in your program: "Step 2.  Ensure that the NRESET signal has a low-to-high transition. Step 5.  Set the FAULTRES pin logic low." May be a good thing to include that also

hello @chrisl the FAULTRES pin can be set to zero by the GUI software that comes with the sensor board. I have already set it low. Also, the NRESET can be made low-to-high by manually pressing the pin associated with the NRESET pin. I have done both but still no progress.

I have separately connected NRESET and FAULTRES pins to pin 4 and 3 of Arduino board and have updated the code


text:
Need help in the problem with analog input readings and RTC DS3231
I have 3 analog input(0-1024). I want two outputs based on levels of analog inputs. Eg. inputs have 2 levels. for A0 at 300,digital output pin3 turns ON; and A0 at 500, digital output pin 4 turns ON. Similar for all analog inputs have two levels. Digital output pin 3 turns ON for 1st level and for 2nd level, pin 4 should turn ON. Both should not turn ON at same time. Also, pin 3, should turn ON for specific time in a day for 1 hour.
Problem Facing: (1) I tried this program but outputs doesnt switch according to levels of analog inputs. Once Pin 3 turns ON, it doesnt let pin4 to turn ON. Also, after removing analog inputs, LED remains ON as it is  (2) RTC doesnt turn ON on correct time.
#include<DS3231.h>
#include<Wire.h>
DS3231 rtc(SDA,SCL);
Time t;
const int OnHour=15;  // specified time to turn pin3 ON
const int OnMin=26;
const int OffHour=15;
const int OffMin=28;
int CO2=0;
int Temp=0;
int Humidity=0;

void setup() {

Serial.begin(115200);
rtc.begin();
for(int i=2;i<6;i++){
  pinMode(i, OUTPUT);
}
 }

void loop() {
  t=rtc.getTime();
  delay(1000);
  CO2=analogRead(A0);   //analog input 1
  Temp=analogRead(A1);   //analog input 2
  Humidity=analogRead(A2); //analog input 3

  if((CO2>500)&&(CO2<700)) //500 is low level and 700 is high level
  {
    digitalWrite(2,HIGH);  //indicator LED for low level
    digitalWrite(4,HIGH);  //actual output for low level
    digitalWrite(3,LOW);   //indicator LED for high level
    digitalWrite(5,LOW);   //actual output for high level

  }
  else if(CO2>700) //700 is high level
  {
    digitalWrite(3,HIGH);
    digitalWrite(5,HIGH);
    digitalWrite(2,LOW);
    digitalWrite(4,LOW);

  }

  if((Temp>450)&&(Temp<600))
  {
    digitalWrite(4,HIGH);
    digitalWrite(2,HIGH);
    digitalWrite(3,LOW);
    digitalWrite(5,LOW);

  }
  else if(Temp>600)
  {
    digitalWrite(3,HIGH);
    digitalWrite(5,HIGH);
    digitalWrite(2,LOW);
    digitalWrite(4,LOW);

  }

  if((Humidity>300)&&(Humidity<850))
  {
    digitalWrite(4,HIGH);
    digitalWrite(2,HIGH);
    digitalWrite(3,LOW);
    digitalWrite(5,LOW);

  }
  else if(Humidity>850)
  {
    digitalWrite(5,HIGH);
    digitalWrite(3,HIGH);
    digitalWrite(2,LOW);
    digitalWrite(4,LOW);

  }

  if (t.hour==OnHour && t.min==OnMin)
  {
    digitalWrite(2,HIGH);
    digitalWrite(4,HIGH);
    digitalWrite(3,LOW);
   digitalWrite(5,LOW);

  }
  else if(t.hour==OffHour && t.min==OffMin)
  {
    digitalWrite(2,LOW);
    digitalWrite(4,LOW);
    digitalWrite(3,LOW);
    digitalWrite(5,LOW);

 }
}

Please format your code correctly like you did with your first code. You can put a horizontal line between the codes by adding --- surrounded by free lines. Also please be more specific how the codes don't work. Explain, what the code does and what you expected from it. And do you really want to have 2 seperate codes?

I don't see how the code isn't working, maybe it's because of this line: for(int i=2;i<6;i++){   pinMode(i, OUTPUT); }. try defining pin 2-6 as OUTPUT one by one instead of using that method...

The first problem I see is that you did not set the actual time of the RTC. Do you program it with another piece of code? The second problem I see is, that you are manipulating all LEDs in all conditional cases. Probably you overwrite the information of CO2 with Humidity or Temp or both.  But as far as I don't know what the LEDs mean and how exactly you want them to behave, this is just a rough guess.

Your description is not clear, but definitely different from your code. >"Also I put other 3 LEDs to read which analog input is higher." I don't see such a comparison.

thank you for sparing your time to read my question. I have edited my question here. I guess it can be clearly pictured now.


text:
ESP8266 mqtt publish + subscribe + serial read
seems I have some issues in my code as I subscribe for specific mqtt topic and also read same value via serial and publish it to mqtt. It takes time for device connected to serial to change setting and I'am reading its state to quickly. How to optimize code that during subscribed topic value change serial read would be susspended or specific value data byte read ignored for some time.
Main code parts:
    const char* mqtt_topic_base = "panasonic_heat_pump/sdc";
    const char* mqtt_set_quiet_mode_topic =

"panasonic_heat_pump/SetQuietMode";
        byte inCheck = 0;

    #define MAXDATASIZE 256
    char data[MAXDATASIZE];
    int data_length = 0;

    // log message to sprintf to
    char log_msg[256];

    // mqtt topic to sprintf and then publish to
    char mqtt_topic[256];

    // mqtt
    WiFiClient mqtt_wifi_client;
    PubSubClient mqtt_client(mqtt_wifi_client);

    void send_command(byte* command, int length)
    {

      int bytesSent = Serial.write(command, length);
      sprintf(log_msg, "sent bytes    : %d", bytesSent); log_message(log_msg);

      // wait until the serial buffer is filled with the replies
      delay(1000);

      // read the serial
      readSerial();

      sprintf(log_msg, "received size : %d", data_length); log_message(log_msg);
    }

    // Callback function that is called when a message has been pushed to one of your topics.
    void mqtt_callback(char* topic, byte* payload, unsigned int length) {
      char msg[length + 1];
      for (int i=0; i < length; i++) {
        msg[i] = (char)payload[i];
      }
      msg[length] = '\0';
    // set 0 for Off mode, set 1 for Quiet mode 1, set 2 for Quiet mode 2, set 3 for Quiet mode 3
        if (strcmp(topic, mqtt_set_quiet_mode_topic) == 0)
         {
        String set_quiet_mode_string(msg);
        int quiet_mode = (set_quiet_mode_string.toInt() + 1) * 8;
        int checksum = 512 - (241 + 108 + 1 + 16 + quiet_mode);

        sprintf(log_msg, "set Quiet mode to %d", quiet_mode / 8 - 1); log_message(log_msg);
        byte command[] = {0xf1, 0x6c, 0x01, 0x10, 0x00, 0x00, 0x00, quiet_mode, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, checksum};
        send_command(command, sizeof(command));
         }

     if (strcmp(topic, mqtt_topic_base) == 0)
      {
        log_message("Updating..");

        update_everything();
      }
    }

    void update_everything()
    {

      get_heatpump_data();

    }

    void get_heatpump_data() {
        byte command[] = {0x71, 0x6c, 0x01, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x12};
        send_command(command, sizeof(command));

        int quiet_mode_state = (int)(data[7]);

        char* quiet_mode_state_string;
        if (quiet_mode_state == 73) {
          quiet_mode_state_string = "0";
        } else if (quiet_mode_state == 81) {
          quiet_mode_state_string = "1";
        } else if (quiet_mode_state == 89) {
          quiet_mode_state_string = "2";
        } else if (quiet_mode_state == 97) {
          quiet_mode_state_string = "3";
        } else if (quiet_mode_state == 73) {
          powerfull_mode_state_string = "OFF";
        } else if (quiet_mode_state == 74) {
          powerfull_mode_state_string = "30min";
        } else if (quiet_mode_state == 75) {
          powerfull_mode_state_string = "60min";
        } else if (quiet_mode_state == 76) {
          powerfull_mode_state_string = "90min";
        } else {
          quiet_mode_state_string = "Unknown";
        }
        sprintf(log_msg, "received quiet mode state : %d (%s)", quiet_mode_state, quiet_mode_state_string); log_message(log_msg);
        sprintf(log_msg, "powerfull mode state : %d (%s)", quiet_mode_state, powerfull_mode_state_string); log_message(log_msg);

        sprintf(mqtt_topic, "%s/%s", mqtt_topic_base, "quiet_mode_state"); mqtt_client.publish(mqtt_topic, quiet_mode_state_string);
        sprintf(mqtt_topic, "%s/%s", mqtt_topic_base, "powerfull_mode_state"); mqtt_client.publish(mqtt_topic, powerfull_mode_state_string);

    }

    void loop() {
      // Handle OTA first.
      ArduinoOTA.handle();

      if (!mqtt_client.connected())
      {
        mqtt_reconnect();
      }
      mqtt_client.loop();

      update_everything();
      delay(5000);
    }

    void readSerial()
    {
        if(Serial.available() > 0){

          log_message("serial available");
        Serial.readBytes(data, 203);
        while(Serial.available()){
          delay(2);
          Serial.read();
        }

      }
    }

set the used value from the published mqtt, not from the internal value. it fires an event anyway, right? this pattern vastly simplifies reconciling values, at the slight cost of model update delay time, which often isn't strictly required anyway.

Any example how to do??


text:
Wemos D1 Mini using RF with RCSwitch
I’ve bought a RF transmitter and receiver on eBay and I’m trying to get my garage door codes with my Wemos D1 Mini.

I’ve downloaded the RCSwitch library, hooked up the receiver to ground, 5v and data to pin D4.  Also flashed the sample receiver sketch.
The problem is that I don’t get anything on serial monitor... the Wemos board has an inbuilt led that flashes when I press my garage remote buttons, which means that pin DATA is sending a signal to the board, but I can’t see anything on serial monitor (Baud rates and serial connectivity is all good).
Tried other pins and didn’t get anything different.
Does anyone know how can I specify the pins with RCSwitch or have and idea of what is going on?
UPDATE 1
I’ve certified that transmitter is working and hooked properly using the Radiohead library.

UPDATE 2
The remote I have is so cheap that it is barely impossible to determine which chip it uses:

get the neighbor's garage door codes too if it is possible :-)

Well, I can’t get even my garage door codes...

why do you believe that you can receive your garage control codes with that device?

Actually, I don’t need the code, I need to clone the signal to open my garage using my Wemos

how about sharing your code?

There is no code to share. I was running the example from RCSwitch library

Would be interesting to share the code anyway, also the schema you're connecting your arduino to the RC or TX devices. I am connecting to D2 (pin #2, so INT0) as the sample requests.