text:
ESP32-CAM not sending base64 string as HTTP post request
in my recent project, I'm trying to detect motion and capture an image using the esp32 cam module and send it to the server via HTTP.
Once the image is captured it is converted to a base64 string and while trying to send the data at the server the body of the HTTP request is empty i.e., the base64 string is not sent.
Code that sends the image
void sendPic(String data, String len) {

    if(WiFi.status() == WL_CONNECTED) {

      HTTPClient http;

      http.begin("http://192.168.1.35:8000/capture");

      String d = data ;

      int res_c = http.POST(d);

      if(res_c > 0){
        Serial.println(res_c);
      }
      else{
        Serial.println("Not sent");
        Serial.print(res_c);
      }
      http.end();
    }
}

Entire code
// turn on debug messages
#define VERBOSE
#include "Arduino.h"
#include <base64.h>
#include <esp_wifi.h>
#include <HTTPClient.h>
#include "EloquentSurveillance.h"

const char* ssid = "****";
const char* password = "********";

void sendPic(String data, String len) {

    if(WiFi.status() == WL_CONNECTED)

      HTTPClient http;

      http.begin("http://192.168.1.35:8000/capture");

      String d = data ;

      int res_c = http.POST(d);

      if(res_c > 0){
        Serial.println(res_c);
      }
      else{
        Serial.println("Not sent");
        Serial.print(res_c);
      }
      http.end();

    }
}

/**
 * Instantiate motion detector
 */
EloquentSurveillance::Motion motion;

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

    WiFi.begin(ssid, password);
    Serial.println("Connecting");
    while(WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
    }
    Serial.println("");
    Serial.print("Connected to WiFi network with IP Address: ");
    Serial.println(WiFi.localIP());

    if(WiFi.status() == WL_CONNECTED) {
      HTTPClient http;
      int res_c = -1;
      while(res_c < 0){
        http.begin("http://192.168.1.35:8080/capture");
        http.addHeader("Content-Type", "text/plain");
        String test = "hello from esp32";
        res_c = http.POST(test);

        if(res_c > 0){
          Serial.println(res_c);
        }
        else{
          Serial.println(res_c);
        }
        http.end();
      }

    }

    delay(3000);
    debug("INFO", "Init");

    /**
     * See CameraCaptureExample for more details
     */

    camera.aithinker();
    camera.vga();
    camera.bestQuality();

    /**
     * Configure motion detection
     *
     * > setMinChanges() accepts a number from 0 to 1 (percent) or an integer
     *   At least the given number of pixels must change from one frame to the next
     *   to trigger the motion.
     *   The following line translates to "Trigger motion if at least 10% of the pixels
     *   in the image changed value"
     */
    //motion.setMinChanges(0.015);
    motion.setMinChanges(0.02);

    /**
     * > setMinPixelDiff() accepts an integer
     *   Each pixel value must differ at least of the given amount from one frame to the next
     *   to be considered as different.
     *   The following line translates to "Consider a pixel as changed if its value increased
     *   or decreased by 10 (out of 255)"
     */
    motion.setMinPixelDiff(5);

    /**
     * > setMinSizeDiff() accepts a number from 0 to 1 (percent) or an integer
     *   To speed up the detection, you can exit early if the image size is almost the same.
     *   This is an heuristic that says: "If two consecutive frames have a similar size, they
     *   probably have the same contents". This is by no means guaranteed, but can dramatically
     *   reduce the computation cost.
     *   The following line translates to "Check for motion if the filesize of the current image
     *   differs by more than 5% from the previous".
     *
     *   If you don't feel like this heuristic works for you, delete this line.
     */
    //motion.setMinSizeDiff(0.015);
    motion.setMinSizeDiff(0.02);

    /**
     * Initialize the camera
     * If something goes wrong, print the error message
     */
    while (!camera.begin())
        debug("ERROR", camera.getErrorMessage());

    debug("SUCCESS", "Camera OK");
}

/**
 *
 */
void loop() {
    /**
     * Try to capture a frame
     * If something goes wrong, print the error message
     */
    if (!camera.capture()) {
        debug("ERROR", camera.getErrorMessage());
        return;
    }

    /**
     * Look for motion.
     * In the `true` branch, you can handle a motion event.
     * For the moment, just print the processing time for motion detection.
     */
    if (!motion.update())
        return;

    if (motion.detect()) {
        debug("INFO", String("Motion detected in ") + motion.getExecutionTimeInMicros() + " us");
        String encoded = base64::encode(camera.getBuffer(), camera.getFileSize());
        int size = camera.getFileSize() + 50;
        sendPic(encoded, (String)size);
        delay(4000);
    }
    else if (!motion.isOk()) {
        /**
         * Something went wrong.
         * This part requires proper handling if you want to integrate it in your project
         * because you can reach this point for a number of reason.
         * For the moment, just print the error message
         */
        debug("ERROR", motion.getErrorMessage());
    }
}

I'm a beginner in using esp32 cam any guidance on how to achieve the objective will be helpful. Thanks in advance!

ESP32-CAM not sending base64 string as HTTP post request  ... what is it sending? ... how is it sending it?

Hi @jsotola the request is received at the server when I print the request in the console it contains only the headers and the body is empty. I checked it with wireshark as well.

Have you checked it before it's sent? Try outputting the body in your code everywhere you pass it through the code - like right after the data is encoded and just before it's posted. Also there's absolutely no need to do  String d = data ;, all that's doing is making an extra unneeded copy of the data, which given the limited memory on the ESP32 is not great.

Hi @romkey I actually did print the encoded data before it was sent and the string was printed. And I just added the line because while debugging I tried adding a prefix to see whether it went through but no either way.


text:
How to configure I2S with ESP32 and MAX98357A to reproduce wav files?
I have configured I2S to reproduce files with an ESP32 and a MAX98357A from and SD card. The problem is that it reproduces the files way too fast, like they are sped up * 100. Here is my (simplified) code:
#define I2S_DOUT 25
#define I2S_BCLK 27
#define I2S_LRC 26

void setup() {
// Start SD card and sqlite
  SPI.begin();
  if (!SD.begin()) {
    Serial.println("SD card not found");
    while (1) {};
  }
// Configure I2S
  i2s_config_t i2s_config = {
      .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_TX),
      .sample_rate = 44100,
      .bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT,
      .channel_format = I2S_CHANNEL_FMT_RIGHT_LEFT,
      .communication_format = I2S_COMM_FORMAT_I2S_MSB,
      .intr_alloc_flags = ESP_INTR_FLAG_LEVEL1,
      .dma_buf_count = 2,
      .dma_buf_len = 1024,
      .tx_desc_auto_clear = true,
  };

  i2s_pin_config_t pin_config = {
      .bck_io_num = I2S_BCLK,
      .ws_io_num = I2S_LRC,
      .data_out_num = I2S_DOUT,
      .data_in_num = -1,
  };

  i2s_driver_install(I2S_NUM_0, &i2s_config, 0, NULL);
  i2s_set_pin(I2S_NUM_0, &pin_config);
  i2s_set_dac_mode(I2S_DAC_CHANNEL_RIGHT_EN);
  i2s_set_sample_rates(I2S_NUM_0, 44100);
}

void loop() {
// Play the audio file
  string filename = "/audios/" + text + ".wav";
  File file = SD.open(filename.c_str());
  if (!file) {
    Serial.println("Failed to open file for reading");
    return;
  }

  const size_t buffer_size = 512;
  uint8_t buffer[buffer_size];
  size_t bytes_read;
  size_t bytes_written;
  while (file.available() && (bytes_read = file.read(buffer, buffer_size)) > 0) {
    i2s_write(I2S_NUM_0, buffer, bytes_read, &bytes_written, portMAX_DELAY);
    if (bytes_read == 0) break;
  }
  file.close();
}

How do I configure it correctly?

So I figured it out (a somewhat long time ago) but forgot to post here hahaha.
Basically, the i2s_config_t was not properly configured. Here's a corrected version:
i2s_config_t i2s_config = {
      .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_TX),
      .sample_rate = 44100,
      .bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT,
      .channel_format = I2S_CHANNEL_FMT_ONLY_LEFT,
      .communication_format = I2S_COMM_FORMAT_I2S_MSB,
      .intr_alloc_flags = ESP_INTR_FLAG_LEVEL1,
      .dma_buf_count = 8,
      .dma_buf_len = 1024,
      .use_apll = false,
      .tx_desc_auto_clear = true,
  };

If you compare, the .channel_format configuration changes from I2S_CHANNEL_FMT_RIGHT_LEFT to I2S_CHANNEL_FMT_ONLY_LEFT. This is important because when using RIGHT_LEFT and only using one amplifier, 2 sound outputs were sent but only one amp was receiving them, causing the sound to play at twice the speed. Now, the .dma_buf_count was increased to 8, and added the .use_apll config, because I saw it somewhere else, I don't really know what it does hahaha.
There are other things.
In the setup for the i2s communication, I didn't include
i2s_set_dac_mode(I2S_DAC_CHANNEL_RIGHT_EN);
i2s_set_sample_rates(I2S_NUM_0, 44100);

And created a new function, play_sound.
Here's the complete code:
// sound.cpp

#include <sound.h>

bool parseWavHeader(File &file, WavHeader &header) {
  if (file.read() != 'R' || file.read() != 'I' || file.read() != 'F' || file.read() != 'F') {
    Serial.println("Invalid WAV file");
    return false;
  }

  file.seek(22);
  header.num_channels = file.read() | (file.read() << 8);
  header.sample_rate = file.read() | (file.read() << 8) | (file.read() << 16) | (file.read() << 24);
  file.seek(34);
  header.bits_per_sample = file.read() | (file.read() << 8);
  file.seek(44);  // Skip to the audio data
  return true;
}

void setup_sound() {
  i2s_config_t i2s_config = {
      .mode = (i2s_mode_t)(I2S_MODE_MASTER | I2S_MODE_TX),
      .sample_rate = 44100,
      .bits_per_sample = I2S_BITS_PER_SAMPLE_16BIT,
      .channel_format = I2S_CHANNEL_FMT_ONLY_LEFT,
      .communication_format = I2S_COMM_FORMAT_I2S_MSB,
      .intr_alloc_flags = ESP_INTR_FLAG_LEVEL1,
      .dma_buf_count = 8,
      .dma_buf_len = 1024,
      .use_apll = false,
      .tx_desc_auto_clear = true,
  };

  i2s_pin_config_t pin_config = {
      .bck_io_num = I2S_BCLK,
      .ws_io_num = I2S_LRC,
      .data_out_num = I2S_DOUT,
      .data_in_num = -1,
  };

  i2s_driver_install(I2S_NUM_0, &i2s_config, 0, NULL);
  i2s_set_pin(I2S_NUM_0, &pin_config);
}

void play_sound(std::string text, fs::FS &SD) {
  std::string filename = "/audios/" + text + ".wav";
  File file = SD.open(filename.c_str());
  if (!file) {
    Serial.println("Failed to open file for reading");
    while (1) delay(1);
  }

  WavHeader header;
  if (!parseWavHeader(file, header)) {
    Serial.println("Invalid WAV file");
    return;
  }

  i2s_set_sample_rates(I2S_NUM_0, header.sample_rate);

  const size_t buffer_size = 512;
  uint8_t buffer[buffer_size];
  size_t bytes_read;
  size_t bytes_written;
  while (file.available() && (bytes_read = file.read(buffer, buffer_size)) > 0) {
    i2s_write(I2S_NUM_0, buffer, bytes_read, &bytes_written, portMAX_DELAY);
    if (bytes_read == 0) break;
  }

  file.close();
}

// sound.h

#ifndef SOUND_H
#define SOUND_H

#include <SD.h>
#include <driver/i2s.h>

#define I2S_DOUT 25
#define I2S_BCLK 33
#define I2S_LRC 26

struct WavHeader {
  uint32_t sample_rate;
  uint16_t bits_per_sample;
  uint16_t num_channels;
};

bool parseWavHeader(File &file, WavHeader &header);
void setup_sound();
void play_sound(std::string text, fs::FS &SD);

#endif  // SOUND_H

Hope it helps you not go through the struggle I went through!

good job.
the another solution is to change the .sample_rate = 16000, can play well. for the file saved at same sample_rate.

source: Stack Exchange

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

sort: votes


text:
RFID card read loop seems to stop
I successfully programmed an RFID card reader to switch lights on and off if any rfid card is presented.  I have tested this and it works, with the lights continually switching on and off if any rfid enabled card is is presented.
I tried to add a command that if two specific cards are read (identified by their UID numbers) then only those cards would reset the lights to "off" no matter what the state they were currently in - like a reset button.
The problem is that once one of those cards is presented, the light goes off but the system stops responding and presenting one of the other cards no longer turns the light on and off.
I am fairly new to programming Arduino, as well as with RFID technology, but it seems like the loop does not reset to the beginning properly, or my IF statement somehow leaves the system in a state where the beginning code can't be run.
My code is below.  Any thoughts would be appreciated.
`
#define r1 A0
int relay1 = LOW;

#include <SPI.h>
#include <MFRC522.h>

#define SS_PIN 10
#define RST_PIN 9
MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.

void setup()
{
  pinMode(r1, OUTPUT);

  Serial.begin(9600);   // Initiate a serial communication
  SPI.begin();      // Initiate  SPI bus
  mfrc522.PCD_Init();   // Initiate MFRC522
  Serial.println("Approximate your card to the reader...");
  Serial.println();
}

void loop()
{
  // Look for new cards
  if ( ! mfrc522.PICC_IsNewCardPresent())
  {
    return;
  }

// Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial())
  {
    return;
  }

  //Show UID on serial monitor
  Serial.print("UID tag :");
  String content = "";
  byte letter;
  for (byte i = 0; i < mfrc522.uid.size; i++)
  {
    Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
    Serial.print(mfrc522.uid.uidByte[i], HEX);
    content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
    content.concat(String(mfrc522.uid.uidByte[i], HEX));
  }
  Serial.println();
  Serial.print("Message : ");
  content.toUpperCase();

  if ((content.substring(1) == "23 49 1F BE") || (content.substring(1) == "CB CB 2C E3")) //change here the UID of the card/cards that you want to give access
  {
   Serial.println("Staff access");
    Serial.println();
    relay1 = HIGH;
    digitalWrite(r1, relay1);
    delay(500);
  }
  else
  {

    Serial.println("Authorized access");
    Serial.println();
    relay1 = ~ relay1;
    digitalWrite(r1, relay1);
    delay(500);
  }
}

`

Are you looking at the serial output when this happens? do you see the "Staff Access" message? and then is there any other indication of what its doing? I would add print statements in the two places you return, this way you will be able to monitor the state of the loop and/or see if it stops running and where the last place it printed from.

if the first card i present is a generic card, the serial monitor returns "authorized access" with each tap and keeps turning the light on and off.  If I then present staff card, the serial monitor returns "staff access" but the lights do nothing, and thereafter, if i tap the generic card again, the serial monitor returns "authorize access again, but the lights don't respond anymore.

This operation on an int needs some explanation: relay1 = ~ relay1;. Is there another way you could achieve your goal here?

Ya, relay1 should be a bool, and then use relay1=!relay1; to switch states.

relay1 = ~relay1 worked fine when i was just using one criteria for the cards (meaning everyone was authorized).  it was only when I added the criteria of "Staff access" that it stopped working.   Is there a particular reason why !relay1 would work better than ~relay1  ?

The C++ tilde  (~) operator is a bitwise NOT operator.  That is, it changes every 0 to a 1 and every 1 to a 0. It is almost never appropriate for use with signed numbers such as int where the high order bit is a sign bit. It is normally used for manipulating individual bits in a variable, not for logical operations.

Thank you, and advice taken, but do you think this the issue causing the loop appear not to work?  Like I said, it worked before, alternating the state from low to high, when any card would activate it.  Why would the code no longer trigger the lighting event now that there are two sets of access cards to evaluate?  I feel like there might be something wrong with the if statement, or how it ends.

The problem is the inappropriate use of the tilde (~) , which is a bitwise NOT operator, against the int variable relay1.
It appears to work correctly when relay1 starts with LOW which has the value 0. That is, relay1 has the internal value 0b0000000000000000.  If now the statement relay1 = ~relay1 is executed, relay1 has the internal value 0b1111111111111111. This is treated as a HIGH in the expression digitalWrite(r1, relay1); So it appears to work correctly.
If again the statement relay1 = ~relay1 is executed, relay1 has the internal value 0b0000000000000000 This is treated as a LOW in the expression digitalWrite(r1, relay1);
So that would also appear to work continuously, turning the relay on and off.
The problem comes when you explicitly set relay1 to HIGH here: relay1 = HIGH;. HIGH has the value 1, that is relay1 now has the intenal value 0b0000000000000001 and again that works, however, the next execution of the statement relay1 = ~relay1 gives relay1 the internal value
0b1111111111111110 which is also treated as HIGH. So, from now on, the statement relay1 = ~relay1 will always result in relay1 having a value which is interpreted as HIGH. So the relay appears to be stuck.
The solution, which already appears in a comment, is to change the statement int relay1 = LOW; to bool relay1 = LOW; and change this statement relay1 = ~ relay1; to relay1 = ! relay1;

Thank you SO much for explaining.  I didn't understand that there would be an internal value other than zero and one associated with LOW and HIGH, so couldn't really see how the solution of changing the relay statement would help.  That does sound like it will fix the problem and now I have another concept to look into and understand more :)

@Christine, the protocol is to tick the answer is correct.  :-)

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


text:
SPFD5408 for TFT in Arduino Due
I have interfaced HC024071 TFT Display with Arduino Due using SPFD5408 Adafruit library. It works perfect.
But using the same library with Arduino Due (with pin connections modified as follows):
// For the Arduino Uno, Duemilanove, Diecimila, etc.:
//   D0 connects to digital pin 8  (Notice these are
//   D1 connects to digital pin 9   NOT in order!)
//   D2 connects to digital pin 2
//   D3 connects to digital pin 3
//   D4 connects to digital pin 4
//   D5 connects to digital pin 5
//   D6 connects to digital pin 6
//   D7 connects to digital pin 7

But unfortunately, errors occur (which made me guess Due is incompatible with the same)
Build options changed, rebuilding all
In file included from C:\Users\Arun Baby\Desktop\test\sketch_dec16c\sketch_dec16c.ino:2:0:

sketch\TFTLIB.H: In function 'void Draw_Welcome_Screen()':

sketch\TFTLIB.H:154:36: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   draw_text("Z.A.R.S",55,150,BLUE,3);

                                    ^

sketch\TFTLIB.H:155:59: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   draw_text("Zone Adaptive Response System",25,180,BLACK,1);

                                                           ^

sketch\TFTLIB.H:157:57: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   draw_text("Touch anywhere to continue!",30,280,BLACK,1);

                                                         ^

sketch\TFTLIB.H: In function 'void Draw_Menu()':

sketch\TFTLIB.H:166:48: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   draw_text("Z.A.R.S Main Menu",120,300,WHITE,1);

                                                ^

sketch\TFTLIB.H:168:42: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   draw_text("Driving Mode",20,45,0x1220,2);

                                          ^

sketch\TFTLIB.H:169:46: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   draw_text("Zones Supported",20,135,0x1220,2);

                                              ^

sketch\TFTLIB.H:170:39: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   draw_text("Settings",20,225,0x1220,2);

                                       ^

sketch\TFTLIB.H: In function 'void Draw_Settings()':

sketch\TFTLIB.H:179:39: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   draw_text("Settings",160,300,WHITE,1);

                                       ^

sketch\TFTLIB.H:181:43: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   draw_text("Re-Caliberate",20,45,0x1220,2);

                                           ^

sketch\TFTLIB.H:182:39: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   draw_text("GPS Lock",20,135,0x1220,2);

                                       ^

sketch\TFTLIB.H:183:34: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

   draw_text("BACK",20,225,WHITE,2);

                                  ^

sketch\TFTLIB.H: In function 'void Manual_Recaliberation()':

sketch\TFTLIB.H:189:63: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

     draw_text("Touchscreen \n   Recaliberation",60,100,WHITE,2);

                                                               ^

sketch\TFTLIB.H:191:39: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

     draw_text("STEP 1",100,200,WHITE,2);

                                       ^

sketch\TFTLIB.H:192:60: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

     draw_text("Please touch the BLUE dot...",40,250,WHITE,1);

                                                            ^

sketch\TFTLIB.H:198:63: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

     draw_text("Touchscreen \n   Recaliberation",60,100,WHITE,2);

                                                               ^

sketch\TFTLIB.H:200:39: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

     draw_text("STEP 2",100,200,WHITE,2);

                                       ^

sketch\TFTLIB.H:201:59: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

     draw_text("Please touch the RED dot...",40,250,WHITE,1);

                                                           ^

sketch\TFTLIB.H:209:63: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

     draw_text("Touchscreen \n   Recaliberation",60,100,WHITE,2);

                                                               ^

sketch\TFTLIB.H:211:39: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

     draw_text("STEP 3",100,200,WHITE,2);

                                       ^

sketch\TFTLIB.H:212:62: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

     draw_text("Please touch the YELLOW dot...",40,250,WHITE,1);

                                                              ^

sketch\TFTLIB.H:224:61: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

     draw_text("Recaliberation \n    Complete",30,100,WHITE,2);

                                                             ^

sketch\TFTLIB.H:227:36: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]

     draw_text("BACK",20,225,WHITE,2);

                                    ^

In file included from C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_Adafruit_TFTLCD.cpp:30:0:

C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\pin_magic.h:306:33: warning: backslash and newline separated by space [enabled by default]

   #define read8inline(result) { \

 ^

In file included from C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/pins_arduino.h:20:0,

                 from C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:6:

C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp: In member function 'TSPoint TouchScreen::getPoint()':

C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:63:65: error: invalid conversion from 'Pio*' to 'uint8_t {aka unsigned char}' [-fpermissive]

 #define digitalPinToPort(P)        ( g_APinDescription[P].pPort )

                                                                 ^

C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:61:21: note: in expansion of macro 'digitalPinToPort'

   uint8_t xp_port = digitalPinToPort(_xp);

                     ^

C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:63:65: error: invalid conversion from 'Pio*' to 'uint8_t {aka unsigned char}' [-fpermissive]

 #define digitalPinToPort(P)        ( g_APinDescription[P].pPort )

                                                                 ^

C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:62:21: note: in expansion of macro 'digitalPinToPort'

   uint8_t yp_port = digitalPinToPort(_yp);

                     ^

C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:63:65: error: invalid conversion from 'Pio*' to 'uint8_t {aka unsigned char}' [-fpermissive]

 #define digitalPinToPort(P)        ( g_APinDescription[P].pPort )

                                                                 ^

C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:63:21: note: in expansion of macro 'digitalPinToPort'

   uint8_t xm_port = digitalPinToPort(_xm);

                     ^

C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:63:65: error: invalid conversion from 'Pio*' to 'uint8_t {aka unsigned char}' [-fpermissive]

 #define digitalPinToPort(P)        ( g_APinDescription[P].pPort )

                                                                 ^

C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:64:21: note: in expansion of macro 'digitalPinToPort'

   uint8_t ym_port = digitalPinToPort(_ym);

                     ^

C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:66:44: error: base operand of '->' is not a pointer

 #define portOutputRegister(port)   ( &(port->PIO_ODSR) )

                                            ^

C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:77:4: note: in expansion of macro 'portOutputRegister'

   *portOutputRegister(yp_port) &= ~yp_pin;

    ^

C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:66:44: error: base operand of '->' is not a pointer

 #define portOutputRegister(port)   ( &(port->PIO_ODSR) )

                                            ^

C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:78:4: note: in expansion of macro 'portOutputRegister'

   *portOutputRegister(ym_port) &= ~ym_pin;

    ^

C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:66:44: error: base operand of '->' is not a pointer

 #define portOutputRegister(port)   ( &(port->PIO_ODSR) )

                                            ^

C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:86:4: note: in expansion of macro 'portOutputRegister'

   *portOutputRegister(xp_port) |= xp_pin;

    ^

C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:66:44: error: base operand of '->' is not a pointer

 #define portOutputRegister(port)   ( &(port->PIO_ODSR) )

                                            ^

C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:87:4: note: in expansion of macro 'portOutputRegister'

   *portOutputRegister(xm_port) &= ~xm_pin;

    ^

C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:66:44: error: base operand of '->' is not a pointer

 #define portOutputRegister(port)   ( &(port->PIO_ODSR) )

                                            ^

C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:102:5: note: in expansion of macro 'portOutputRegister'

    *portOutputRegister(xp_port) &= ~xp_pin;

     ^

C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:66:44: error: base operand of '->' is not a pointer

 #define portOutputRegister(port)   ( &(port->PIO_ODSR) )

                                            ^

C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:106:5: note: in expansion of macro 'portOutputRegister'

    *portOutputRegister(yp_port) |= yp_pin;

     ^

C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:66:44: error: base operand of '->' is not a pointer

 #define portOutputRegister(port)   ( &(port->PIO_ODSR) )

                                            ^

C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:125:5: note: in expansion of macro 'portOutputRegister'

    *portOutputRegister(xp_port) &= ~xp_pin;

     ^

C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:66:44: error: base operand of '->' is not a pointer

 #define portOutputRegister(port)   ( &(port->PIO_ODSR) )

                                            ^

C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:129:5: note: in expansion of macro 'portOutputRegister'

    *portOutputRegister(ym_port) |= ym_pin;

     ^

C:\Users\Arun Baby\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.9\variants\arduino_due_x/variant.h:66:44: error: base operand of '->' is not a pointer

 #define portOutputRegister(port)   ( &(port->PIO_ODSR) )

                                            ^

C:\Users\Arun Baby\Documents\Arduino\libraries\SPFD5408-master\SPFD5408_TouchScreen.cpp:133:5: note: in expansion of macro 'portOutputRegister'

    *portOutputRegister(yp_port) &= ~yp_pin;

     ^

Is it actually true? Is SPFD5408 completely incompatible with Due?
Trying out UTFT Library with Due gave errors and with Uno, Blank white screen.
Is there any library that is compatible with Due then?

Yes, that is true. It looks like it tries to do some low-level port manipulation for speed, but it doesn't know how to do that on a Due since it's a completely different beast.
You could always read the datasheet and look at the initialisation code (the hardest part to work out yourself) and roll your own code to control the TFT - it's not actually that hard usually.

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


text:
Building a GPS-controlled Camera
I've been trying to build an Arduino UNO controlled Camera using two servo motors that points in the direction of an object with a certain tag.
Here's an Example: A camera is on the sideline of a gym, and the players are running around. One player has a portable GPS piece attached to him, and the camera should point in the player's direction in order to capture the player's movements along with his background.
A few questions:
Would I use two different compasses in order to both record the direction and point the camera in this direction? Or would I use a GPS for the player and somehow convert the streaming data into compass direction(in which the camera will point)?
In a way, what combination (Player-Camera) would I use (if I need a combination), a GPS-GPS, GPS-compass, or compass-compass?
Do I actually need two location devices or just one?
Thanks,
Mark

You should be aware of the accuracy of GPS, especially indoors. For consumer-grade products, it may not be enough for this project.

I agree with @Sanchises, unless you are going for a wide photo the resolution of GPS is about 10m.  You might be better using multiple directional radio signal sensors and triangulating the position, or if you have a camera with auto focus and no intervening objects you might be able to get a way with one directional radio sensor.  In either case you would need to do some reflection processing to cancel out the signal on the player bouncing off the gym walls.  Might it be better to look at the Pixy cam and visually track the 'player'?

A compass would be useless on the player. Whether the player is face towards or away from the camera, the camera should point in the same direction in either case.

you probably may want to look into this: http://sports.stackexchange.com/q/4996

Take a look at the uTube site of "iforce2d". Chris has a couple of GPS projects, which use a GPS and nRF24L01 transceivers to implement a "GPS tag" and he has a model car follow the tag. He also has a ground station with a pan and tilt and a camera following his quadcopter (drone). Lots of useful stuff there.

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


text:
slave arduino receiving commands from two serials
I have a slave arduino connected to a master arduino mega (through UART) and to a RPi (through USB). The slave arduino is set to monitor various SHT85 (through I2C) and NTC sensors. What I would like to do is to have the slave arduino respond to both commands from the master and the RPi.
The code I have works ok for the NTCs but it is sometimes problematic for the SHT sensors. From times to times (every ~10 minutes) some of the sensors do not send back all requested bytes. The functions I am using to write and read are the following:
//
// I2C write
void cmdI2Cwrite(int address, char *cmd) {
  Wire.beginTransmission(address);

  int c = 0;
  for (int i = 0; i < strlen(cmd); i += 2) {
    sscanf(&cmd[i], "%02x", &c);
    Wire.write(c);
  }

  if (Wire.endTransmission() != 0) {
    MySerial->println(F("end trasmission failed"));
  }

  if(address == 112)
  {
    if(cmd[1] == '0')
    {
      MySerial->println(F("OK - unlocked"));
      IsLocked = false;
      }
    else
    {
      MySerial->println(F("OK - locked"));
      IsLocked = true;
    }
  }
  else
  {
    MySerial->println(F("OK"));
  }
}

and for read:
// I2C read
void cmdI2Cread(int address, unsigned int nBytes) {
  delay(15);
  Wire.requestFrom(address, nBytes);

  unsigned char c;
  char cstr[4];

  // check if the same number of bytes are received that are requested.
  if (Wire.available() != nBytes) {
    MySerial->println("Requested bytes not returned");
  }

  for (unsigned int i = 0; i < nBytes; i++) {
      c = Wire.read();
      sprintf(cstr, "%02x", c);
      MySerial->print(cstr);
  }
  MySerial->println();
}

The command: Wire.available() != nBytes is sometimes satisfied and basically I receive no response from the SHT
Both the master and Rpi serials are set to a baud rate of 115200.
I have tried changing cables, shielding cables, reducing the baud rate, implementing some kind of lock mechanism
the problem doesn't seem to appear when I disconnect either the RPi or the master from the slave (so it seems there is some kind of cross talk.. not sure)
Any help would be appreciated
Thank you

the code is incomplete ... it does not compile

which arduino are you using? ... first thing to try when facing communication problems is to reduce the baud rate

Hello,
Thank you for your reply! You are right the code is incomplete! The problem is that the it's rather long and it's a bit complicated to provide a working version here. But the main loop of the slave code where the communication switch from master arduino to rpi occurs should be shared

I am using arduino mega 2560
I have tried decreasing the baud rate for both serials to 9600 and I still get the same issue

Sounds like you're using the same UART pins on your secondary arduino for communicating with the RPi and the primary arduino mega. The USB serial chip is connected to the RX/TX pins a.k.a. UART0 on an arduino. If you've got a Uno/Nano/Mini as a secondary arduino, you'll need SoftwareSerial on different pins to avoid crosstalk (two "clients" on an TX line may pull down the signal too much due to parallel pulldown resistors).


text:
How to Send GPS Data to Firebase via SIM808 GSM Module
I have an Arduino UNO with SIM808 and I'm trying to send my GPS data to the Firebase. I have successfully get a location from SIM808 via serial. However I found that Arduino only supported HTTP communication while the Firebase accepted only HTTPS requests. How can I connect them (Arduino and Firebase) so I can send data to Firebase. Any guide and help can help me a lot thank you so much :)

don't use an Arduino UNO for the project


text:
Connecting Arduino Mega 2560 to Python with PyFirmata
I am currently controlling two servos using the Arduino IDE, but now need to integrate my Arduino code into a Python script. I read about how to use PyFirmata and went through the process of uploading StandardFirmata to my Arduino Mega 2560 board after changing the samplingInterval value to 99, instead of the default 19. However, having followed the exact procedure of translating Arduino code to Python and downloading/using the correct pyfirmata package, the board simply does not react. I tested the board, the individual servos, power, etc. and have even used the ArduinoMega module in pyfirmata, but there is absolutely no reaction when using the Python code. I have looked through multiple online forums and it seems that this is a recurring issue, but no one has posted a solution (as per my knowledge) to the problem and it would be of great help if someone could help me fix this. Please let me know if you would like to see any of the code, it is very simple and I do not mind sharing it if required. Thanks in advance!

Some code sure help to understand the issue. Also, you can send some predetermined commands from Python to Arduino through a serial port to make your Arduino do what it is supposed to do. You don't necessarily need PyFirmata if your case is simple servo control.

Before uploading StandardFirmata to Arduino check baud rate in StandardFirmata sketch at line Firmata.begin()


text:
connecting 5 mq sensor at a time
I want to take a reading from 5 different mq sensor at a time. do I need an external power source to power these sensors or it will be ok to power sensors from 5v available from the board? I am using arduino uno board .

How much current does each sensor draw?

@VE7JRO     maximum current drawn by each sensor is 240 ma . I have measured using multimeter altough its power rating is given as 800 mw .

I only had experience with the MQ2 sensor (more info here), so I'm going to use it as an example. If you have different sensors double check their datasheets.
Now, the main current consumption for these comes from the heater. Can you turn the heater off to save some power? Apparently not, since they say that

Please note that the best preheat time for the sensor is above 24
  hours.

So, for the moment, let's consider all five sensors turned on at the same time.
The heater specs say that its resistance is around 33 ohm +/- 5% in the worst case this means 31.35 ohms. At 5V, this means 160mA for each sensor. Five of them are 800mA, and then let's add something like 50mA for the rest of the circuit (just a random number, and highly depends on the rest of the circuit).
Now, how is the UNO powered? If it is powered from the USB, the maximum current you can draw is 500mA (so 850mA is not allowed). So.. No powering from USB. If, on the other hand, the board is powered by the barrel jack, the onboard regulator can dissipate roughly 1-1.5W (taken from this thread). The power dissipation comes from the input voltage. With a 9V input, about 3V (slightly more) will need to be handled by the regulator. At 850mA, this means 2.5W (Not ok). In both cases you will need an external 5V power supply. With a 7V input (the very minimum you can apply) you will have to dissipate roughly 1.2V, at 850mA this means 1.02W. Please beware that this means something like 80-90°C of temperature increase in that area, so the part will become very hot. And moreover its lifespan will be reduced. So use this path only if really necessary.
If you reduce the performances and start powering just one sensor at a time (this means longer time before having it fully operational, and adding some transistor to switch them on and off) this data can change. I mean, if put a transistor to stop powering it, and then turn on one sensor at a time, you will be able to reduce the maximum current consumption to 210mA.
This means that you will be able to get power from the USB port; moreover you will be able to use the external power connector for voltages up to 10.5V (0.8V on the diode, so 4.7V on the regulator - around 1W). This comes at a price, of course: the heater will work for 1/5 of the time, so it will be harder to reach the temperature required for the measurement

160 ma is the maximum requirement. For safer side, if I take 120 ma per sensor that is total 720 ma. Now can I use an external power source whose output is 5v and power rating is 3500 mw or around this? . One more doubt is that although I will provide the external power source to sensors for input but, will there be any problem for Arduino due to input from all six sensors at the same time which may exceed its input capacity?

@r0000 You can also assume 100mA per sensor. Even 10mA. But it will be wrong. Usually a designer makes designs in the worst case, which in this case is 160mA. If you use the nominal value, it is 152mA. But this will be an underestimation, and may result in bad working. As I told you, if you want to dimension it, assume 850mA. At 5V, this means 4.25W. Your 3.5W will be undersized. As for the inputs, the UNO has six inputs so six sensors are feasible


text:
Control/Interacting with Android OS using Arduino board
I am new to arduino, and based on my search, it is possible to connect Android devices and Arduino board thru bluetooth module. But most solutions i found are either for controlling Arduino board using an Android app, or controlling Android app using Arduino board.
My question is, is there a way to control/interact with the Android OS on the phone using Arduino, thru whatever connection?
I am asking this because I am thinking of building a portable keyboard or touchscreen device for Android devices, and want to see if Arduino is a good platform for prototype.

What do you mean "thru whatever connection"?

Whatever = TCP/IP?

@gre_gor so can be bluetooth, usb, wifi, wifi direct, etc.

@MatsK that can work, but i guess it is part of wifi or cellular connection?

There is wifi and cellular add-ons to Arduino that can have a TCP/IP stack and thereby you can have a program that is agnostic to what coimmunication layer you have.

What you've seen is most usually a bluetooth module which has a "virtual COM port" service -- you connect to the bluetooth module and you can then send a data stream up and down through this COM port, just like you are able to do with a normal Serial port.
If you want a bluetooth keyboard:
What you want for seamless integration is a bluetooth module which natively exposes a "HID" (Human Interface Device) profile. Keyboard, mice and gamepads are examples of an HID.
There is a multitude of projects which use Arduino + Bluetooth HID module:

http://www.kobakant.at/DIY/?p=3310 uses an Arduino Pro Mini and and BlueSMiRF HID (from Sparkfun)
Evan Kale's video: https://www.youtube.com/watch?v=BBqsVKMYz1I (uses HC05 bluetooth module with altered firmware)
https://mitxela.com/projects/bluetooth_hid_gamepad
Bluefruit EZ-Key: https://www.adafruit.com/product/1535

When you are a beginner you should buy the more expensive modules which don't require you to do any firmware hacking. Adafruit's product might work for you. As the description page says, you can connect a microcontroller's UART TX to the modules RX pin to send arbitrary keystrokes. You can then add a keyboard matrix, or lots of buttons, or whatever you desire to that microcontroller to make it trigger the keypresses you want.
This should get you started on your own research.

super detailed thanks! what about touchscreen device, is that considered as HID too?

I have never seen remote touchscreens or displays on Android. I am not sure if it is possible to connect a new screen to an Android wirelessly.


text:
Why do we need a transistor with a dc motor while we don't need one with a servo motor?
I was wondering why do we need to attach a transistor as we don't need one while we connect the Arduino with the servo motors. I am using mini servos.

A servo typically has 3 wires: Power, Ground, and Signal
Inside the servo are a bit of electronics that read the input signal duty cycle, the absolute position of the horn, and power the motor in forward or reverse accordingly. There are transistors inside the servo housing to handle the high current of the motor.
A standalone motor doesn't have any other control electronics that separate power from control inputs.
EDIT:
Just to clarify: the signal wire for the Servo doesn't carry any significant power. The IO pins on the Arduino should not be asked to provide more than 40mA of current, and the PWM signal to the servo falls under that current limit.
But to operate a motor, or other device which draws significant operating power, it (the motor) asks for much more than 40mA of current, which can burn out the IO pin and damage it forever. This is why a transistor or other "switch" is necessary: the device which switches the high-current on and off can itself be operated by a very low current.

Because a servo contains a driver circuit that controls the motor portion, whereas a motor doesn't. The transistor is the (simplistic) driver circuit for the motor.


text:
Clock generator up to 8 MHz using pin 3 arduino nano
I would like to generate square signal up to 8 MHz using internal timer of arduino, I have done successfully in pin 11, but i want to change it in pin 3, but still stuck. Here is the code
 pinMode(11,OUTPUT);

 TCCR2A = ((1 << WGM21) | (1 << COM2A0));
 TCCR2B = (1 << CS20); // prescaler = 1
 TIMSK2 = 0;
 OCR2A = 1;

from this page here
How can i change the pin to pin 3?
Thank you

The MCU Timer Outputs are hardwired to specific pins. Arduino Nano (ATmega328p) pin 3 is the MCU pin PD3 and may be connected to Timer 2 output logic, OC2B with Output Compare Register 2B (OCR2B). Waveform Generator Mode and Timer Clock prescale are the same as above.
 pinMode(3,OUTPUT);

 TCCR2A = ((1 << WGM21) | (1 << COM2B0));
 TCCR2B = (1 << CS20); // prescaler = 1
 TIMSK2 = 0;
 OCR2B = 1;

Cheers!

You should also set OCR2A, as it defines the TOP value of the counter in CTC mode, which is the mode being used here.


text:
Generate single pulse from timer 1 in arduino nano
i have a code that shot a single pulse from pin D5 timer 0 (based on josh levine code), it works fine. the code is below
#define OSP_SET_WIDTH(cycles) (OCR0B = 0xff-(cycles-1))
void osp_setup(uint8_t cycles) {
    TCCR0B =  0;
    TCNT0 = 0x00;
    OCR0A = 0;
    OSP_SET_WIDTH(cycles);
    TCCR0A = _BV(COM0B0) | _BV(COM0B1) | _BV(WGM00) | _BV(WGM01);
    TCCR0B = _BV(WGM02) | _BV(CS00);
    DDRD |= _BV(5);
}

void osp_setup() {
    osp_setup(1);
}

#define OSP_FIRE() (TCNT0 = OCR0B - 1)
#define OSP_INPROGRESS() (TCNT0>0)
#define OSP_SET_AND_FIRE(cycles) {uint8_t m=0xff-(cycles-1); OCR0B=m;TCNT0 =m-1;}

void setup()
{
    osp_setup();
}

void loop()
{
    OSP_SET_AND_FIRE(4);
    delayMicroseconds(20);
}

however, i want to generate the same pulse in pin 10 or 9 which is timer 1, so a change the code a bit just like this
#define OSP_SET_WIDTH(cycles) (OCR1B = 0xff-(cycles-1))
void osp_setup(uint8_t cycles) {
    TCCR1B =  0;
    TCNT1 = 0x00;
    OCR1A = 0;
    OSP_SET_WIDTH(cycles);
    TCCR1A = _BV(COM1B0) | _BV(COM1B1) | _BV(WGM10) | _BV(WGM11);
    TCCR1B = _BV(WGM12) | _BV(CS10);
    DDRD |= _BV(10);
}

void osp_setup() {
    osp_setup(1);
}

#define OSP_FIRE() (TCNT1 = OCR1B - 1)
#define OSP_INPROGRESS() (TCNT1>0)
#define OSP_SET_AND_FIRE(cycles) {uint8_t m=0xff-(cycles-1); OCR1B=m;TCNT1 =m-1;}

void setup()
{
    osp_setup();
}

void loop()
{
    OSP_SET_AND_FIRE(4);
    delayMicroseconds(20);
}

but it doesn't work, and i am stuck, any help? i use arduino nano
Thank you

what does this mean? ... it doesn't work

Did you just change the 0s with 1s? You can’t do that as the registers for timer1 are a bit different from timer 0. Check the datasheet to see what the original code does. The look in the datasheet and see which bits need to be set in which registers to get the same functionality.

@jsotola it didn't generate the desired signal

@Gerben that is because when i change the 0s with 2 and use pin D3, it works fine

@ZahiAzmi, it didn't generate the desired signal that is almost the same as it doesn't work .... what did it generate?

@jsotola , it should generate a single pulse signal but nothing generated, just 0 volt all the time

Both timer0 and timer2 are 8-bit timers. Their registers are almost identical. Timer1 is a 16-bit timer and has some additional functions. So it's registers are a bit different.

Timer1 has a few extra features, so you need to set the registers slightly differently from timer0 (or timer2). You need to also set the WGM13 bit in the TCCR1B register.
Since timer1 is a 16 bit timer, you need to change OSP_SET_AND_FIRE to also use 16 bits.
Lastly; Arduino pin 10 is port B, not port D.
#define OSP_SET_WIDTH(cycles) (OCR1B = 0xff-(cycles-1))
void osp_setup(uint8_t cycles) {
    TCCR1A = 0;
    TCCR1B = 0;
    TCNT1 = 0x00;
    OCR1A = 0;
    OSP_SET_WIDTH(cycles);
    TCCR1A = _BV(COM1B0) | _BV(COM1B1) | _BV(WGM10) | _BV(WGM11);
    TCCR1B = _BV(WGM12) | _BV(WGM13) | _BV(CS10);
    DDRB |= _BV(DDB2);//pin 10; PB2
}

void osp_setup() {
    osp_setup(1);
}

#define OSP_FIRE() (TCNT1 = OCR1B - 1)
#define OSP_INPROGRESS() (TCNT1>0)
#define OSP_SET_AND_FIRE(cycles) {uint16_t m=0xffff-(cycles-1); OCR1B=m;TCNT1 =m-1;}

void setup()
{
    osp_setup();
}

void loop()
{
    OSP_SET_AND_FIRE(4);
    delayMicroseconds(20);
}


text:
Looking for learning resources to teach the "principles" rather than "follow this" projects
I just got the Arduino starter kit as my background is software developer (C++, python, etc) and I'm interested to get into the electronics side, and I love LED effects and home automation of all kinds.
As such I'm quite comfortable with the type of C programming required (loops etc) but need to learn the principles of electronics.
Can you suggest any resources (websites, tutorials, books - I'm willing to pay for books if they are useful) whose focus is teaching the principles as well as doing specific projects?
The kit came with the "Arduino Projects Book" but I don't really like it as it's focused on "do this, do that, put the circuit together according to this diagram" rather than explaining the principles first. For example I did the "Spaceship Interface" (light up different LEDs in different patterns based on whether a button is pushed or not) and it introduces things like "You'll also need to add a 10k ohm resistor from ground to the switch pin that connects to the Arduino [...] it connects the pin to ground when the switch is open so it reads LOW when there is no voltage coming in through the switch". I understand that in principle I think, but why is it 10kohm, why do we have to connect it using a resistor when the switch is open, etc. (I see that we have to have a complete circuit and I'm assuming it is because the 10kohm is a "default" branch of most resistance with nothing else connected?)
I'm asking about general principles rather than the specific case of why do we have a 10kohm resistor in this case, but this is a pretty good example early in the book.

Google is your best option! It's free and all is there. If you don't understand something, post a question on this Q&A site and maybe we can help you!

Meet your new bible.

I see people are voting to close this as too broad. Well, it is broad, but I'll try to give you some pointers. I used to wonder this stuff too, like "why use 10k and not 20k or 5k?". A good starting point is to watch some of Dave Jones' EEVblog videos.
For example Designing a Li-Ion Battery Gauge with the LM3914 - EEVblog #204 - this is already 5 years old. He has done a lot of them. This particular one describes using the LM3914 chip to make a battery gauge, and in the middle he works through the resistor values using Ohm's Law.
Another entertaining and informative blog is Afrotechmods. He also goes into detail but in a humorous way.
Also try M J Lorton's blog.
My only problem with videos is, if you are trying to reproduce some of their stuff you end up having to rewatch a (perhaps lengthy) video and pause it from time to time to copy stuff off the screen.
For this reason I made some posts of my own on the Electronics part of my own forum. (Some of the more popular ones are also here in Stack Exchange as reference questions, for example How do you use SPI on an Arduino?).
You could also look at the Adafruit and Sparkfun tutorials (amongst many others).


text:
Visual Studio for Arduino - Deep Search Issue
Finally got some time to play with my Arduino. I downloaded the Arduino editor and wrote a quick sketch which worked fine.
I then downloaded the Visual Studio extension from  VisuaMicro. I configured it to point towards my Arduino directory, which in my case is : C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt
I created a new Arduino project and copied the same sketch it. When I try to build it I get errors as below:
Compiling debug version of 'Sketch1' for 'Arduino/Genuino Uno'
Build Folder:
file:///C:/Users/bbbsb/AppData/Local/Temp/VMBuilds/Sketch1/uno/Debug
Additional Defines: VM_DEBUG;VM_DEBUG_ENABLE
1;VM_DEBUG_BANDWIDTH_THROTTLE_MS 50;VM_DEBUGGER_TYPE_HARDWARESERIAL
0;VM_DEBUGGER_TYPE_SOFTWARESERIAL 1;VM_DEBUGGER_TYPE_FASTSERIAL
2;VM_DEBUGGER_TYPE_USB 3;VM_DEBUGGER_TYPE_TEENSY 4;VM_DEBUGGER_TYPE_UART
5;VM_DEBUGGER_TYPE_USART 6;VM_DEBUGGER_TYPE_USBSERIAL
7;VM_DEBUGGER_TYPE_TTYUART 8;VM_DEBUGGER_TYPE_NET_CONSOLE
9;VM_DEBUGGER_TYPE_Uart 10;VM_DEBUGGER_TYPE_COSA
11;VM_DEBUGGER_TYPE_CDCSerialClass 12;VM_DEBUGGER_TYPE_HARDWARESERIAL1
13;VM_DEBUGGER_TYPE_HARDWARESERIAL2 14;VM_DEBUGGER_TYPE_HARDWARESERIAL3
15;VM_DEBUGGER_TYPE_NET_UDP 16;VM_DEBUGGER_TYPE_USBAPI
17;VM_DEBUGGER_TYPE_SERIALUSB 18;VM_DEBUGGER_TYPE
VM_DEBUGGER_TYPE_HARDWARESERIAL;VM_DEBUG_BREAKPAUSE;
Architecture Tools:
file:///C:/Program%20Files/WindowsApps/
ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt/hardware/tools/avr/bin/
Api: 1.1706.25-9.061
Sketch Book: file:///C:/Users/bbbsb/Documents/Arduino
Sketch Include Paths
Core Include Paths
Include Path     file:///C:/Program%20Files/WindowsApps/ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt/hardware/arduino/avr/cores/arduino
Include Path     file:///C:/Program%20Files/WindowsApps/ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt/hardware/arduino/avr/variants/standard
Searching for libraries ...
"C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\hardware\tools\avr\bin\avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -flto -w -x c++ -E -CC -mmcu=atmega328p -DVM_DEBUG_BREAKPAUSE -
DVM_DEBUGGER_TYPE=VM_DEBUGGER_TYPE_HARDWARESERIAL -
DVM_DEBUGGER_TYPE_SERIALUSB=18 -DVM_DEBUGGER_TYPE_USBAPI=17 -
DVM_DEBUGGER_TYPE_NET_UDP=16 -DVM_DEBUGGER_TYPE_HARDWARESERIAL3=15 -
DVM_DEBUGGER_TYPE_HARDWARESERIAL2=14 -DVM_DEBUGGER_TYPE_HARDWARESERIAL1=13 -
DVM_DEBUGGER_TYPE_CDCSerialClass=12 -DVM_DEBUGGER_TYPE_COSA=11  -
DVM_DEBUGGER_TYPE_Uart=10 -DVM_DEBUGGER_TYPE_NET_CONSOLE=9 -
DVM_DEBUGGER_TYPE_TTYUART=8 -DVM_DEBUGGER_TYPE_USBSERIAL=7 -
DVM_DEBUGGER_TYPE_USART=6 -DVM_DEBUGGER_TYPE_UART=5 -
DVM_DEBUGGER_TYPE_TEENSY=4 -DVM_DEBUGGER_TYPE_USB=3 -
DVM_DEBUGGER_TYPE_FASTSERIAL=2 -DVM_DEBUGGER_TYPE_SOFTWARESERIAL=1 -
DVM_DEBUGGER_TYPE_HARDWARESERIAL=0 -DVM_DEBUG_BANDWIDTH_THROTTLE_MS=50 -
DVM_DEBUG_ENABLE=1 -DVM_DEBUG   -DF_CPU=16000000L -DARDUINO=10805  -
DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -I"C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\cores\arduino" -I"C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\variants\standard" "C:\Users\bbbsb\AppData\Local\Temp\VMBuilds\Sketch1\uno\Debug\Sketch1.cpp" -o "nul"
Access is denied
Preprocess: "C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\hardware\tools\avr\bin\avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -flto -w -x c++ -E -CC -mmcu=atmega328p -DVM_DEBUG_BREAKPAUSE -
DVM_DEBUGGER_TYPE=VM_DEBUGGER_TYPE_HARDWARESERIAL -
DVM_DEBUGGER_TYPE_SERIALUSB=18 -DVM_DEBUGGER_TYPE_USBAPI=17 -
DVM_DEBUGGER_TYPE_NET_UDP=16 -DVM_DEBUGGER_TYPE_HARDWARESERIAL3=15 -
DVM_DEBUGGER_TYPE_HARDWARESERIAL2=14 -DVM_DEBUGGER_TYPE_HARDWARESERIAL1=13 -
DVM_DEBUGGER_TYPE_CDCSerialClass=12 -DVM_DEBUGGER_TYPE_COSA=11 -
DVM_DEBUGGER_TYPE_Uart=10 -DVM_DEBUGGER_TYPE_NET_CONSOLE=9 -
DVM_DEBUGGER_TYPE_TTYUART=8 -DVM_DEBUGGER_TYPE_USBSERIAL=7 -
DVM_DEBUGGER_TYPE_USART=6 -DVM_DEBUGGER_TYPE_UART=5 -
DVM_DEBUGGER_TYPE_TEENSY=4 -DVM_DEBUGGER_TYPE_USB=3 -
DVM_DEBUGGER_TYPE_FASTSERIAL=2 -DVM_DEBUGGER_TYPE_SOFTWARESERIAL=1 -
DVM_DEBUGGER_TYPE_HARDWARESERIAL=0 -DVM_DEBUG_BANDWIDTH_THROTTLE_MS=50 -
DVM_DEBUG_ENABLE=1 -DVM_DEBUG   -DF_CPU=16000000L -DARDUINO=10805 -
DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -I"C:\ProgramFiles\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\cores\arduino" -I"C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\variants\standard" "C:\Users\bbbsb\AppData\Local\Temp\VMBuilds\Sketch1\uno\Debug\Sketch1.cpp" -o "nul"
Object reference not set to an instance of an object

An error was encountered during the 'Deep Search' library discovery process.

Debug build failed for project 'Sketch1'
I've obviously not setup something correctly but cnnot work out what?
Any ideas?

I suspect that the problem is that you're using the Windows App Store version of the Arduino IDE. Windows puts some strange restrictions on the C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.10.0_x86__mdqgnx93n4wtt folder that the Windows Store version of the Arduino IDE is installed to. Please try uninstalling this App thing and instead use the standard IDE downloaded from https://www.arduino.cc/en/Main/Software.

I had the same problem and just tried it as per1234 suggested: installed the full windows version (not the windows app version), configured the VS extension accordingly and now it builds (same code).

If I remember well, you have to "import" the libraries for your project from within Visual Micro.


text:
Alternative code for pinMode()?
In my code I need to set five pins to output mode. I have the pinMode() statements in my setup.
I am trying to make my Arduino code run a bit faster, and I came across a tutorial which swaps digitalWrite() for PORTB &= _BV(PB6) (high), and makes it run ~25 times faster.
I'm wondering if there's a similar type of substitution I can do for pinMode(), that will make it run faster as well? Or is pinMode() already a fast command, so I shouldn't worry about it?
Thanks

Things inside the setup are only done once, so optimizing those is rarely worth the trouble, replacing digital writes and reads (which are done often) will have more effect overall.

It isn't worth it for something done once, if you only do it in setup. However if you need to toggle the mode frequently yes it can be done. You sadly haven't said which pins, but assuming they are D2 to D6 (digital pins 2 to 6) on a Mega you can do this to set output mode:
  DDRE |= bit(PE3) | bit(PE4) | bit(PE5); // D5, D2, D3
  DDRG |= bit(PG5); // D4
  DDRH |= bit(PH3); // D6

For input mode you have to "and" in the ones-complement of the bits like this:
  DDRE &= ~(bit(PE3) | bit(PE4) | bit(PE5)); // D5, D2, D3
  DDRG &= ~(bit(PG5)); // D4
  DDRH &= ~(bit(PH3)); // D6

The exact register names are in the datasheet, and the mappings to the pins on your board are in the schematic (available from the Arduino site). The relevant part is this:

The bit numbers are in grey on the left (eg. PE4) and the board pin numbers are in green on the right (eg. 2 is digital pin 2).
The bit macro works similarly to the _BV one you mentioned in your question. It shifts 1 left the required number of bit positions to be in the right place.

A somewhat simpler and more portable solution is to use the digitalWriteFast library which you can download from:
https://github.com/NicksonYap/digitalWriteFast
This uses various compiler tricks to detect if you are using a constant for pinMode and digitalWrite and converts them into the appropriate register manipulation. You just install the library and add Fast to the function names, eg.
pinModeFast (2, OUTPUT);
digitalWriteFast (2, HIGH);

yeah. the corresponding registers are DDRx.
with a little bit of coding, you can easily convert pinMode() to your own, say, mypinMode() that operates on the DDRx directly.
the datasheet is your best friend, as always.

The Arduino reference manual has all you need to know:

https://www.arduino.cc/en/Reference/PortManipulation

The register you need is the DDRx register (Data DiRection X). Set a bit to 1 for output and 0 for input.


text:
How to send information from Arduino?
I plan to make an air quality monitoring system that uses Arduino uno, but I can't decide how I will be able to distribute the air condition and harmful gas concentration info and have it available to other people.
Aside from using a GSM module to text individual persons and making a new website to chart the data from the Arduino, what else can I use to receive information that my Arduino sensed to people's smartphones/computers wirelessly?

what else can I use to receive information that my Arduino sensed to people's smartphones/computers wirelessly?

take a different route. get the information to a pc (or to a server through a pc) and you have much more flexibility.
there are many ways to get that information to a pc, like serial, spi, i2c, acquisition cards, wired / wireless, ....

You can use a pair of ESP8266 WiFi Transceiver modules (one as the client and the other as the server).
There are a few guides to getting started with the ESP8266 out there, which generally contain some helpful tips.
I also found this fairly straightforward ESP8266 – Wireless Weather Station with Data Logging to Excel project which illustrates the principle of using a pair of ESP8266 modules as client and server.

Others suggest ESP8266, but I think it's now outdated, there's a new and improved version of it available named ESP32, it's better in basically every way (faster, more RAM, ROM etc.), not that much more expensive and can still be programmed using the Arduino IDE, that means programming it just as simple as programming an ESP8266.
Disclaimer: ESP32 Arduino core is still under development, some less frequently used features might be experimental or missing.

There is a Wi-Fi module named "ESP-01" (which uses the ESP8266 microcontroller) and it comes ready to be used with Arduino. But better than that, I think, is that you can program it directly via Arduino's IDE if you flash it with NodeMCU's firmware. You can also use a NodeMCU instead of Arduino, but ESP-01 has the advantage of being much, much cheaper.


text:
connecting multiple keypads
My project is to use an Arduino to control the lighting of a small apartment. My preferred option is to replace each wall light switch with a 4x4 membrane keypad (https://www.amazon.co.uk/Mirocle-Matrix-Membrane-Keyboard-Arduino/dp/B01LMU6OPG/ref=sr_1_19?s=electronics&ie=UTF8&qid=1504376458&sr=1-19&keywords=membrane+keypad). The UX would allow any keypad to control any light, eg. pressing 1-4 will set light 1 to brightness 4.
The problem I have is this will result require 4 x 8 = 32 pins, so I'm looking for alternatives.
So my questions:-
1/ Is there a simple pll to serial converter that I should be using to interface the keypads?
2/ Can I wire multiple keypads onto the same set of 8 pins? Only one keypad will ever be touched at one time.
3/ Are there simple serial versions of the classic membrane keypad.

the short answer is "because it's my apartment and that's what I want to do". The slightly longer answer is "my apartment is never pitch black, also some lights are on photocell-gated, PIR motion detectors, and also the bottom left key will turn on a light with a single press. Luckily it's not a requirement of SE that every Arduino question needs to come with a justification for the project. Notwithstanding that, thanks for sharing that you can walk around your apartment in complete darkness with the SE community. We're all enriched by that knowledge.

Or the 8 pins 4 will be connected to output pins to be enabled one at a time and 4 will be connected to input pins that get shorted to the input pins when the button is pressed.
The way to get a keypress from this will be to pull a single output pin high and then check all of the inputs, if any of them are high then the corresponding button is pressed.
If you want to treat all keypads the same then you can simply put them in parallel. If you want to treat each of them differently then you can parallel either the inputs or the outputs. But the other set needs to have a S2P or P2S shift register to get the proper data or make the correct pin high.
Though it will probably be simpler if each got their own microcontroller to poll the keypad and use a different longer range protocol to communicate to the main controller.

I will be treating all keypads the same.

As far as I know, you can connect multiple keypads of this type to a single set of 8 pins.  However, it seems like a lot of wire needs to be strung to get this to work, for each switch, 8 wires for the keypad, and two, or more, for power control.
Were I to do this project.  I would likely handle each switch independently, embedding a Pro Mini in each switch box along with an HC-12, or some such.  This means no wires are needed, any pad could control any switch, and expansion is much easier.
Of course, this is only what I would do, and you understand your own requirements far better than I.

many thx. I'm very open to alternative approaches, so I'll look into HC12. My architecture is the way it is because I want to run everything off a dedicated 12V circuit, and was trying to avoid having to distribute too much power.

@pinoyyid Good luck in your endeavour, whatever path you choose.
You will find the HC-12 to be very easy to work with, and highly reliable. I have used a few dozen with different networked projects of mine, and it is one of my favourite components.

Cool. Part of my architecture is to link the Arduinos with a controlling Raspberry. The HC-12 looks a great option for that aspect.


text:
ESP8266 error: espcomm_upload_mem failed while uploading sketch
First of all, I would like to apologize for posting this error once again to this community. However, I have been studying articles for last many days to resolve this error. Unfortunately, I did not get any solution which could resolve my problem.
Below is the error which I get when uploading a sketch (even the example sketch):
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed
Here are the connections:
Vcc - 3.3V
RST - 3.3v
CH_PD - 3.3v
Tx - Rx
Rx - Tx
GPIO0 - GND
GND - GND
I tried various combinations like Tx to Tx, Rx to Rx, pulling off GPIO0. Pulling off reset and ch_pd. Supplying external power source, supplying power directly from Arduino using 3.3V. Supplying power from Arduino 5V using an LD33V regulator. I have even tried uploading the code using USB to TTL. But every time I get exactly the same error.

Which OS you are working with?

Well, first of all you should make sure that the voltage on both Tx and Rx pins of the ESP8266 is 3.3V (the Tx and Rx voltage on Arduino is 5V). Personally, I've never succeded in using an Arduino to program the ESP (even though there are plenty of examples of this setup in the web). After a while, I just gave up and bought a converter to do the job for me (it's totally worth it).
Even so, I got this error a few times. You must keep two things in mind:

In operation mode, the CH_PD pin must be connected to 3.3V, but it won't do any harm to let it connected during the flashing, so I just soldered a wire between these two pins to make things easier.
In flashing mode, GPIO0 must be connected to GND. It won't work otherwise. I strongly recommend you using a usb converter for this, and only connect it to your computer once GPIO0 has been set to GND. This has solved this issue for me, in fact I even soldered a switch on my converter between GPIO0 and GND.

Hope this answers your question.
EDIT: Here are some photos of the setup

tried ur ways too. nothing worked :(

Have you plugged to the device to the USB port AFTER you connected GND and RST? Are you trying to supply power with the arduino, or are you using a converter? If you're using a converter, which one is it?

If you are using the arduino, also keep in mind that you must connect Tx with Tx and Rx with Rx, since you're just using it as an interface between the computer and the ESP8266.

Oh, I just noticed. I said RST and GND, it's actually GPIO0 and GND. Sorry for the mistake. It should work now. I editted the answer so others can see the right setup.

It didn't. I made a check on the voltage too. It was absolutely fine. I tried it to connect to external power supply. but didn't work. still the same error

i attempted to upload code via both ways. arduino and usb to ttl converter. and changed their connections as per the requirement.

Please verify you're choosing the right board -Generic ESP for ESP-01.


text:
How do you post json data to HTTPS endpoint from ESP8266MOD?
Board: ESP8266MOD module from AI Thinker.
Using ArduinoHttpClient I am unable to send a post message to an Azure IOT Hub endpoint. The endpoint is listening on 443 and expects a shared key passed via a custom header.
The error I get is "Connection Timed Out"
Here is the brief sketch
char serverAddress[] = "myapp.azure-devices.net";
int port = 443;
string sig = "Azure shared access signature";
HttpClient client = HttpClient(wifiClient, serverAddress, port);
  String jsonPayload = payload; // passed into this function
  client.beginRequest();
  String contentType = "application/json";
  client.post("/devices/deviceId/messages/events?api-version=2016-02-03");
  client.sendHeader(HTTP_HEADER_CONTENT_TYPE, contentType);
  client.sendHeader("Authorization", sig);
  client.sendHeader(HTTP_HEADER_CONTENT_LENGTH, jsonPayload.length());
  client.beginBody();
  client.print(jsonPayload);
  client.endRequest();

  statusCode = client.responseStatusCode();
  response = client.responseBody();

The Status Code is -3 indicating a Timeout
I then created a simple REST API that accepts the JSON. Hosted it as an Azure website on port 80.
The board is able to connect to this HTTP endpoint
Question(s):
1. Is the board underpowered to handle HTTPS?
2. Is creating an HTTP proxy the only option?
3. Am I not using the right library?
Thanks

Thanks to @Majenko I was able to find the right solution.
The resolution is here
Essentially, a secure WiFiClient needs to be created and used in the HttpClient constructor

Paste the HTTPS URL You are trying to connect to, in a browser
window and grab the SHA1 Fingerprint of the certificate
Create aninstance of WifiClientSecure
Call Connect on WifiClientSecure passing in the HTTPS URL and Port number
Upon successful connection, call the Verify method of WifiClientSecure to verify the fingerprint.
Pass the fingerprint from setp1 and URL to this method
Use the WifiClientSecure instance when creating an instance of
HttpClient.

Hope this helps.

Your link doesn't contain any resolution.

@m12lrpv check out sandeepmistry's comment in the thread. I added the steps in an attempt to clarify the comments.

You are only making an HTTP request to an HTTPS server. It's not going to work.
AFAIK there is no direct support for HTTPS in the ESP8266 libraries, but there is support for SSL, and you can then manually create an HTTP request over that - as detailed in the HTTPSRequest.ino example.

Thanks for responding. When you say "You are only making an HTTP request to an HTTPS Server", do you mean the library constructs the URL as http:// even though the port specified is 443?
If I change char serverAddress[] = "myapp.azure-devices.net"; to
char serverAddress[] = "https://myapp.azure-devices.net";
it does not work either.

Yes, I mean that the library doesn't know that 443 corresponds to HTTPS, since you can run HTTP on any port, not just 80. Also it doesn't know what HTTPS is. It only talks HTTP.


text:
How to send data from an Arduino GPRS module to a Django application hosted on Heroku?
I have a Django web application hosted on a Heroku server. Currently I am using the free package for hosting. I want to send data from an Arduino using a SIM900L GPRS module to the web application. I want to know if it is possible. I have searched for a solution but couldn't find a proper guide or example for it. My web application accepts get requests and updates values in the database when url is entered. However if the Arduino sends data using the same url I get the following error:

AT+CIPSTART="TipCP","https://.herokuapp.com",80
  ERROR

Any tested example or suggestions about what I am doing wrong or what I should be doing instead?
     void gprs(float *value1, float *value2, float *value3, float *AFR, float *value5, float *value6)
{

  String APN = "";
  String UNAME = "";
  String PWD = "";
  char fid[] = "";
  char nid[] = "";
  char s_ip[] = "https://<appname>.herokuapp.com";
  char apikey[] = "";

  wdt_reset();
  digitalWrite(A4, HIGH);
  Serial.println(F("GPRS-1 Function"));
  delay(5000);
  wdt_reset();
  delay(5000);
  wdt_reset();

  char buffer1[10];

  uint8_t GSMTries = 0;
  String res;

  //wdt_reset();
  // the below code establishes connection and if not successful
  // tries three times in total
  do {
    sendData(F("AT\r\n"), 1000, DEBUG);
    sendData(F("AT+CIPSHUT\r\n"), 2000, DEBUG);
    sendData(F("AT+CIPMUX=0\r\n"), 2000, DEBUG);

    sendData(F("AT+CSQ\r\n"), 2000, DEBUG);
    sendData("AT+CSTT= \"" + APN + "\", \"" + UNAME + "\", \"" + PWD + "\"\r\n", 2000, DEBUG);

    sendData(F("AT+CIICR\r\n"), 2000, DEBUG);
    sendData(F("AT+CIFSR\r\n"), 2000, DEBUG);

    sendData(F("AT+CSQ\r\n"), 2000, DEBUG);
    String scnt = "AT+CIPSTART=\"TipCP\",\"" ;
    scnt += s_ip ;
    scnt += "\",80\r\n" ;

    res = sendData(scnt, 10000, DEBUG);
    GSMTries++;

    wdt_reset();

  } while (((res.indexOf("ERROR") != -1) || (res.indexOf("CONNECT") == -1)) && (GSMTries < 3));
  /*
    if(res.indexOf("ERROR") != -1){
    delay(200);
    sendData(scnt, 10000, DEBUG);
    }
  */

  String api = "GET /value?apkey=" ;
  api += apikey;
  api += "&&fid=";
  api += fid;
  api += "&&nid=";
  api += nid;

  Serial.println(F("API......."));
  Serial.flush();
  Serial.println(F("here-1"));

  String Data1 = "";

  //wdt_reset();
  //Co ordinator data is compiled along with html commands
  //and sent through GPRS
  String sensor = dtostrf(*value1, 4, 2, buffer1);
  Data1.concat(api);
  Data1.concat(F("&field1="));
  Data1.concat(sensor);

  sensor = dtostrf(*value2, 4, 2, buffer1);
  Data1.concat(F("&field2="));
  Data1.concat(sensor);

  sensor = dtostrf(*value3, 4, 2, buffer1);
  Data1.concat(F("&field3="));
  Data1.concat(sensor);

  sensor = dtostrf(*AFR, 4, 2, buffer1);
  Data1.concat(F("&field4="));
  Data1.concat(sensor);

  sensor = dtostrf(*value4, 4, 2, buffer1);
  Data1.concat(F("&field5="));
  Data1.concat(sensor);

  sensor = dtostrf(*value6, 4, 2, buffer1);
  Data1.concat(F("&field6="));
  Data1.concat(sensor);

  Data1.concat(F("\r\n"));

  delay(1000);

  String cipSend = "AT+CIPSEND=";
  cipSend.concat(Data1.length());
  cipSend.concat("\r\n");
  sendData(cipSend, 8000, DEBUG);
  sendData(Data1, 8000, DEBUG);
  sendData(F("AT+CIPCLOSE\r\n"), 5000, DEBUG);
  digitalWrite(A4, LOW);

  wdt_reset();

}

The above is a part of code used in arduino to upload data to website. This code was being used before to upload data to thingspeak through its IP address and worked fine.

Why is this tagged as python?

There's a number of errors in your program regarding your understanding of basic networking:
Let's start with this bit:
String scnt = "AT+CIPSTART=\"TipCP\",\"" ;
scnt += s_ip ;
scnt += "\",80\r\n" ;

That constructs a string:
AT+CIPSTART="TipCP","https://<appname>.herokuapp.com",80

and sends it to the modem.  Now:

There is no such protocol as "TipCP" - I think you meant "TCP"
You need to provide an FQDN (Fully Qualified Domain Name), not a URL.  FQDNs don't start with "https://".  I think you meant to use "foobar.herokuapp.com" where "foobar" is the name of your application.

You then go on to form a GET request and send it.
Now: the URL you used instead of an FQDN starts with https:// - that tells me you want to be using SSL for your communications. I don't know if that is required for Heroku or not, but if it is then you cannot use AT+CIPSTART with it unless you feel like trying to implement the entirety of SSL in your program. Also you would be connecting to port 443 not port 80.
Assuming you don't need SSL fixing your protocol and FQDN may be enough. However using the AT+HTTP... commands instead of manual manipulation of a raw TCP socket may be an easier option.
If you do need SSL (and it is advisable that you do if you can) then you will have to use the SIM900's AT+HTTPS... command set (detailed here).


text:
Use ESP-01 with Arduino Uno/Nano, with the ESP8266WiFi library
There is this library - https://github.com/esp8266/Arduino
That provides a more user-friendly API for WiFi capabilities with the ESP8266.
However, all tutorials that I found so far for this library show how to program the ESP8266 (usually 12) directly. That is not what I'm looking for.
My current setup is having an Arduino Uno/Nano where the ESP8266 is connected to, say, GPIO8 and GPIO9 (RX, TX) and I use SoftwareSerial to communicate with it with AT commands. So I want to keep all the logic in my Arduino, but use ESP-01 only to provide WiFi capabilities to my Arduino.
However in that library I don't see the option to set the serial port pins (RX and TX) so I'm not sure if that's even possible.
In short - I want to use this library, but not program the ESP directly. Also, I'm using an ESP-01 and not 12.
Thanks.

i strongly encourage you to investigate directly programming the ESP and forgetting the AVR;

If you use serial to talk to the ESP then you are adding a load to the Arduino and ESP you don't need to add.  You are going to constrain the data link to ~9600, because this sort of hook up doesn't seem to work above that with software serial.  Finally you a going to use a ESP, with a clock speed of at least 80MHz, as a slave to an Arduino with a max clock speed of 32MHz.  You can program the ESP with the Arduino IDE, using the same language.  Look at using the Arduino as a port expander to the ESP communication over I2C.

You cannot use that "library". Simply because that isn't a library, that is a core. It's the entirety of the Arduino API designed to run on an ESP8266.
You can use it to program the ESP8266 directly and nothing else. No part of that has anything at all to do with Arduino boards like the Uno.

+1 for the above answer as well since it clarifies the point that the stuff you have mentioned is not a library and is a core;

You can infact connect ESP as a serial device to the arduino and use AT commands supported by the ESP to interact with it and achieve what you want;
For ESP-01 read the detail on http://www.teomaragakis.com/hardware/electronics/how-to-connect-an-esp8266-to-an-arduino-uno/
Please read the following instructable which has detailed explanation on how to connect ESP12 also if interested;
http://www.instructables.com/id/ESP-12E-ESP8266-With-Arduino-Uno-Getting-Connected/


text:
Max Sample Rate of an Arduino Uno
I am using the FFT library from Open Music Labs and I am trying to analyze frequencies up to 40 kHz. Now I don't understand fully but know that my sample rate has to be at least twice as much, but my question is with the example code fft_adc_serial, how can I adjust the sample frequency to 80kHz? Is it even possible to sample at these high frequencies.

112 us, 8.9 k samples per second max on an arduino uno. And that is if you do extreme programming.

Trying to get 80kHz from an Uno will reduce the samples to unusable garbage.

From the datasheet: "Up to 76.9kSPS (Up to 15kSPS at Maximum Resolution)"

Nick Gammon has some ADC tests that show the accuracy as a function of the prescaler setting. From his data, prescaler = 16 (which gives a sampling rate of 76.9 kS/s) seems still almost accurate, whereas prescaler = 8 (153.8 kS/s) seems to leave only 3 – 5 bits of effective resolution.


text:
Disable the Amplifier during the flashing ESP8266
I use ESP-12 and Adafruit Mono Amplifier for playing audio. It works but It has one big issue. My circuit uses RxD to transfer audio (A+ connect to RxD), also ESP uses for flashing the chip. This causes horrible noise when it is programming the ESP8266 from the speaker. The good thing about this module is it has SD pin which can be used to turn it off.
Now the question is how I can connect this SD pin to disable the amplifier during the flashing procedure and also keep it off by default in normal mode and use something like digitalWrite() to turn it on manually in my application when it is needed. Thanks

since you can't set pins during/before flashing, afaik, you have to use pins 4 or 5, which are LOW during RESET

Are they LOW during RESET or Flashing? Do you mean GPIO4 and GPIO5?

low from power-on, yes, gpio 4-5. useful for relays, buzzers, and other output where an uncontrolled state is annoying or dangerous,.

SD is pulled up to VIN by a 10kΩ resistor. You will need to pull it down to ground with something "stronger" that 10kΩ - a 1kΩ resistor would probably do it.
Then you can drive the pin HIGH and override that 1kΩ resistance to enable the module.
You could also modify the module to remove the 10kΩ pull-up resistor (the one right by the VIN label which has 1002 printed on it) and use a weaker pull-down resistor (10kΩ would be good).

Thank you, I change 10K pull-up to the ground and it works perfectly. The only problem now is the pin (I'm using GPIO16 now) is HIGH when it flashes the new ROM and it still makes the noisy sound. Is there any other pin (LOW during flashing) to use to fix that too?

16 is a special pin used for wakeup. 0, 2 and 15 have special meanings too. Anuthing other than those pins should be fine.


text:
Using TxD pin and NeoPixel library for RGB LEDs
I have no free pin on my ESP-12 but GPIO16 and TxD (GPIO1). I use Neo Pixel Library and this design:

GPIO16 powers it on/off
TxD uses to handle single-wire-based for LEDs (GPIO1)

It works but it has one issue. I use USB <> TTL converter to program my ESP, it just worked for 1 2 times and after that burned the converter! I'm afraid there's something wrong with my design. Any better idea to use GPIO16 and TxD to do that? I need to power down LEDs when I don't need them to save power.

I would consider optimising the rest of your design and free up some other pins to use.

There probably is something electrically wrong, but what cannot be determined from the information you posted.  You could disconnect the LED power supply while programming, but that only lessens the chance - whatever damaged components could still damage something else.


text:
Conncet Bluetoth module HC-05 to Arduino Uno Using UART Usb to enter in AT command
I have connected Arduino Rx(pin 0) to Bluetooth module Rx pin. Tx od Arduino to Tx of Bluetooth . I am able to send command to Bluetooth module using Serial Monitor of Arduino on my PC.
I have uploaded the empty code in Arduino.
I want to know why we connected Tx to Tx and Rx to Rx i.e one to one connection?
If I send command "AT" from my PC using serial Monitor of Arduino , How is it flowing to Bluetooth module.
Why not we connect Rx to Tx pin in AT Mode of Bluetooth module?
Pls explain using diagram.

By using SoftSerial you can connect the HC-05 module to another pin than D0 and D1. Example connect HC-05 to D2 and D3 and define SoftSerial to use D2 and D3.
---------                        -----------                        ------
| HC-05 +---(SoftSerial)---(D2/3)+ Arduino +(D0/1)---(Serial USB)---+ PC |
---------                        -----------                        ------


text:
LED matrix question light up H or 4
Just a basic query;
On my understanding of LED Matrix's, The following would light up 4 LEDs.
But what if I only wanted to light up just 3 of those LEDs? The circuit still needs the same inputs, since power will continue across all columns/rows
Thanks
Tom

Multiplexing means you are powering only one of them and you have to set corresponding columns (in this case more like reset). If you're doing it for all rows fast enough, your eye won't see flickering (only if you move display)

BTW, you took this picture out of some place where multiplexing is explained. I deduce this by the leftover of the image title "What is multiplexing": did you actually read that article?

I was trying to find out on the internet and it looks like I was close to the answer. Maybe I didn’t think multiplexing would work over large LED arrays. Or let’s assume LED screens with 255 levels of brightness for each colour. The number of cycles or computing needs to be quick to support the display.

Multiplexing is the answer.

If you want to, as an example, light up only LEDS 1, 3 and 4, you will:

activate line A
activate line X
de-activate line X
de-activate lines A and B (yes, B was not active)
activate line A and B
activate line Y
de-activate line Y
de-activate lines A and B
start again from top

Do this so that the loop takes less than 10 milliseconds and you are actually refreshing the entire matrix at 100Hz, fast enough to trick the eyes of any human being as if the LEDs 1,3 and 4 are lighted up at the same time: persistence of vision is your friend.

This is very simple. You can turn on each LED one at a time and repeat this over and over again. The easiest way of achieving this is to put this code in the loop section.

Persistence of vision is defined as "the retention of a visual image for a short period of time after the removal of the stimulus that produced it" - dictionary.com

Even though the LED is on for only 1/3 of the time, it is fast enough that the human eye will not be able to tell that each LED turns off. Hence the viewer sees 3 LEDs on at the same time.
This allows any combination of LED patterns in your LED matrix.
7-segment displays also use this technique. You probably have some in a microwave or DVD player that you never realized that they were cycling through each digit, using persistence of vision.
Resources:
http://www.circuitstoday.com/interfacing-8x8-led-matrix-with-arduino (recommended)
http://tronixstuff.com/2013/10/11/tutorial-arduino-max7219-led-display-driver-ic/
https://playground.arduino.cc/Main/LEDMatrix
http://forum.hobbycomponents.com/viewtopic.php?f=43&t=1489


text:
Power consumption for arduino
I am using an Arduino SMD UNO r3 board ,and connecting thermal sensor MLX 90614 , wifi modem ESP 8266 , a buzzer and an arduino based sound sensor .
How much power distribution will it require ?
What should be the capacity of the battery ?

You need to create a power budget. This means pouring through the datasheets of each component and finding the max and nominal current consumption info and then summing it up. From this, you should be able to come up with a battery capacity value.
There is a great article called "What is a Power Budget" written by Chris Gammell (from The Amp Hour) that goes into power budgets in more detail. Here are the key items from that page:

So what is a power budget? Much like a budget you might have for your personal finances, a power budget shows where all the possible power will be used by a device to by breaking it down into components and categories.
As you can see, not much more is required than your datasheets and a spreadsheet type program. ... The first two columns (A&B) are simply identifiers to allow you to recognize which components correspond to which set of data. The next two columns (C&D) determine the multiplicative factor. If you have 5 components that contain 4 op amps per, then that will consume 20x the power of a device that has the same supply current needs but only one op amp per and there is only one on the board.  The next two columns (E&F) show how much current each individual component contributes and then the sum of all the components of that type contribute. Note that this parameter on a data sheet would be listed as “supply current” or “active current”. The “quiescient” number is when the device is in a resting state and will likely be much less than the active number (and not relevant for this example). Finally, the supply voltage is listed (in column G) to calculate power (using the formula P=I*V) which is listed in column I per device. All of these contributors are summed, an efficiency is estimated (I assumed a poor efficiency linear type supply) and the total power required input to the device is given. Further calculations could result from much of this initial data.


text:
Slowly decreasing the speed on a steppermotor over time
I am currently working on an elevator for my examsproject in school.
It's a quite simple simulation of a lifesize elevator.
I'm currently using a steppermotor for the elevatorchair and it's set with a certain speed.
However, in a real elevator, the speed would slowly decrease as it's progressing towards it's destination for a more pleasant ride for the passengers. I'd like to make the same simulation.
I was thinking of using the millis to periodically increase the delays over time, but I don't know whether alternative methods could be used for better results.

Some stepper libraries already support acceleration out of the box. You'd have to check if you can make the acceleration/deceleration slow enough, as the purpose is mostly to prevent missed steps.

millis() sound like a good way to go.
Check the estimated time until arrival (stopping), and in steps (you define yourself) you changen the (PWM) speed of the stepper motor.
Note, also for accelerating you can use the same step schema but reversed.
There are other ways, but I think those will be too complicated, like setting a (hardware) timer for the next speed change. Changing the speed in ms-accuracy will be more than enough.
Do not use delay, since you still want to be responsive for pressed buttons, and (safety) sensors.

Response to your answer that is a comment and will be deleted high likely: Hello Soren, this is not an answer, so you have to put it either as comment, or update your question (the latter is best). I understand the for loop (and I kind of understand, being Dutch). In principle the delay is possible, but it will get you in trouble when wanting to read button states/sensor states (imagine a safety sensor is activated exactly in those 5 ms, you either miss it or have a 5 ms delay). It's better to use millis() over delay, unless you don't have anything else that needs to be responsive.


text:
What is the use of 1k resistor shown in the picture and why it is used? Please check Arduino Uno Schematics for more info

Can anyone tell me why 1k resistor is used on pin 13 of ATmega16U2 in arduino uno schematics. I have also seen a 100k resistor used in this position?
Link for schematics - https://www.arduino.cc/en/uploads/Main/Arduino_Uno_Rev3-schematic.pdf

Pin 13 of the USB interface chip is connected to RESET line of the ATMEGA328 MCU. I would guess (also from "USB boot En" label) that pressing/issuing board reset gives the USB interface an interrupt (INT7), such that USB bootloader gets activated and the ATMEGA328 can start loading firmware code over USB. The resistor is a pull-down resistor ensuring LOW signal, and its value shouldn't matter much. However, there is a capacitor (C5) which provides a short pulse to the interrupt line. This is not the best way to form a digital signal and initiate an interrupt, but the RC should be long enough, so I would expect that if 100k is used, the cap can be much smaller than 100n as in 1k case.


text:
Simultaneous input output in arduino mega
I need to read 5 analog pins simultaneously , is it possible?
note that:
analogRead(1);
analogRead(2);
analogRead(3);
will not work this case

on the UNO (mega should be same) the analogRead(x); takes about 500us to complete. So depending upon the reaction speed of the signals that may be sufficient. You need to ask yourself what is the precision of time you consider to be simultaneous. If you are only looking at sampling everything once a Kilo Hertz (give or take) then back to back reads may be sufficient.

Why won't the code given work?

No, it is not. The ADC in the MCU is only capable of sampling a single analog channel at a time.
If you require sampling more than one channel at a time then you will need to use one or more external ADCs that are capable of sampling multiple channels, or multiple ADCs each dedicated to a single channel.


text:
Works on Uno but not on Yun
I found some code that works to transmit the required signal to an RX-2B RC receiver, the code works great from my Uno but when I tried to run it from my Yún nothing happens.
The code has definitely uploaded as I tested with an LED and the pin is getting a HIGH voltage written to it.
Does anyone have any idea what the issue might be? Code below.
Thanks.
/**
* Control Realtek RX2 (RX2 -G) RC Receiver with Arduino
*
* @author Mircea Diaconescu, Octomber 28, 2013
* @source https://github.com/dimircea/
* GPL v3 License
*
 * Many cheap RC toys are based on TX2 / RX2 transmitter / receiver ICs.
 * This Arduino sketch allows to replace the TX2 based Remote Control with Arduino.
 * Just one single pin is used from the Arduino board.
 *
 * Connect Arduino pin 10 to the solder point where the toy antenna is connected or         to the toy antenna cable.
 * One can replace pin 10 with other free digital pin available on the Arduino board.
     *
 * TX-2B/RX-2B datasheet: http://www.datasheetarchive.com/dl/Datasheet-    035/DSA0017137.pdf
 */

/** Functions (aka W1) - as defined by the IC datasheet */
#define COMMAND_ENDCODE         4
#define COMMAND_FORWARD        10
#define COMMAND_FORWARD_TURBO  16
#define COMMAND_TURBO          22
#define COMMAND_FORWARD_LEFT   28
#define COMMAND_FORWARD_RIGHT  34
#define COMMAND_BACKWARD       40
#define COMMAND_BACKWARD_RIGHT 46
#define COMMAND_BACKWARD_LEFT  52
#define COMMAND_LEFT           58
#define COMMAND_RIGHT          64

//output pins
#define ANTENNA_PIN 9

/** Initialize the Arduino data and pin */
void setup() {
 pinMode( ANTENNA_PIN, OUTPUT);
}

/** Loop code */
void loop() {
 // add here your commands to control the RX2 module...
 // for test purposes, here a continuous forward command is sent

 sendCommand( COMMAND_FORWARD);

}

/** Send command to the RX2 IC */
void sendCommand( int command) {
 int w1 = 0, w2 = 0;

 /** start code sequence 4 x W2, ~625Hz, Duty Cycle 75% */
 for ( w2 = 0; w2 < 4; w2++) {
   digitalWrite( ANTENNA_PIN, HIGH);
   delayMicroseconds( 1200);
   digitalWrite( ANTENNA_PIN, LOW);
   delayMicroseconds( 400);
  }

 /** function code sequence, n x W1, ~1.25KHz, Duty Cycle 50% */
 for ( w1 = 0; w1 < command; w1++) {
   digitalWrite( ANTENNA_PIN, HIGH);
   delayMicroseconds( 400);
   digitalWrite( ANTENNA_PIN, LOW);
   delayMicroseconds( 400);
 }
}

Note that delayMicroseconds() based timing is only consistent if you disable interrupts, though that would probably lead to intermittent rather than complete failure.  It's also not particularly accurate, as the time of intervening operations must be taken into account, too.  Your data rate is slow enough that you might be able to use a sound card as an oscilloscope to debug the timing.

Thanks for the info Chris, I will disable interrupts and see if it makes a difference. There is other code here link which does a similar job but again doesn't work on the Yun, only the Uno and another variant which I haven't had a chance to try yet link

Try the sound card, probing through a .1 - 1uF capacitor, starting with the uno.  It will be educational if nothing else.

Indeed it would, any resources?

A Yun is like a Leonardo with a CPU running GNU/Linux at its side. If your sketch works with a Leonardo, it's likely to work with a Yun.
Uno has a different MCU and thus not every sketch will just work, especially those using the hardware serial. You'll have to convert them.

As this bears no relation to the operations performed by the posted code it is at most a comment.  It is nowhere near being an answer.