text:
How to connect multiple I2C devices?
I am trying connecting I2C OLED SSD1306 and I2C INA219 on ESP32 but without success.
First try:
#include <WiFi.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <Adafruit_INA219.h>
Adafruit_INA219 ina219;

#define SDA1 21  //OLED SSD1306
#define SCL1 22  //OLED SSD1306
#define SDA2 5  //INA219
#define SCL2 4  //INA219

float shuntvoltage = 0;
float busvoltage = 0;
float current_mA = 0;
float current_A = 0;
float loadvoltage = 0;
float power_W = 0;

#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET   0
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

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

IPAddress local_IP(192, 168, 0, 241);
IPAddress gateway(192, 168, 0, 230);
IPAddress subnet(255, 255, 255, 0);
IPAddress primaryDNS(8, 8, 8, 8);
IPAddress secondaryDNS(8, 8, 4, 4);

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

  Wire.begin(SDA1, SCL1);

  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println(F("SSD1306 allocation failed"));
    for(;;); // Don't proceed, loop forever
  }

   display.fillScreen(BLACK);
   display.setTextColor(WHITE);
   display.setTextWrap(false);

   startWiFi();

  Wire.begin(SDA2, SCL2);
  ina219.begin();

  display.ssd1306_command(SSD1306_DISPLAYOFF);
  delay(5000);
  display.ssd1306_command(SSD1306_DISPLAYON);
  display.println("Awake!");
  display.display();

}

void loop()
{
      shuntvoltage = ina219.getShuntVoltage_mV();
      busvoltage = ina219.getBusVoltage_V();
      current_mA = ina219.getCurrent_mA();
      loadvoltage = busvoltage + (shuntvoltage / 1000);
      current_A = current_mA / 1000;
      power_W = current_A * loadvoltage;

      Serial.println("");
      Serial.print("Bus Voltage:   "); Serial.print(busvoltage); Serial.println(" V");
      Serial.print("Shunt Voltage: "); Serial.print(shuntvoltage); Serial.println(" mV");
      Serial.print("Load Voltage:  "); Serial.print(loadvoltage); Serial.println(" V");
      Serial.print("Current:       "); Serial.print(current_mA); Serial.println(" mA");
      Serial.print("Power:       "); Serial.print(power_W); Serial.println(" w");
      Serial.println("");

  delay(1000);

  display.stopscroll();
  display.fillScreen(BLACK);
  display.invertDisplay(0);

  testscrolltext("TESTING");    // Draw scrolling text

}

const char* wl_status_to_string(wl_status_t status) {
  switch (status) {
    case WL_NO_SHIELD: return "WL_NO_SHIELD";
    case WL_IDLE_STATUS: return "WL_IDLE_STATUS";
    case WL_NO_SSID_AVAIL: return "WL_NO_SSID_AVAIL";
    case WL_SCAN_COMPLETED: return "WL_SCAN_COMPLETED";
    case WL_CONNECTED: return "WL_CONNECTED";
    case WL_CONNECT_FAILED: return "WL_CONNECT_FAILED";
    case WL_CONNECTION_LOST: return "WL_CONNECTION_LOST";
    case WL_DISCONNECTED: return "WL_DISCONNECTED";
  }
}

void printWifiStatus() {
  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  Serial.print("Gateway: ");
  Serial.println(WiFi.gatewayIP());
  Serial.print("Subnet: ");
  Serial.println(WiFi.subnetMask());
  Serial.print("Primary DNS: ");
  Serial.println(primaryDNS);

  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");

  Serial.printf("BSSID: %s\n", WiFi.BSSIDstr().c_str());
  Serial.println("Connected to wifi");
}

void startWiFi() { // Start a Wi-Fi access point, and try to connect to some given access points. Then wait for either an AP or STA connection

typedef enum {
    WL_NO_SHIELD        = 255,   // for compatibility with WiFi Shield library
    WL_IDLE_STATUS      = 0,
    WL_NO_SSID_AVAIL    = 1,
    WL_SCAN_COMPLETED   = 2,
    WL_CONNECTED        = 3,
    WL_CONNECT_FAILED   = 4,
    WL_CONNECTION_LOST  = 5,
    WL_DISCONNECTED     = 6
} wl_status_t;

  WiFi.begin(ssid, password);
  Serial.print("MAC Address: ");
  Serial.println(WiFi.macAddress());
  WiFi.config(local_IP, gateway, subnet, primaryDNS, secondaryDNS);
  WiFi.mode(WIFI_STA);
  Serial.println("Connecting Wifi...");
  delay(5000);

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    Serial.println("NOT Connected to wifi");
    Serial.print("Status: ");
    Serial.println(wl_status_to_string(WiFi.status()));
    WiFi.begin(ssid, password);
  WiFi.config(local_IP, gateway, subnet, primaryDNS, secondaryDNS);
    WiFi.mode(WIFI_STA);
    delay(5000);
    ESP.restart();
  }

  //If connection successful show IP address in serial monitor
  Serial.println("Connected to wifi");
  printWifiStatus();

}

void testscrolltext(char * text) {
  display.clearDisplay();

  display.setTextSize(2); // Draw 2X-scale text
  display.setTextColor(WHITE);
  display.setCursor(10, 0);
  display.println(F(text));
  display.display();      // Show initial text
  delay(100);

  // Scroll in various directions, pausing in-between:
  display.startscrollright(0x00, 0x0F);
  delay(2000);
  display.stopscroll();
  delay(1000);
  display.startscrollleft(0x00, 0x0F);
  delay(2000);
  display.stopscroll();
  delay(1000);
  display.startscrolldiagright(0x00, 0x07);
  delay(2000);
  display.startscrolldiagleft(0x00, 0x07);
  delay(2000);
  display.stopscroll();
  delay(1000);
}

OLED doesn't work. But INA219 works perfectly.
Second try:
#include <WiFi.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <Adafruit_INA219.h>
Adafruit_INA219 ina219;

#define SDA1 21  //OLED SSD1306
#define SCL1 22  //OLED SSD1306
#define SDA2 5  //INA219
#define SCL2 4  //INA219

TwoWire I2Cone = TwoWire(0);
TwoWire I2Ctwo = TwoWire(1);

float shuntvoltage = 0;
float busvoltage = 0;
float current_mA = 0;
float current_A = 0;
float loadvoltage = 0;
float power_W = 0;

#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET   0
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

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

IPAddress local_IP(192, 168, 0, 241);
IPAddress gateway(192, 168, 0, 230);
IPAddress subnet(255, 255, 255, 0);
IPAddress primaryDNS(8, 8, 8, 8);
IPAddress secondaryDNS(8, 8, 4, 4);

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

  I2Cone.begin(SDA1,SCL1,400000);
  I2Ctwo.begin(SDA2,SCL2,400000);

  I2Cone.beginTransmission(0x3C);
  I2Ctwo.beginTransmission(0x40);

  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println(F("SSD1306 allocation failed"));
    for(;;); // Don't proceed, loop forever
  }

   display.fillScreen(BLACK);
   display.setTextColor(WHITE);
   display.setTextWrap(false);

  startWiFi();
  ina219.begin();

  display.ssd1306_command(SSD1306_DISPLAYOFF);
  delay(5000);
  display.ssd1306_command(SSD1306_DISPLAYON);
  display.println("Awake!");
  display.display();

}

void loop()
{

      shuntvoltage = ina219.getShuntVoltage_mV();
      busvoltage = ina219.getBusVoltage_V();
      current_mA = ina219.getCurrent_mA();
      loadvoltage = busvoltage + (shuntvoltage / 1000);
      current_A = current_mA / 1000;
      power_W = current_A * loadvoltage;

      Serial.println("");
      Serial.print("Bus Voltage:   "); Serial.print(busvoltage); Serial.println(" V");
      Serial.print("Shunt Voltage: "); Serial.print(shuntvoltage); Serial.println(" mV");
      Serial.print("Load Voltage:  "); Serial.print(loadvoltage); Serial.println(" V");
      Serial.print("Current:       "); Serial.print(current_mA); Serial.println(" mA");
      Serial.print("Power:       "); Serial.print(power_W); Serial.println(" w");
      Serial.println("");

  delay(1000);

  display.stopscroll();
  display.fillScreen(BLACK);
  display.invertDisplay(0);

  testscrolltext("TESTING");    // Draw scrolling text

}

OLED works perfectly. But INA219 doesn't work.
How to make both OLED SSD1306 and INA219 works simultaneously?
Please help...

why does your code contain WiFi functions? .... reduce your code to minimum ..... display fixed text on the OLED and read a single value from the INA219

why do you use two instances of TwoWire? I2C is a bus. connect both devices to the same pair of pins

I have used a 128*64 oled display with a ina219. Both of them were working fine. Check the below code. Hope it helps.
#include <Adafruit_INA219.h>
#include <Adafruit_SSD1306.h>
#include <Adafruit_GFX.h>

#define I2C_OLED_ADDRESS    0x3C
#define I2C_INA219_ADDRESS  0x40

#define OLED_RESET  4

 Adafruit_SSD1306 oled(OLED_RESET);
 Adafruit_INA219 ina219;

 void initialize_device () {

  oled.begin (SSD1306_SWITCHCAPVCC, I2C_OLED_ADDRESS);
  oled.setTextColor (WHITE);
  oled.clearDisplay ();

  ina219.begin ();
}

 void refresh_oled (float current_ma, float load_voltage) {
  oled.clearDisplay ();

  oled.setTextSize (2);
  oled.setCursor (0, 0);
  oled.print ("V:"); oled.print (load_voltage); oled.print ('V');
  oled.setCursor(0, 20);
  oled.print ("I:"); oled.print (current_ma); oled.print ("mA");

  oled.display();
}

 void setup () {
  initialize_device ();
}

 void loop () {

  float current_ma = ina219.getCurrent_mA ();
  float load_voltage = ina219.getBusVoltage_V () + (ina219.getShuntVoltage_mV() / 1000);

  refresh_oled (current_ma, load_voltage);

  delay(100);
}

Please note that both of the modules were connected to the same I2C bus lines.

Thanks a lot for the note thilinaur. Because of your note, I realized my mistake. I2C doesn't need separate SDA SCL pins. As long as each device has separate addresses then using same SDA SCL pins will works.

I think that the issue is during INA219 initialization.
According with the begin function of class Adafruit_INA219.
Use:

ina219.begin(&I2CTwo);

instead of

ina219.begin();

According with the constructor of class Adafruit_INA219, default INA219 address is 0x40. As long as INA219 address on 0x40, no need ina219.begin(&I2CTwo). ina219.begin() will find 0x40 automatically.

@wieb the problem is NOT the address but the instance of i2c class to be used. I meant ‘’begin’’ function and not constructor.

Here is the code for connecting I2C OLED SSD1306 and I2C INA219 on ESP32 which will works simultaneously
#include <WiFi.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <Adafruit_INA219.h>
Adafruit_INA219 ina219;

#define SDA 21  //OLED SSD1306 & INA219 pin
#define SCL 22  //OLED SSD1306 & INA219 pin

float shuntvoltage = 0;
float busvoltage = 0;
float current_mA = 0;
float current_A = 0;
float loadvoltage = 0;
float power_W = 0;

#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET   0
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

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

IPAddress local_IP(192, 168, 0, 241);
IPAddress gateway(192, 168, 0, 230);
IPAddress subnet(255, 255, 255, 0);
IPAddress primaryDNS(8, 8, 8, 8);
IPAddress secondaryDNS(8, 8, 4, 4);

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

  Wire.begin(SDA, SCL);

  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println(F("SSD1306 allocation failed"));
    for(;;); // Don't proceed, loop forever
  }

   display.fillScreen(BLACK);
   display.setTextColor(WHITE);
   display.setTextWrap(false);

  startWiFi();
  ina219.begin();

  display.ssd1306_command(SSD1306_DISPLAYOFF);
  delay(5000);
  display.ssd1306_command(SSD1306_DISPLAYON);
  display.println("Awake!");
  display.display();

}

void loop()
{

      shuntvoltage = ina219.getShuntVoltage_mV();
      busvoltage = ina219.getBusVoltage_V();
      current_mA = ina219.getCurrent_mA();
      loadvoltage = busvoltage + (shuntvoltage / 1000);
      current_A = current_mA / 1000;
      power_W = current_A * loadvoltage;

      Serial.println("");
      Serial.print("Bus Voltage:   "); Serial.print(busvoltage); Serial.println(" V");
      Serial.print("Shunt Voltage: "); Serial.print(shuntvoltage); Serial.println(" mV");
      Serial.print("Load Voltage:  "); Serial.print(loadvoltage); Serial.println(" V");
      Serial.print("Current:       "); Serial.print(current_mA); Serial.println(" mA");
      Serial.print("Power:       "); Serial.print(power_W); Serial.println(" w");
      Serial.println("");

  delay(1000);

  display.stopscroll();
  display.fillScreen(BLACK);
  display.invertDisplay(0);

  testscrolltext("TESTING");    // Draw scrolling text

}

const char* wl_status_to_string(wl_status_t status) {
  switch (status) {
    case WL_NO_SHIELD: return "WL_NO_SHIELD";
    case WL_IDLE_STATUS: return "WL_IDLE_STATUS";
    case WL_NO_SSID_AVAIL: return "WL_NO_SSID_AVAIL";
    case WL_SCAN_COMPLETED: return "WL_SCAN_COMPLETED";
    case WL_CONNECTED: return "WL_CONNECTED";
    case WL_CONNECT_FAILED: return "WL_CONNECT_FAILED";
    case WL_CONNECTION_LOST: return "WL_CONNECTION_LOST";
    case WL_DISCONNECTED: return "WL_DISCONNECTED";
  }
}

void printWifiStatus() {
  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  IPAddress ip = WiFi.localIP();
  Serial.print("IP Address: ");
  Serial.println(ip);

  Serial.print("Gateway: ");
  Serial.println(WiFi.gatewayIP());
  Serial.print("Subnet: ");
  Serial.println(WiFi.subnetMask());
  Serial.print("Primary DNS: ");
  Serial.println(primaryDNS);

  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");

  Serial.printf("BSSID: %s\n", WiFi.BSSIDstr().c_str());
  Serial.println("Connected to wifi");
}

void startWiFi() { // Start a Wi-Fi access point, and try to connect to some given access points. Then wait for either an AP or STA connection

typedef enum {
    WL_NO_SHIELD        = 255,   // for compatibility with WiFi Shield library
    WL_IDLE_STATUS      = 0,
    WL_NO_SSID_AVAIL    = 1,
    WL_SCAN_COMPLETED   = 2,
    WL_CONNECTED        = 3,
    WL_CONNECT_FAILED   = 4,
    WL_CONNECTION_LOST  = 5,
    WL_DISCONNECTED     = 6
} wl_status_t;

  WiFi.begin(ssid, password);
  Serial.print("MAC Address: ");
  Serial.println(WiFi.macAddress());
  WiFi.config(local_IP, gateway, subnet, primaryDNS, secondaryDNS);
  WiFi.mode(WIFI_STA);
  Serial.println("Connecting Wifi...");
  delay(5000);

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    Serial.println("NOT Connected to wifi");
    Serial.print("Status: ");
    Serial.println(wl_status_to_string(WiFi.status()));
    WiFi.begin(ssid, password);
  WiFi.config(local_IP, gateway, subnet, primaryDNS, secondaryDNS);
    WiFi.mode(WIFI_STA);
    delay(5000);
    ESP.restart();
  }

  //If connection successful show IP address in serial monitor
  Serial.println("Connected to wifi");
  printWifiStatus();

}

void testscrolltext(char * text) {
  display.clearDisplay();

  display.setTextSize(2); // Draw 2X-scale text
  display.setTextColor(WHITE);
  display.setCursor(10, 0);
  display.println(F(text));
  display.display();      // Show initial text
  delay(100);

  // Scroll in various directions, pausing in-between:
  display.startscrollright(0x00, 0x0F);
  delay(2000);
  display.stopscroll();
  delay(1000);
  display.startscrollleft(0x00, 0x0F);
  delay(2000);
  display.stopscroll();
  delay(1000);
  display.startscrolldiagright(0x00, 0x07);
  delay(2000);
  display.startscrolldiagleft(0x00, 0x07);
  delay(2000);
  display.stopscroll();
  delay(1000);
}

NOTE: Both OLED SSD1306 and INA219 must be using the same SDA & SCL pins (pin 21 & pin 22 on ESP32).
Hope this will help anyone who has same issue like me.


text:
'inet_addr_to_ipaddr' was not declared in this scope
I am using ESP32 Ping from this page: https://github.com/pbecchi/ESP32_ping
It works fine on ESP32, no compiler error.
Because something wrong on my PC, I did fresh install Windows 10 and Arduino IDE 1.8.8.
After fresh install, ESP32 Ping doesn't work anymore.
Arduino IDE Compiler error in Ping.cpp:
//Ping.cpp

#include <Arduino.h>

#include <math.h>
#include <float.h>
#include <signal.h>
#include <stdint.h>
#include <string.h>
#include <errno.h>

#include "ping.h"

#include "lwip/inet_chksum.h"
#include "lwip/ip.h"
#include "lwip/ip4.h"
#include "lwip/err.h"
#include "lwip/icmp.h"
#include "lwip/sockets.h"
#include "lwip/sys.h"
#include "lwip/netdb.h"
#include "lwip/dns.h"

static uint16_t ping_seq_num;
static uint8_t stopped = 0;

/*
* Statistics
*/
static uint32_t transmitted = 0;
static uint32_t received = 0;
static float min_time = 0;
static float max_time = 0;
static float mean_time = 0;
static float last_mean_time = 0;
static float var_time = 0;

#define PING_ID 0xAFAF

#define PING_DEFAULT_COUNT    10
#define PING_DEFAULT_INTERVAL  1
#define PING_DEFAULT_SIZE     32
#define PING_DEFAULT_TIMEOUT   1

/*
* Helper functions
*
*/
static void ping_prepare_echo(struct icmp_echo_hdr *iecho, uint16_t len) {
    size_t i;
    size_t data_len = len - sizeof(struct icmp_echo_hdr);

    ICMPH_TYPE_SET(iecho, ICMP_ECHO);
    ICMPH_CODE_SET(iecho, 0);
    iecho->chksum = 0;
    iecho->id = PING_ID;
    iecho->seqno = htons(++ping_seq_num);

    /* fill the additional data buffer with some data */
    for (i = 0; i < data_len; i++) {
        ((char*)iecho)[sizeof(struct icmp_echo_hdr) + i] = (char)i;
    }

    iecho->chksum = inet_chksum(iecho, len);
}

static err_t ping_send(int s, ip4_addr_t *addr, int size) {
    struct icmp_echo_hdr *iecho;
    struct sockaddr_in to;
    size_t ping_size = sizeof(struct icmp_echo_hdr) + size;
    int err;

    iecho = (struct icmp_echo_hdr *)mem_malloc((mem_size_t)ping_size);
    if (!iecho) {
        return ERR_MEM;
    }

    ping_prepare_echo(iecho, (uint16_t)ping_size);

    to.sin_len = sizeof(to);
    to.sin_family = AF_INET;
    inet_addr_from_ipaddr(&to.sin_addr, addr);

    if ((err = sendto(s, iecho, ping_size, 0, (struct sockaddr*)&to, sizeof(to)))) {
        transmitted++;
    }
    free(iecho)
    return (err ? ERR_OK : ERR_VAL);
}

static void ping_recv(int s) {
    char buf[64];
    int fromlen, len;
    struct sockaddr_in from;
    struct ip_hdr *iphdr;
    struct icmp_echo_hdr *iecho = NULL;
    char ipa[16];
    struct timeval begin;
    struct timeval end;
    uint64_t micros_begin;
    uint64_t micros_end;
    float elapsed;

    // Register begin time
    gettimeofday(&begin, NULL);

    // Send
    while ((len = recvfrom(s, buf, sizeof(buf), 0, (struct sockaddr*)&from, (socklen_t*)&fromlen)) > 0) {
        if (len >= (int)(sizeof(struct ip_hdr) + sizeof(struct icmp_echo_hdr))) {
            // Register end time
            gettimeofday(&end, NULL);

            /// Get from IP address
            ip4_addr_t fromaddr;
            inet_addr_to_ipaddr(&fromaddr, &from.sin_addr);

            strcpy(ipa, inet_ntoa(fromaddr));

            // Get echo
            iphdr = (struct ip_hdr *)buf;
            iecho = (struct icmp_echo_hdr *)(buf + (IPH_HL(iphdr) * 4));

            // Print ....
            if ((iecho->id == PING_ID) && (iecho->seqno == htons(ping_seq_num))) {
                received++;

                // Get elapsed time in milliseconds
                micros_begin = begin.tv_sec * 1000000;
                micros_begin += begin.tv_usec;

                micros_end = end.tv_sec * 1000000;
                micros_end += end.tv_usec;

                elapsed = (float)(micros_end - micros_begin) / (float)1000.0;

                // Update statistics
                // Mean and variance are computed in an incremental way
                if (elapsed < min_time) {
                    min_time = elapsed;
                }

                if (elapsed > max_time) {
                    max_time = elapsed;
                }

                last_mean_time = mean_time;
                mean_time = (((received - 1) * mean_time) + elapsed) / received;

                if (received > 1) {
                    var_time = var_time + ((elapsed - last_mean_time) * (elapsed - mean_time));
                }

                // Print ...
                log_d("%d bytes from %s: icmp_seq=%d time=%.3f ms\r\n", len, ipa,
                    ntohs(iecho->seqno), elapsed
                );

                return;
            }
            else {
                // TODO
            }
        }
    }

    if (len < 0) {
        log_d("Request timeout for icmp_seq %d\r\n", ping_seq_num);
    }
}
/*
static void stop_action(int i) {
    signal(i, SIG_DFL);
    stopped = 1;
}
+/
/*
* Operation functions
*
*/
void ping(const char *name, int count, int interval, int size, int timeout) {
    // Resolve name
    hostent * target = gethostbyname(name);
    IPAddress adr = *target->h_addr_list[0];
    if (target->h_length == 0) {
        // TODO: error not found target?????
        return;
    }
    ping_start(adr, count, interval, size, timeout);
}
bool ping_start(struct ping_option *ping_o) {

    return ping_start(ping_o->ip,ping_o->count,0,0,0);

}
bool ping_start(IPAddress adr, int count=0, int interval=0, int size=0, int timeout=0) {
//  driver_error_t *error;
    struct sockaddr_in address;
    ip4_addr_t ping_target;
    int s;
    // Get default values if argument are not provided
    if (count == 0) {
        count = PING_DEFAULT_COUNT;
    }

    if (interval == 0) {
        interval = PING_DEFAULT_INTERVAL;
    }

    if (size == 0) {
        size = PING_DEFAULT_SIZE;
    }

    if (timeout == 0) {
        timeout = PING_DEFAULT_TIMEOUT;
    }

    // Create socket
    if ((s = socket(AF_INET, SOCK_RAW, IP_PROTO_ICMP)) < 0) {
        // TODO: error
        return false;
    }

    address.sin_addr.s_addr = adr;
    ping_target.addr = address.sin_addr.s_addr;

    // Setup socket
    struct timeval tout;

    // Timeout
    tout.tv_sec = timeout;
    tout.tv_usec = 0;

    if (setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &tout, sizeof(tout)) < 0) {
        closesocket(s);
        // TODO: error
        return false;
    }

    stopped = 0;
    transmitted = 0;
    received = 0;
    min_time = 1.E+9;// FLT_MAX;
    max_time = 0.0;
    mean_time = 0.0;
    var_time = 0.0;

    // Register signal for stop ping
    //signal(SIGINT, stop_action);

    // Begin ping ...
    char ipa[16];

    strcpy(ipa, inet_ntoa(ping_target));
    log_i("PING %s: %d data bytes\r\n",  ipa, size);

    ping_seq_num = 0;

    while ((ping_seq_num < count) && (!stopped)) {
        if (ping_send(s, &ping_target, size) == ERR_OK) {
            ping_recv(s);
        }
        delay( interval*1000L);
    }

    closesocket(s);

    log_i("%d packets transmitted, %d packets received, %.1f%% packet loss\r\n",
        transmitted,
        received,
        ((((float)transmitted - (float)received) / (float)transmitted) * 100.0)
    );

    if (received) {
        ping_resp pingresp;
        log_i("round-trip min/avg/max/stddev = %.3f/%.3f/%.3f/%.3f ms\r\n", min_time, mean_time, max_time, sqrt(var_time / received));
        pingresp.total_count = 10;
        pingresp.timeout_count = 10;
        pingresp.total_bytes = 1;
        pingresp.total_time = mean_time;
        pingresp.ping_err = 0;
        return true;
    //  ping_o->sent_function(ping_o, (uint8*)&pingresp);
    }
    return false;
}

bool ping_regist_recv(struct ping_option *ping_opt, ping_recv_function ping_recv)
{
    if (ping_opt == NULL)
        return false;

    ping_opt->recv_function = ping_recv;
    return true;
}

bool ping_regist_sent(struct ping_option *ping_opt, ping_sent_function ping_sent)
{
    if (ping_opt == NULL)
        return false;

    ping_opt->sent_function = ping_sent;
    return true;
}

Arduino IDE 1.8.8. compiler stop in this line:
inet_addr_from_ipaddr(&to.sin_addr, addr);

The error message: 'inet_addr_to_ipaddr' was not declared in this scope
According to this post, inet_addr need lwip library.
So... the conclusion: cause of this issue is broken lwip library.
But when ESP32 Ping working fine previously, I didn't install any separate lwip library. Maybe ESP32 Ping use lwip library from Arduino library - #include <Arduino.h>
But why after fresh install, ESP32 Ping doesn't work anymore?
Arduino IDE installation automatically included Arduino library. Also, I didn't change anything on Arduino Sketch & Library folder - C:\Users\Documents\Arduino. The folder content as the same as before fresh install.
How to fix this?
Please help...

did you use git to install the esp32 boards?

did the install of ESP32 package in Board Manager finish without errors?

@Juraj - ESP32 package installation in Board Manager finished without any errors but when compile the sketch always error 'inet_addr_to_ipaddr' was not declared in this scope

I did search all Ping.cpp included files in C:\Program Files (x86)\Arduino folder. ALL included files has been found in that sub folder EXCEPT ip4.h. The ip4.h file doesn't found in that folder, maybe this is the cause of broken lwip library. How to fix this?

Found ip4.h in C:\Users\AppData\Local\Arduino15\packages\esp32\hardware\esp32\1.0.1\tools\sdk\include\lwip\lwip. It seems ESP32 Ping use 2 separate lwip libraries (Arduino libraries in C:\Program Files (x86)\Arduino and ESP32 library in C:\Users\AppData\Local\Arduino15\packages\esp32\hardware\esp32\1.0.1\tools\sdk\include\lwip\lwip). But somehow the library connection is broken and cause 'inet_addr_to_ipaddr' was not declared in this scope error

Instead using Board Manager to install ESP32 package, also tried install it by using git, but didn't help either. Still 'inet_addr_to_ipaddr' was not declared in this scope error

Tried very dumb solution by adding #define inet_addr_from_ipaddr and
#define inet_addr_to_ipaddr in Ping.cpp file. No compiler error and able upload the sketch into ESP32, but ping doesn't work because it didn't find inet_addr_from_ipaddr and inet_addr_to_ipaddr functions.

Did searching in folders: C:\Program Files (x86)\Arduino, C:\Users\AppData\Local\Arduino15\ , and C:\Users\Documents\Arduino , NOT FOUND any inet_addr_from_ipaddr and inet_addr_to_ipaddr functions. Maybe this is the cause 'inet_addr_to_ipaddr' was not declared in this scope error. But how to fix this?

Done this steps:
1. Uninstall Arduino IDE 1.8.8
2. Delete C:\Users\AppData\Local\
3. Rename C:\Users\Documents\Arduino into C:\Users\Documents\Arduino_OLD
4. Restart the PC
5. Install Arduino IDE 1.8.8
6. Install ESP32 Core version 1.0.0 using Boards Manager

Then.... compile my sketch.
And now.... it WORKS....  :)  :)  :)
My previous mistake is not installing ESP32 Core version 1.0.0.
I did it by installing version 1.0.1 - the Boards Manager default version - which didn't work.
It seems some change in ESP32 Core version 1.0.1 broke ESP32 Ping library connection.

and why this answer? there is a simpler way to reinstall a boards package

source: Stack Exchange

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

sort: votes


text:
Invalid conversion from 'const char' to 'uint8_t*'
I am just a newbie, don't know how to solve this issue
void loop()
{
  UdpSend("Test", "192.168.0.240", 4210);
}

void UdpSend(const char* message, uint8_t * ipaddress, int port){
      Serial.println("Send message: ");
      Udp.beginPacket(ipaddress, port);
      Udp.write(message);
      Udp.endPacket();
}

Arduino IDE can't compile.
The error message:  invalid conversion from 'const char' to 'uint8_t* {aka unsigned char*}' [-fpermissive]*
Trying to change with this code:
void UdpSend(uint8_t * message, uint8_t * ipaddress, int port){
      Serial.println("Send message: ");
      Udp.beginPacket(ipaddress, port);
      Udp.write(message);
      Udp.endPacket();
}

Also doesn't work, the error message: invalid conversion from 'const char' to 'uint8_t* {aka unsigned char*}' [-fpermissive]*
Please help...

you changed the wrong one ... try changing uint8_t * ipaddress to const char * ipaddress ... then in Udp.beginPacket((uint8_t *) ipaddress, ...

Change the code like this:
void UdpSend(const char * message, const char * ipaddress, int port){       Serial.println("Send message: ");       Udp.beginPacket((uint8_t *)ipaddress, port);       Udp.write(message);       Udp.endPacket(); } Error: invalid conversion from 'const char*' to 'uint8_t {aka unsigned char}' in **Udp.write(message);**

void UdpSend(const char * message, const char * ipaddress, int port){       Serial.println("Send message: ");       Udp.beginPacket((uint8_t *)ipaddress, port);       Udp.write((uint8_t *)message);       Udp.endPacket(); } Error: invalid conversion from 'uint8_t* {aka unsigned char*}' to 'uint8_t {aka unsigned char}' in Udp.write((uint8_t *)message);

Please help....

hmm ... ok, I probably didn't look at the code properly

what library is Udp from? - you actually do not need the (uint8_t *) at all

#include <WiFiUdp.h>

Remove all (uint8_t ): void UdpSend(const char * message, const char * ipaddress, int port){       Serial.println("Send message: ");       Udp.beginPacket(ipaddress, port);       Udp.write(message);       Udp.endPacket(); } Error: _invalid conversion from 'const char' to 'uint8_t {aka unsigned char}'_ in Udp.write(message);

In ESP32 Arduino package the WiFiUdp.h doesn't pull in all Print class write functions. As consequence the WiFiUdp class doesn't know write(const char *str).
Use Udp.print(message); if message is a zero-terminated char array
or Udp.write(message, size); if message is a byte array

Wild guess that it's esp32. Props to you if you're right!!!

Juraj guess is correct, I am using ESP32

Thanks a lot Juraj, your solution works perfectly.

@JaromandaX, it was not so wild. there are not so many WiFiUdp.h (OP revealed it in comment)

I'm still impressed

Not sure why you're using uint8_t at all
The Udp.beginPacket function signature is
int WiFiUDP::beginPacket(const char *host, uint16_t port)

No hint of uint8_t there
and .write is either
WiFiUDP::write(uint8_t byte)
WiFiUDP::write(const uint8_t *buffer, size_t size)
WiFiUDP::write(const char *str)
WiFiUDP::write(const char *buffer, size_t size)

So, your other attempt to use write((uint8_t *)) is also wrong
Try this:
void loop()
{
  UdpSend("Test", "192.168.0.240", 4210);
}

void UdpSend(const char* message, const char * ipaddress, int port){
      Serial.println("Send message: ");
      Udp.beginPacket(ipaddress, port);
      Udp.write(message);
      Udp.endPacket();
}

Sorry, I am just a newbie, still don't know how and learning to do it in proper way. void UdpSend(const char* message, const char * ipaddress, int port){       Serial.println("Send message: ");       Udp.beginPacket(ipaddress, port);       Udp.write(message);       Udp.endPacket(); } Error: invalid conversion from 'const char*' to 'uint8_t {aka unsigned char}' in Udp.write(message);

which line is the error referring to - the code I posted works

The error referring to Udp.write(message); line. Error: invalid conversion from 'const char*' to 'uint8_t {aka unsigned char}' [-fpermissive]

you're doing something else wrong, since Udp.write can take a single const char * argument

Change in Loop function: UdpSend("T", "192.168.0.240", 4210); Also error in Udp.write(message); Error message: invalid conversion from 'const char*' to 'uint8_t {aka unsigned char}' [-fpermissive]

Previously I am using this code: Serial.println("Send: ");       Udp.beginPacket("192.168.0.240", 4210);       Udp.write("TESTING FROM 240");       Udp.endPacket(); And it works perfectly. But for simplicity, I am trying to write simple function for itvoid UdpSend(const char* message, const char * ipaddress, int port) (which doesn't work)

@wieb Provided "try" code is working on Arduino IDE 1.8.8 (if you compile it for the Arduino Uno + WiFi shield). You HAVE TO provide more details. Versions of everything (IDE, WiFi lib), setup info (board, shield if used)...

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


text:
Can't extract basic data using ThingspeakHTTP
I don't know anything about HTML, but I want to extract the % probability of the Northern lights being visible from this webpage
http://aurorawatch.ca/.
I entered this into the URL field, and selected HTML version 1.
When I inspect the text element I want and copy the Xpath I get the following:
"/html/body/div1/div[5]/table/tbody/tr1/td/div1/table[2]/tbody/tr[2]/td/div/table/tbody/tr/td[2]/span"
and enter this into the "parse string" field of the ThingSpeak API app, but get the following error:
"Error parsing document, try a different parse string."
Most people who get this error seem to be getting data that doesn't load with the original page, so I think I must be missing something.
If there is a better solution for pulling this number to my ESP8266 than creating a thingspeak API, I would love to hear it too!

Post your code for a better understand of question

Maybe the website is blocking thingspeak as a scraper. You would want to make the ESP8266 do the GET request and then parse the data. I'd suggest using http://www.aurorawatch.ca/index.php?option=com_content&task=view&id=28&Itemid=47 as it's a) less data, and b) less likely to change.

@Majenko Thanks for the quick response! That's a good suggestion, using the alternate page. I thought that was possible too, but when I leave the parser string blank, the thingspeak api request returns the full site.
I know this is beyond the scope of the question, but do you have any recommendation for where to start learning how to make the GET request I want from the ESP8266?

why do you select HTTP 1.0 (HTML 1?)

@Juraj I believe that's what version the website I'm attempting to get data from is build on

I can see no reason for it not to work. I have manually downloaded the webpage source, prettified it with xmllint, then worked through each node of the xpath, and it is exactly as it should be. Yet it can't parse it. Maybe there is something about the content that ThingSpeak's parser doesn't like.

I tested the date and it returned the logo. something is added into page with script or style?

Ok, I have it working. It doesn't like the first tbody. Remove that and it starts working.  Also it's good to add /text() to the end.  I have it parsing this page: http://www.aurorawatch.ca/index.php?option=com_content&task=view&id=28&Itemid=47 with this xpath: /html/body/div[1]/div[5]/table[2]/tr[3]/td/table/tbody/tr/td[2]/span/text()

just for interest:   here is another site that has aurora visibility percentages ....  https://services.swpc.noaa.gov/text/aurora-nowcast-map.txt

@jsotola that is where I looked first, which has a few awesome resources! The format of the text array is a little ambiguous though (is it -90deg to 90deg top to bottom, or bottom to top?), and I am lucky enough to go to the university that made Aurora watch for the city I live in

You should use this page, since the other is the front page of the site and more likely to be dynamic:

http://www.aurorawatch.ca/index.php?option=com_content&task=view&id=28&Itemid=47

The XPath is also slightly different. The first tbody in the reported path doesn't actually exist. You should also add /text() to the end of the path to just return the textual content of the node:

/html/body/div[1]/div[5]/table[2]/tr[3]/td/table/tbody/tr/td[2]/span/text()


text:
Signal reading from existing snackmachine
So - i started a project at my civil-service. I want to fill a old snack-machine with things we need in the ambulance (bandages, cool-packs, etc.)
In order to get the current amount of everything without counting everything all these things should be stored in the snack-machine.
The Arduino should be attached to the signal wires of the machine. If a signal is firing (when a button is pressed) the microcontroller should decrease the current amount of the item in the connected database.. so it is easy to see if some product is running low.
The machine itself works with AC.
 now the problem: I'm not that professional with microcontrollers/hardware and this is my first big project.
If the Arduino is connected between the motherboard of the machine and the buttons the Arduino won't interrupt when something is pressed. I attached a picture of the circuit. (The only thing what's not on the picture are resistors between arduino and the buttons). The voltage on the wires is about 7.5-8 Volts alternative current.

So, your idea is to count the number of times that an item has been released, and use that to calculate the number of items left in the machine?  This does not seem very foolproof.  Is the database updated in real time?

7.8V AC connected to arduino ... that doesn't seem safe

I think you might get a problem with checking the button matrix. A matrix is typically checked by giving a HIGH consecutively to each row and checking the states of the columns. So the machine will drive some of the lines HIGH in it's own pace and you would have to synchronize to that, so that you don't disturb it, and only read the machines output voltage (not generating your own). It would also be possible to intercept the lines to the matrix and activating the corresponding lines on the machine with the Arduino, but I think you would have to use more external parts for that.

Even if you solve somehow the multiplexed keyboard input pointed by @chrisl still somebody can push the a key multiple times while dispensing an item counting as fake dispenses. Reliable reading of the multiplexed keyboard is tricky even for an experienced programmer, you need a different approach, I would think of lever switches or optos on the dispensing mech.  Can you post a picture of the dispensing mechanism?


text:
What is the typical form for a finished Arduino project?
I just started with Arduino. I am an experienced software developer so the programming side was already mostly known to me, and I am surprised at just how easy Arduino have made the hardware side of things, and how easy to use the various libraries are.
So for my first non tutorial project, I want to make air quality sensor web servers to be placed in several rooms throughout my house. I will then have a program running on my PC which collects readings from each sensor and stores then somewhere, to be analyzed later.
All I have right now is an Arduino UNO R3 starter kit, and I am having a WiFi shield delivered today. I feel confident that I can have a working version using the kit that I have shortly after the shield gets delivered.
But my question is: what is the best (some combination of easiest and cheapest) way to crank out half a dozen of these?
Presumably, most experienced makers don't include a breadboard in their finished products? I suppose I should buy a soldering iron.
Should I buy half a dozen UNO R3s and half a dozen WiFi shields (along with air quality sensors)? Or is there a cheaper option that is intended for semi-productionizing an Arduino project?
PS: I feel like the tags I have included barely intersect with the purpose of this question, so if you know of any more appropriate ones, feel free to suggest/edit.

Should you buy a soldering iron? Erm... yes? Along with many other things.  For instance: https://hackingmajenkoblog.wordpress.com/2016/03/23/top-6-things-every-engineer-needs/

I think you should have a look at the ESP8266 boards. That is a more powerful processor with WiFi already inside. I think the Arduino WiFi shield is way to expensive.

I'm in the same boat as you (SW engineer by trade who likes to tinker with electronics, and is a "maker" at heart.)
I think the answer to your question is "it depends." For a one-off, a breadboard might be fine.
For half-a-dozen, you might want to get project cases and perf-boards, and solder up your design. (For the Mega, there is a very nice prototyping "shield" that brings all the pins from the Mega up on headers and has quite a bit of working room for soldering up circuits.) If you want to make more than a handful, though, you'd probably want to create a custom PC board. You can either create a design in a CAD program and send it off to be small-batch manufactured, or you can buy the equipment to do it yourself. If you make hundreds of units, you should think about ditching the Arduinos and designing a completely custom board using the AVR-family microcontroller and only the components you need.
(I'm still at the breadboard/hand soldered perf-board stage myself, and haven't created any custom PC boards yet, just read about it.)

The "final" form of an Arduino "project" is not an Arduino project at all.
Arduino and the associated shields and breadboards are just development tools. They are intended to be used during development only.
As soon as you want to take the next step (certainly if you don't want to be laughed at by professionals) and create a product you need to learn about building your own PCBs. That means taking the schematics of all the shields and boards you are using and combining them all into one schematic, then designing a board from that schematic - and that, of course, means being able to understand what a schematic means.
It's kind of like taking the step from playing with LEGO® to building a house (or a garden shed maybe). There's a lot of learning you have to go through between the two stages.
There are plenty of online resources to get you started with schematic design and PCB layout, but to do it properly takes years of proper training. If you are serious about moving from just tinkering as a hobby you should consider formal training with a reputable educational establishment.

Or, hire a hardware designer for a few hours to combine the various bits that make up the working project into one PCB and order a batch of boards built up.

Indeed. As a hardware designer I didn't want to mention that lest it be seen as advertising.


text:
let Arduino limit it's own input power
My current project will be sitting next to a 12VDC power line. It seems a waste no to tap it to power into the Arduino board too. Now I read everywhere that with 12V input quite  a lot power gets dissipated by the voltage regulator. Wouldn't it then a wise move to use the board 's own PWM capabilities to throttle the input voltage?
Nother point is whether it is sensible at all when the board is using little current (in this case less than 5mA over the pins for 0.1 sec every few seconds, plus the board in deep sleep mode).

You could use a 12V to 5V or 3.3V Buck Converter Module ($0.84CDN) https://www.aliexpress.com/item/Mini-DC-DC-12-24V-To-5V-3A-Step-Down-Power-Supply-Module-Buck-Converter-Adjustable/32821900056.html

If there isn't a lot connected to the Arduino, that is not a lot of current is used, then the loss will also be minimal. (12-5)*current. Let's say the Arduino Uno uses 50ma. You'd end up with a loss of 0.350Watt. Not a lot, so the regulator will only get a bit warm. The problem is that some people will connect a 12V power supply, and then run a string of leds from the regulated 5V pin. Resulting in a lot of wasted power in the form of heat. So much heat that the regulator burns out.

Thanks @Gerben, this is reassuring. I thought so, but wasn't too confident about it. VE7JRO: at the moment the price is no issue with the Chinese parts, but shipping times have increased to well over a month. If I could take a shortcut as outlined here, I would prefer that. But not yet in this project, so.

How did you measure that it's going to be 5mA? Because if that's really the case, the regulator dropping 7V (I'm assuming it's a regular 5V arduino) will need to dissipate ~35mW of heat which is not much and it should not cause a lot of problems for your board.
Another option would be using a step-down power supply module, there are tons of available dc-dc converters, mostly based on LM2596 (search for LM2596 DC-DC module) which will handle your 12 power rail with ease.

There are some models of clone boards that have a DC-DC switching regulator instead of linear regulators to do just that.  The extra cost for the regulator chip, inductor, diode, etc. are probably not worthwhile in the majority of applications tho.


text:
CPU information on Arduino Serial Monitor
how to show the
CPU temperature,
CPU usage (percentage) and
the memory usage(percentage)
in Arduino Serial Monitor.

an Arduino does not have a CPU

@jsotola Yes it does.

CPU temperature
Some Arduino boards have a microcontroller with a temperature sensor inside. For example the Arduino Uno can measure the temperature inside the microcontroller.
As far as I know, no one uses it. It is not accurate and a microcontroller should not get hot in the first place. The microcontroller or processor on the Arduino board can run at 100% load and it does not get hot.
The internal temperature sensor is not accurate enough to measure the ambient temperature.
The internal temperature is therefore (almost) useless.
See this page on the Arduino Playground and this forum thread for the internal temperature sensor.
CPU usage
There is no CPU usage. There is no idle task. The microcontroller or processor usually runs all the time at full speed.
It is possible to determine how long the Arduino board stays in delays (via the yield function).
With a external RTC clock it is possible to determine how long the Arduino board stays in sleep mode (some battery powered Arduino projects use the sleep mode).
However, those are very specific things. Perhaps a project requires to measure them, but there is no common use for them.
A good sketch is not supposed to do nothing, it is supposed to check all the inputs and check millis-timers and act if needed. The Arduino loop() function is supposed to run as often as possible to make the Arduino run fast and smooth.
Memory usage
The memory usage is something to be aware of when writing a sketch. An Arduino board has much less memory than a typical computer.
It is possible to determine the unused memory between the stack and the heap.
The function at the bottom of this page can be used to determine the amount of free memory.
I have also seen code to measure the high water mark (memory that is never used at all), but none of them work for all Arduino boards and the code is not reliable.


text:
Read Serial data from an arduino with c code
I am trying to receive data through the serial port from my SBC (a TS-7200), i am working with linux and handle serial communication using C/C++.To send data to the SBC  i'am using an arduino uno.
So basically the arduino is printing ASCII text data through Pin1 (Hardware Serial) in a loop with a 3ms delay.
From the SBC i read raw data in no canonical mode, ( in the code below are the parameters and configurations for the serial port) i'am trying to read one characters at a time, following the example from this page :
https:/ from this page/chrisheydrick.com/2012/06/17/how-to-read-serial-data-from-an-arduino-in-linux-with-c-part-3/.
but when i run the code it print the number 2 as 3, and the number 3 as f, I am not able to read ASCII characters.
I have tried several things but I have not been able to find the problem, Hope someone can help me.
Here is the Arduino code:
 #include <SoftwareSerial.h>
 SoftwareSerial mySerial(2,3); // RX, TX

 void setup() {

    Serial.begin(9600);
    mySerial.begin(9600);

  }

 void loop() {

   Serial.print(2);

   delay(3000);

   Serial.print(3);

   delay(3000);

}

The c code from the linux side:
#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <termios.h>

char *portname = "/dev/ttyAM1";
char buf[256];

int main(int argc, char *argv[])
{
  int fd,stop = 0;

/* Open the file descriptor in non-blocking mode */
fd = open(portname, O_RDWR | O_NOCTTY);

/* Set up the control structure */
struct termios toptions;

/* Get currently set options for the tty */
tcgetattr(fd, &toptions);

/* Set custom options */

/* 9600 baud */
cfsetispeed(&toptions, B9600);
cfsetospeed(&toptions, B9600);
/* 8 bits, no parity, no stop bits */
toptions.c_cflag &= ~PARENB;
toptions.c_cflag &= ~CSTOPB;
toptions.c_cflag &= ~CSIZE;
toptions.c_cflag |= CS8;
/* no hardware flow control */
toptions.c_cflag &= ~CRTSCTS;
/* enable receiver, ignore status lines */
toptions.c_cflag |= CREAD | CLOCAL;
/* disable input/output flow control, disable restart chars */
toptions.c_iflag &= ~(IXON | IXOFF | IXANY);
/* disable canonical input, disable echo,
   disable visually erase chars,
   disable terminal-generated signals */
toptions.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
/* disable output processing */
toptions.c_oflag &= ~OPOST;

/* wait for 1 character to come in before read returns */
/* WARNING! THIS CAUSES THE read() TO BLOCK UNTIL ALL */
/* CHARACTERS HAVE COME IN! */
toptions.c_cc[VMIN] = 1;
/* no minimum time to wait before read returns */
toptions.c_cc[VTIME] = 0;

/* commit the options */
tcsetattr(fd, TCSANOW, &toptions);

/* Wait for the Arduino to reset */
usleep(1000*1000);
/* Flush anything already in the serial buffer */
tcflush(fd, TCIFLUSH);

while(stop == 0){

  /* read up to 128 bytes from the fd */
  int n = read(fd, &buf, 128);
  usleep(3000*1000);
  /* print how many bytes read */
  printf("%i bytes got read...\n", n);
  /* print what's in the buffer */
  printf("Buffer contains...\n%s\n", buf);
 }
 return 0;
}

This is what i see:
2 bytes got read...
Buffer contains...
f
2 bytes got read...
Buffer contains...
3
2 bytes got read...
Buffer contains...
f
2 bytes got read...
Buffer contains...
3

has the TS-7200 a TTL Serial interface?

Hello Juraj,  no, it doesn't have a TTL  interface, only have 3 serial interface :
ttyAM0 (COM1), ttyAM1 (COM2), ttyAM2 (COM3) .

then how do you wire it to TTL Serial pin on Arduino?

I have a db9 connector, connected to the serial port COM2 of the SBC, using the r232 pinout. The transmition pin1 of the arduino (TXD) is connected to pin2 (RXD) of the db9 connector and the ground pin5 connected to the ground of the arduino .

RS232 uses +/- 12V (or sometimes +/- 5V), and is not compatible with TTL Serial, which uses 0V/5V. Also +12V in RS232 represents 0 and -12V represents 1; inverted from normal TTL.

Thank you very much jose can u c, that was the problem.

RS232 uses +/- 12V (or sometimes +/- 5V), and is not compatible with TTL Serial, which uses 0V/5V. Also +12V in RS232 represents 0 and -12V represents 1; inverted from normal TTL.


text:
Serial.print prints but lcd.print does not
The following code reads a txt file from a SD card, finds the corresponding character and prints the next 12 characters:
...
      char temp;
      byte who = random(1, 13); // 1 to 12
      temp = findName(who);
      Serial.print(who);
      Serial.print("  ==> ");
      Serial.println(temp);
...

    char findName (byte number) {
      char text[12];
      byte i;
      txt = SD.open("test.txt");
      txt.seek(12 * (number - 1));
      for (i = 0; i < 11; i++) text[i] = txt.read();
      txt.close();
      return text;
    }

But the following, on a LCD, does not. (setCursor, etc. ommited for clarity)
...
char temp;
byte who = random(1, 13); // 1 to 12
temp = findName(who);
lcd.print(who);
lcd.print("  ==> ");
lcd.print(temp);
...

I'm certain the cause is a variable data type mismatch, but I don't know how to solve it. Any help is appreciated.
Thank you.

what is the variable lcd

how do you know that your LCD works? ... run the LCD example sketch in the Arduino IDE to make certain

the LCD does work. The variable is a char array, made by the findName() routine.

lcd type and library?

The variable is a char array ... so, why would a char array have a print method?

Juraj, regular character lcd on i2c bus, library is LiquidCrystal_I2C.h. Jaromanda X, should I convert it to a String? If so, how? Thank you.

In the findName() function, you declare a char array of name text. Internally, text is a pointer to a block of memory 12 bytes in size.
When you return text within the findName() function, you are passing back the pointer to the block of memory. The return type of char is inconsistent with the return command. But probably more problematic is that once findName() ends, the memory set aside for the text array is marked as unused. It is no longer reserved for holding anything and may be reallocated at any time by some other function or operation.
In C/C++, array variables do not refer to the entire array, but to the first element in the array. The fact that your program works with Serial.print() is probably just good luck. lcd.print() may declare some variable or buffer which overwrites what the findName() function had put in those 12 bytes.
There are many approaches to take to resolve this. One way is to declare char arrays in the "highest" scope in which it will be used, and to declare it with the largest size that you could ever see in the operation of your program.
In your case, you can:
...
      char temp[12];
      byte who = random(1, 13); // 1 to 12
      findName(temp, who);
      Serial.print(who);
      Serial.print("  ==> ");
      Serial.println(temp);
...

    void findName (char *text, byte number) {
      byte i;
      txt = SD.open("test.txt");
      txt.seek(12 * (number - 1));
      for (i = 0; i < 11; i++) text[i] = txt.read();
      txt.close();
    }

What this does:

temp is now the char array
findName() takes the pointer to the char array, and the number as arguments
findName() modifies text, which refers to the same block of already-allocated memory as temp, and that block of memory does not go away at the end of findName().
Because findName() is not returning a value, it's return type is void.

Thank you, sir! Learned a lot from your answer and your snippet finally solved the issue. Now I can finally proceed. Thanks again.


text:
Array is affecting digitalread values
i want to turn on an led with two buttons. If either of the buttons is pressed i want the led to turn on while the button is pressed and stay off if nothing is pressed. i have two sets of code, they both do the same thing, but the second set of code causes the led to stay in the on position even when nothing is being pushed and i dont understand why.. i am using pulldown resistors on both the buttons.
This is the first set of code that works properly:
class Button {

  public:

    int pin;
    int state;
    int location;
    int Speed;
    int Direction;
    int active;
    int prevstate;

    Button(int pin1, int state1, int location1, int active1, int previousState)
    {
      pin = pin1;
      state = state1;
      location = location1;
      active = active1;
      prevstate = previousState;
    }
};

Button button(7,0,0,0,0);
Button button2(8,0,0,0,0);
Button buttons[2] = {button, button2};

void setup() {
      pinMode(ledPin, OUTPUT);
}

void loop() {
   if (digitalRead(button2.pin) == HIGH){
             digitalWrite(ledPin, HIGH);
          } else {
          // turn LED off:
          digitalWrite(ledPin, LOW);
          }
       if (digitalRead(button.pin) == HIGH){
             digitalWrite(ledPin, HIGH);
          } else {
          // turn LED off:
          digitalWrite(ledPin, LOW);
          }
}

this is the code i want to use but it is not working.. the led stays in the on position:
void loop(){
  for (int i = 0; i<sizeof(buttons); i++){
    if(digitalRead(buttons[i].pin) == HIGH){
          digitalWrite(ledPin, HIGH);
          } else {
          // turn LED off:
          digitalWrite(ledPin, LOW);
          }
    }
}

also if i change
if(digitalRead(buttons[i].pin) == HIGH)

to
if(digitalRead(buttons[0].pin) == HIGH)

the code works for the first or second button alone in the array.. but not both???

sizeof(buttons) is not the count of elements in the array. it is the size in bytes. so you read some other pins too. use #define BUTTONS_COUNT 2

"If either of the buttons is pressed i want the led to turn on while the button is pressed and stay off if nothing is pressed" - Just put the buttons in parallel and use only 1 I/O pin ;-)

You seem to have made 4 button objects: button, button2, and buttons[2]. buttons[0] and buttons[1] are full button objects whose first member, .pin, is initialized to the addresses of button and button2, respectively. This is probably not what you intended.
Did you mean to create:
Button buttons[2] = {
   {7,0,0,0,0},
   {8,0,0,0,0}
};

, an array of two initialized button objects?

I have to disagree that your first sketch is working. I suppose that a very fast blinking led seems to be "on".
When you describe what should happen in a logic way, then you can put that into code.
The logic is: The led is on, if at least one of the buttons is pressed.
In other words: The led is off, if no button is pressed, else the led is on.
This logic has as a result that the led stays on if a second button is pressed and after that the first button is released. I assume this is okay.
For two buttons it is possible to check both conditions.
if (digitalRead(button.pin) == HIGH || digitalRead(button2.pin) == HIGH)
  digitalWrite(ledPin, HIGH);
else
  digitalWrite(ledPin, LOW);

Or test for LOW:
if (digitalRead(button.pin) == LOW && digitalRead(button2.pin) == LOW)
  digitalWrite(ledPin, LOW);
else
  digitalWrite(ledPin, HIGH);

For multiple buttons, a bool can be used or the number of pressed buttons can be counted.
A fixed number for the array size is easy and has less chance for a mistake:
#define BUTTONS_COUNT 2

It is also possible to use sizeof(). The total size has to be divided by the size of one element:
int count = 0;
for (int i = 0; i<sizeof(buttons)/sizeof(Button); i++) {
  if (digitalRead(buttons[i].pin) == HIGH) {
    count++;
  }
}

if (count == 0)
  digitalWrite(ledPin, LOW);
else
  digitalWrite(ledPin, HIGH);


text:
Installing Arduino IDE in the new Ubuntu Disco Dingo
I tried installing the Arduino IDE in the newly released Ubuntu 19.04 Disco Dingo.
I downloaded the file from the official downloads page. I chmod +x ed the file and ran the install script. Then, it says:
Adding desktop shortcut, menu item and file associations for Arduino IDE...
rm: cannot remove '/usr/local/bin/arduino': No such file or directory
Removing symlink failed. Hope that's OK. If not then rerun as root with sudo.
touch: cannot touch '/root/.config/mimeapps.list': No such file or directory

/usr/bin/xdg-mime: 848: /usr/bin/xdg-mime: cannot create/root/.config/mimeapps.list.new:
Directory nonexistent`
Then, I again ran it as root user with su root but it still gave the same error...
Will this cause a problem..? I mean, I had prior issues related to uploading the sketch in earlier Linux IDE installations. Will this cause a problem...?
`

It is not required to run the installer. You may unpack it in a folder (under your $HOME folder, not a system folder) and make a shortcut (symbolic link) to the 'arduino' file. Put the shortcut on the desktop. Perhaps add yourself to the DIALOUT group and perhaps a permission has to be added when using a programmer to burn the bootloader.


text:
Problem with ESP8266, wrong voltage?
I recently bought a new ESP8266 because I'm pretty sure I used 5V instead of 3.3V on my old one.
But it seems the new one behaves the same as the old one.
I'm using the sketch:
https://i.sstatic.net/BZRd4.jpg
When I open up the serial monitor and type [b]AT [/b]I get not response (on the 115200 baud).
If I boot up the power supply while the device is connected I get this in the serial monitor:
load 0x40100000, len 1856, room 16
tail 0
chksum 0x63
load 0x3ffe8000, len 776, room 8
tail 0
chksum 0x02
load 0x3ffe8310, len 552, room 8
tail 0
chksum 0x79
csum 0x79

2nd boot version : 1.5
  SPI Speed      : 40MHz
  SPI Mode       : DOUT
  SPI Flash Size & Map: 8Mbit(512KB+512KB)
jump to run user1 @ 1000

Fatal exception 0(IllegalInstructionCause):
epc1=0x40215021, epc2=0x00000000, epc3=0x00000000, excvaddr=0x00000000, depc=0x00000000

When I googled the log it seems to be related to the voltage. Could it be the same problem again? If so, what did I do wrong?

The ESP8266 has a relatively high peak current requirement compared to general microcontrollers. This is rarely fully understood. There is a lot of information on the Internet that says the current requirements is about 70mA. But that is a long term operational average. The peak current requirements can be as high as 1/2 an Amp.
When the ESP8266 starts one of the first things it does is an analog calibration. This is where it draws more current. If the power supply can not maintain the minimum required voltage at that current the voltage dip will cause a failure. The duration of this dip can be very short. A digital scope needed to see the fault.
I tend to recommend the use of ESP8266 modules that have an onboard regulator. Modules like the Wemos and Nodemcu type boards.
Using modules like the ESP-01 or the ESP-12 type modules (no regulators) are a lot more touchy. What you need to do is keep the 3.3v regulator as close as possible to those modules, and short solid connections. It also helps to have some additional capacitance across the 3.3v connections at the module.
Breadboards are convenient to use but they also can be the source of poor connections.
Consider what I have wrote here, how it applies to your setup. You may also want to solder an additional capacitor on the module. Vcc to ground. Something like 200-470uF, right onto the top of the module.


text:
VNH2SP30 Motor Driver not working in reverse
I bought 2 new VNH2SP30 Motor Drivers because i thought the first one was broken but they are both giving me the same issue, they run in forward direction but not reverse...
When the motor is unplugged the forward led is bright green, when the code executes the reverse direction, the reverse led is lit very dimly and multi meter measures no voltage.
I have tried:

changing power source and voltage
using different cables and pins
using different motors
using different code
using different VNH2SP30 Motor Driver
using different arduino

here is the code:
  #define INA 5 // outputs arduino
 #define INB 7
 #define EN 8
 #define PWM 11

 int motorSpeed = 255 ;  // motor speed

 void setup ( ) {
  pinMode ( INA , OUTPUT ) ;
  pinMode ( INB , OUTPUT ) ;
  pinMode ( EN , OUTPUT ) ;

  digitalWrite ( EN , HIGH ) ;
 }

 void loop ( )
 {
  digitalWrite ( INA , LOW ) ;  // turn the motor in one direction
  digitalWrite ( INB , HIGH ) ;
  analogWrite ( PWM , motorSpeed ) ;
  delay ( 1000 ) ;

  digitalWrite ( INA , HIGH ) ;  // turn the engine in the opposite direction
  digitalWrite ( INB , LOW ) ;
  analogWrite ( PWM , motorSpeed ) ;
  delay ( 1000 ) ;

  digitalWrite ( EN , LOW ) ;  // turn off
  delay ( 1000 ) ;
  digitalWrite ( EN , HIGH ) ;

 }

Heres the wire diagram but my outputs are just on different pins.

posting an incorrect wiring diagram is pointless

documentation on the web indicates that there are two EN pins

there are two variations of this driver, there is another that drivers 2 motors, this drives only one

There appears to be quite a few faulty drivers such as this one currently on Aliexpress. Of the 4 I have bought, only one works - the other three function exactly as you described.
Same program, same motor, same control wiring as the one which works.
I can only suggest try to buy from a different seller on ebay or ali; or of course pay top dollar for a chip from a reputable source.


text:
How to handle concurrent HTTP request when using interrupt
I'm trying to make a door sensor with a reed switch. Each time the there is a change, the ESP8266 sends an HTTP request to web service.
Unfortunately, the ESP8266 serial monitor dumps a huge stack trace when I'm approaching the magnet to the reed switch:
Exception (9):
epc1=0x40104b14 epc2=0x00000000 epc3=0x00000000 excvaddr=0x00000003 depc=0x00000000

ctx: sys
sp: 3fffeb20 end: 3fffffb0 offset: 01a0

>>>stack>>>
3fffecc0:  00000002 00000006 3ffefdc4 40227108
3fffecd0:  3ffefa74 00000002 00000014 401004e4
3fffece0:  3ffeffbc 3ffeffc0 00000006 00000001
3fffecf0:  402253bc 00000000 00000010 00000000
3fffed00:  00000000 4bc6a7f0 81cac083 00000000
3fffed10:  00000000 00000000 4bc6a7f0 00000000
3fffed20:  40104d40 0037d809 3ffeecd0 00000000
3fffed30:  3ffee520 3ffeecd0 3ffeffbc 40224398
3fffed40:  00000000 00200085 40201578 00001388
3fffed50:  3ffeecd0 00000000 00000050 00000050
3fffed60:  00000000 3fffedd0 3ffefd34 402032e5
3fffed70:  1301a8c0 00000031 3ffeebbc 402039cc
3fffed80:  3ffeedb8 000000ef 000000ef 00000020
3fffed90:  ffffffff 00000050 3fffedd0 40202d5c
3fffeda0:  40204738 1301a8c0 40204738 1301a8c0
3fffedb0:  3ffe8a64 00000005 000...

I think it's because the ESP8266 tries to make concurrent HTTP calls...
How can I solve this?
Here is the code:
// https://www.instructables.com/id/Arduino-Software-debouncing-in-interrupt-function/
// #include "util/atomic.h"
#include "ESP8266WiFi.h"
#include "ESP8266HTTPClient.h"
#include "Wire.h"

const char* ssid = "****";
const char* pass = "****";
const byte interruptPin = 5;
long debouncing_time = 50; //Debouncing Time in Milliseconds
volatile unsigned long last_micros;
const char* host= "192.168.1.19";
const char* doorStates[2] = {"closed", "opened"};

void connection()
{
  // Establish a WIFI connection
}

void setup()
{
  Serial.begin(115200);
  connection();
  pinMode(interruptPin, OUTPUT);

  // Attaching interrupt
  attachInterrupt(digitalPinToInterrupt(interruptPin), handleInterrupt, CHANGE);
}

void loop()
{
  delay(1000);
}

void handleInterrupt() {
  if ((long)(micros() - last_micros) >= debouncing_time * 1000) {
    int val = digitalRead(interruptPin);
      notify(val);
  }
  last_micros = micros();
}
// Make HTTP Call to web service
void notify(int val)
{
  WiFiClient client;
  const String frontDoorState = doorStates[val];
  String url = "http://192.168.1.19/alarm/front-door/state/" + frontDoorState;
  client.connect(host, 80);
    client.print(String("GET ") + url + " HTTP/1.1\r\n" +
                 "Host: 192.168.1.19\r\n" +
                 "Connection: close\r\n\r\n");
                 client.stop();
}

Simple: don't do HTTP requests in the interrupt.
It's usually bad to do anything heavy like that in an interrupt.  Instead you should just set a flag in the interrupt (volatile bool) and examine that flag in loop().
volatile bool sendNotification = false;
volatile int notifyVal = 0;

void loop() {
    if (sendNotification) {
        notify(notifyVal);
        sendNotification = false;
    }
}

void handleInterrupt() {
    if ((long)(micros() - last_micros) >= debouncing_time * 1000) {
        notifyVal = digitalRead(interruptPin);
        sendNotification = true;
    }
    last_micros = micros();
}

Indeed, it was simple :) Thank you. I might need some kind of queue in this case. if the reed switch is open/close very quickly, the state variable might be changed in the meantime.

Indeed it might. In that case, instead of a queue, why not just a count? If it's currently HIGH and there have been 3 transitions, you know they would have been HIGH, LOW, HIGH to get to where you are now. Reset the count as you send it.


text:
How to drive N channel gate correctly from Adafruit Feather pinout?
I am learning how to create a soft latch power switch, using an N channel mosfet.
Currently, I have this:

simulate this circuit – Schematic created using CircuitLab
The idea is (so far) that I can turn it on with the switch, the Arduino immediately brings the power control high (ensuring the FET stays on), and brings that same pin low after 1.5s (simulating a timed shutdown).
However; when the power control goes low, I still see about 1.8v in the power control line (I'm presuming its floating?), which leaves this particular FET partially open.
If I disconnect the power control line from the MCU, I get the behaviour I expect. I can touch the power control to +ve and the FET will switch on.  If I lift the control line from +ve, the FET closes the gate, due to the pull down resistor.
I'm struggling to understand why the FET works in isolation, but does not work when connected to the MCU output pin.  The pinMode is OUTPUT.
FET (3055VL): https://www.onsemi.com/pub/Collateral/MTP3055VL-D.PDF
Here's the test code I'm using.
It simply flashes a build in LED 10 times then does a power off.
int ledPIN = 17;
int controlPin = 11;
int lDelay = 150;

bool shouldBeUp = true;

void setup()
{
  pinMode(ledPIN, OUTPUT);
  pinMode(controlPin, OUTPUT);
  digitalWrite(controlPin, HIGH);
}

void loop()
{
  if (shouldBeUp) {
    for (int i = 0; i < 10; i++)
    {
      digitalWrite(ledPIN, LOW); // on
      delay(lDelay);
      digitalWrite(ledPIN, HIGH); // off
      delay(lDelay / 2);
    }

    // Leave the LED low
    digitalWrite(ledPIN, LOW);
    digitalWrite(controlPin, LOW);
    shouldBeUp = false;
  }
}

Any help is appreciated! Thank you :)

Your problem is that the GPIO pin is referenced to ground - and the MOSFET is isolating that ground.
You need instead to switch the power not the ground - and for that, you use a P-channel MOSFET.

simulate this circuit – Schematic created using CircuitLab
To hold the power on you now set the GPIO LOW instead of HIGH.
If you need to switch a higher voltage than the operating voltage of the MCU you will need to add another N-channel MOSFET to pull down the P-channel's gate.

Thanks for this. I have a p-channel on the way to try this out.   Does that mean a circuit such as described here (https://www.youtube.com/watch?v=0IjJH3ksqfs) see 1:27m, would also not work, since the PWR_CTRL would have the same problem?

That circuit is what I mean when I refer to adding an n fet for switching a higher voltage.


text:
WIFI Bee ESP8266, MySQL and PHP
I am trying to update a db table using a WIFI Bee.
For the life of me, I can't figure out how to connect to and program the WiFi Bee ESP card. I've looked on DFRobot's website and other websites to no avail.
The PHP code is
try {
        include "../Common/ConnectionStringArduino.php"; // Create a connection

        // Update state
        $sql    = "Update `Status` SET `DateTime`='".time()."',`State`='".$_GET["CurrentState"]."' WHERE `Device`='Arduino';";
        $result = $con->query( $sql ); if($result === FALSE) { die(mysqli_error());}
        mysqli_close($con);
        echo "Success";
    } catch (Exception $e) {
        echo "Error";
    };

If i call the page by typing the URL of this page on a browser window it updates the database on a Raspberry Pi but so far I had no luck in doing it via the WiFi Bee module.
I have a Rome v2 board with inbuilt WiFi Bee socket.
I am familiar with AT commands (but not a ginus)
My Arduino code
#include "esp8266.h"

#define ssid "XXX"
#define pass "YYY"
Esp8266 wifi;

void setup() {
  delay(2000);            // It will be better to delay the setup for 2 seconds for esp8266 module to initialize
  Serial.begin(9600);     // Terminal serial port baud rate for USB debugging on the pc serial monitor
  Serial1.begin(115200);  // Xbee Serial port baud rate should be set the same to 115200

  // Items for WiFi Communication
  wifi.begin(&Serial1, &Serial);    // Setup the WiFi to use Setial1 and Serial to debug
  if (wifi.connectAP(ssid, pass)){  // Connect to the AP
    wifi.debugPrintln("Connection to AP sucessful!");
  } else {
    while(true);
  };
  wifi.debugPrintln("esp8266 ip:" + wifi.getIP());
  wifi.setSingleConnect();
  if (wifi.connectTCPServer("192.168.1.17", "80")) { wifi.debugPrintln("Connection to Pi Successful!");}
  else                                             { wifi.debugPrintln("Connection to Pi Failed!!!");};
}

void loop(){
  if(Serial1.available()) {
   ....
   For god sake how do I call this page : "http://192.168.1.17/Arduino/IAmAlive.php?CurrentState=1" to update the database entry using this beeeeeee
   ....
  }
}

The bee gets an IP upon successful connection
Connection to AP successful!
esp8266 ip:192.168.1.23

and i can ping the bee
Reply from 192.168.1.23: bytes=32 time=78ms TTL=255
Reply from 192.168.1.23: bytes=32 time=99ms TTL=255
Reply from 192.168.1.23: bytes=32 time=25ms TTL=255
Reply from 192.168.1.23: bytes=32 time=6ms TTL=255

But have no idea how to call the page to update the db. I have read endless blogs with no luck of solving my simple issue
Please help


text:
Using Arduino as ISP and SoftwareSerial at the same time
I'm trying to use my Arduino Uno as an ISP to program an ATTiny85 and at the same time check my board by using the SoftwareSerial library to output the values I'm getting from my sensor.
Is this actually possible? Or does it require 2 different setups? Because I found a lot of tutorials and threads about one or the other, but never both. Which I find odd because once you send your program to the chip you might want to test it as well (or debug it).
Many thanks for your help and input! :)

Sure you can. You'd need to modify the ArduinoISP sketch to include whatever serial functionality you desire.

Would adding a code like that work for example?
`#include <SoftwareSerial.h>
char anyChar;
void setup(){
Serial.begin(9600);   //to serial monitor
Serial1.begin(9600);  //connected to Attiny (RX to tx and TX to rx)
}
void loop(){
if(Serial1.available() >0) {
anyChar = Serial1.read();
Serial.print(anyChar);
}
}`

Possibly, though it may interfere with ISP programming. You should provide a facility (maybe a switch connected to a GPIO pin) to switch between programming and testing mode.

To keep things simple I would recommend using two Arduino's. One for the ISP and one for the test harness. Alternatively @Majenko's suggestion using a GPIO pin and switch to toggle between to two modes (programming and test harness).

I'm not really sure, but in the Arduino ISP example there is an if that looks if the ISP is in program-mode. You could try adding in the else statement of that if the Software Serial part.


text:
Switch statement cases not executing
Overview:
I am trying to use a switch statement to run different tests. A main menu is displayed on the serial monitor, and then the user is given the option to enter their menu choice in the serial monitor. The menu choice entered in the serial monitor should subsequently run the appropriate case statement.
Issues:
 1. When I enter a choice the case statement for that choice does not run
 2. When I enter a choice my the serial monitor scrolls through my menu 3 times displaying 49, then 13, then 10.
Questions:

Why are my case statements not executing?
Why does the serial monitor scroll three times displaying these random numbers?
//////////////PREPROCESSOR DIRECTIVES/////////

#include <Wire.h>

/////////////GLOBAL VARIABLES////////////////

int ADDRESS_SLAVE = 0x08;
int ADDRESS_VERSION = 0x00;
int ADDRESS_STATUS = 0x01;
int ADDRESS_ENABLE = 0x02;
int ADDRESS_CONFIG = 0x03;
int ADDRESS_RESTART = 0x04;
int ADDRESS_STARTUP_STATE = 0X05;
int ADDRESS_COMPENDISREG1 = 0X07;
int ADDRESS_COMPENDISREG2 = 0X08;
int ADDRESS_COMPENDISREG3 = 0X09;
int ADDRESS_COMPENDISREG4 = 0X0A;
int ADDRESS_FAULT = 0X0B;
int ADDRESS_FAULTMASK = 0X0C;
int ADDRESS_TEST_MODE = 0X0D;

////////////SETUP CONDITIONS/////////////////

void setup()
{
 Wire.setClock(100000);
 Wire.beginTransmission(byte(ADDRESS_SLAVE));
 Serial.begin(9600);
}

////////////MAIN FUNCTION///////////////////

void loop()
{

  int choice = 0;

  int const
            //Clock 100
            CLOCK_FREQ_P = 101,
            CLOCK_FREQ_DIV4 = 102,
            CLOCK_FREQ_DIV8 = 103,
            CLOCK_FREQ_DIV16 = 104,
            CLOCK_FREQ_DIV32 = 105,
            CLOCK_INT_SUPPLY_IBIAS = 106,
            CLK_OK = 107,

            //Bandgap 200
            BG_2p5V = 200,
            BG_MAX_LOAD = 201,
            BG_VBE = 202,
            BG_VP = 203,
            BG_VGATE = 204,
mainMenu();

   choice = menuChoice();

   switch(choice)
   {
    case CLOCK_FREQ_P :
    {
      Serial.println(F("CLOCK_FREQ_P Not yet built out"));
      while(Serial.available() > 0)
        {
           int choice = Serial.read();
        }

      delay(10000);
    }
    break;

    case CLOCK_FREQ_DIV4:
    {
      Serial.println(F("CLOCK_FREQ_DIV4 Not yet built out"));
    }
    break;

    case CLOCK_FREQ_DIV8:
    {
      Serial.println(F("FREQ_DIV8 Not yet built out"));
    }
    break;

    case CLOCK_FREQ_DIV16:
    {
      Serial.println(F("CLOCK_FREQ_DIV16 Not yet built out"));
    }
    break;

    case CLOCK_FREQ_DIV32:
    {
      Serial.println(F("CLOCK_FREQ_DIV32 Not yet built out"));
    }
    break;

    case CLOCK_INT_SUPPLY_IBIAS:
    {
      Serial.println(F("CLOCK_INT_SUPPLY_IBIAS Not yet built out"));
    }
    break;

    case CLK_OK:
    {
      Serial.println(F("CLK_OK Not yet built out"));
    }
    break;

    case BG_2p5V:
    {
      Serial.println(F("BG_2p5V Not yet built out"));
    }
    break;

    case BG_MAX_LOAD:
    {
      Serial.println(F("BG_MAX_LOAD Not yet built out"));
    }
    break;

    case BG_VBE:
    {
      Serial.println(F("BG_VBE Not yet built out"));
    }
    break;

    case BG_VP:
    {
      Serial.println(F("BG_VP Not yet built out"));
    }
    break;

    case BG_VGATE:
    {
      Serial.println(F("BG_VGATE Not yet built out"));
    }
    break;

    delay(500);
}

////////////////FUNCTIONS/////FUNCTIONS/////FUNCTIONS/////FUNCTIONS///////////////////////////

//*******************************************
//**      Function: Main Menu Display
//**      Passes: nothing
//**      Returns: nothing
//*******************************************

void mainMenu()
{
  //Prints main menu to the serial monitor
  Serial.println();
  Serial.println(F("\t\t\t\t\t\t\t\t\t\t       ******************************"));
  Serial.println(F("\t\t\t\t\t\t\t\t\t\t       ******************************"));
  Serial.println(F("\t\t\t\t\t\t\t\t\t\t       **         MAIN MENU        **"));
  Serial.println(F("\t\t\t\t\t\t\t\t\t\t       ******************************"));
  Serial.println(F("\t\t\t\t\t\t\t\t\t\t       ******************************"));
  Serial.println();
  Serial.println(F("\t\t\t\t\t\t ********************************************************************************************************************"));
  Serial.println(F("\t\t\t\t\t\t **   Please type in the number of the test you want to run in the command line window at the top of the screen.   **"));
  Serial.println(F("\t\t\t\t\t\t ********************************************************************************************************************"));
  Serial.println();
  Serial.println();
  //                                        ******************
  //                                        ***  TOP MENU  ***
  //                                        ******************

  Serial.print(F("\t\t\t CLOCKGEN \t\t\t\t BANDGAP \t\t\t GPIO "));
  Serial.println();
  Serial.print(F("\t\t\t   (1) CLK_FREQ_P \t\t\t   (8) BG_2p5V \t\t\t   (13) GPIO0_PD \t (21) GP1_N_Buff \t (29) GP2_Buff_Max \t  "));
  Serial.println();
  Serial.print(F("\t\t\t   (2) CLK_FREQ_Div_4 \t\t\t   (9) BG_MAX_LOAD \t\t   (14) GPIO0_PU \t (22) GP1_W_Buff \t (30) GP2_Buff_Min "));
  Serial.println();
  Serial.print(F("\t\t\t   (3) CLK_FREQ_Div_8 \t\t\t   (10) BG_VBE \t\t\t   (15) GP0_N_Buff \t (23) GP1_Buff_Max \t (31) GPIO3_PD ") );
  Serial.println();
  Serial.print(F("\t\t\t   (4) CLK_FREQ_Div_16 \t\t\t   (11) BG_VP \t\t\t   (16) GP0_W_Buff \t (24) GP1_Buff_Min \t (32) GPIO3_PU "));
  Serial.println();
  Serial.print(F("\t\t\t   (5) CLK_FREQ_Div_32 \t\t\t   (12) BG_VGATE \t\t   (17) GP0_Buff_Max \t (25) GPIO2_PD \t\t (33) GP3_N_BUFF "));
  Serial.println();
  Serial.print(F("\t\t\t   (6) CLK_INT_Supply_(IBias)\t\t\t\t\t\t   (18) GP0_Buff_Min \t (26) GPIO2_PU \t\t (34) GPIO3_W_BUFF "));
  Serial.println();
  Serial.print(F("\t\t\t   (7) CLK_OK \t\t\t\t\t\t\t\t   (19) GPIO1_PD \t (27) GP2_N_Buff \t (35) GP3_BUFF_Max "));
  Serial.println();
  Serial.print(F("\t\t\t\t\t\t\t\t\t\t\t\t   (20) GPIO1_PU \t (28) GP2_W_Buff \t (36) GP3_BUFF_Min "));
  Serial.println();
  Serial.println();
  //                                        *********************
  //                                        ***  CENTER MENU  ***
  //                                        *********************

  Serial.print(F("\t\t\t VBUS COMPARITOR \t\t\t\t\t\t\t VAC COMPARITOR \t\t ISNS COMPARITOR \t\t TSNS COMPARITOR"));
  Serial.println();
  Serial.print(F("\t\t\t   (37) CLK_FREQ_P \t(47) BG_2p5V \t(57) GPIO0_PD \t\t\t   (61) GP1_N_Buff \t\t  (68) GP2_Buff_Max \t\t   (74) VB 2.715V Comparitor Test"));
  Serial.println();
  Serial.print(F("\t\t\t   (38) CLK_FREQ_P \t(48) BG_2p5V \t(58) GPIO0_PD \t\t\t   (62) GP1_N_Buff \t\t  (69) GP2_Buff_Max \t\t   (75) VB 2.715V Comparitor Test"));
  Serial.println();
  Serial.print(F("\t\t\t   (39) CLK_FREQ_P \t(49) BG_2p5V \t(59) GPIO0_PD \t\t\t   (63) GP1_N_Buff \t\t  (70) GP2_Buff_Max \t\t   (76) VB 2.715V Comparitor Test"));
  Serial.println();
  Serial.print(F("\t\t\t   (40) CLK_FREQ_P \t(50) BG_2p5V \t(60) GPIO0_PD \t\t\t   (64) GP1_N_Buff \t\t  (71) GP2_Buff_Max \t\t   (77) VB 2.715V Comparitor Test"));
  Serial.println();
  Serial.print(F("\t\t\t   (41) CLK_FREQ_P \t(51) BG_2p5V \t\t\t\t\t   (65) GPIO0_PD \t\t  (72) GP1_N_Buff \t\t\t\t"));
  Serial.println();
  Serial.print(F("\t\t\t   (42) CLK_FREQ_P \t(52) BG_2p5V \t\t\t\t\t   (66) GPIO0_PD \t\t  (73) GP1_N_Buff \t\t\t\t"));
  Serial.println();
  Serial.print(F("\t\t\t   (43) CLK_FREQ_P \t(53) BG_2p5V \t\t\t\t\t   (67) GPIO0_PD \t\t\t\t\t"));
  Serial.println();
  Serial.print(F("\t\t\t   (44) CLK_FREQ_P \t(54) BG_2p5V \t\t\t\t\t\t\t\t\t\t\t\t"));
  Serial.println();
  Serial.print(F("\t\t\t   (45) CLK_FREQ_P \t(55) BG_2p5V \t\t\t\t\t\t\t\t\t\t\t\t"));
  Serial.println();
  Serial.print(F("\t\t\t   (46) CLK_FREQ_P \t(56) BG_2p5V \t\t\t\t\t\t\t\t\t\t\t\t"));
  Serial.println();
  Serial.println();
  Serial.println();
  //                                        *********************
  //                                        ***  BOTTOM MENU  ***
  //                                        *********************

  Serial.print(F("\t\t\t QR COMPARITOR \t\t\t ADC \t\t\t MS Driver \t\t\t AC Driver \t\t\t Active Clamp FET \t\t  V10"));
  Serial.println();
  Serial.print(F("\t\t\t   (78) CLK_FREQ_P \t\t  (84) BG_2p5V \t\t  (87) GPIO0_PD \t\t  (96) GP1_N_Buff \t\t  (100) AC_FET_LEAKAGE \t\t   (1400) V10MIN_V10_OK_FAL"));
  Serial.println();
  Serial.print(F("\t\t\t   (79) CLK_FREQ_P \t\t  (85) BG_2p5V \t\t  (88) GPIO0_PD \t\t  (97) GP1_N_Buff \t\t  (101) AC_FET_LEAKAGE_SWEEP"));
  Serial.println();
  Serial.print(F("\t\t\t   (80) CLK_FREQ_P \t\t  (86) BG_2p5V \t\t  (89) GPIO0_PD \t\t  (98) GP1_N_Buff \t\t  (102) AC_FET_RDS_ON"));
  Serial.println();
  Serial.print(F("\t\t\t   (81) CLK_FREQ_P \t\t\t\t\t  (90) BG_2p5V \t\t\t  (99) GPIO0_PD"));
  Serial.println();
  Serial.print(F("\t\t\t   (82) CLK_FREQ_P \t\t\t\t\t  (91) BG_2p5V"));
  Serial.println();
  Serial.print(F("\t\t\t   (83) CLK_FREQ_P \t\t\t\t\t  (92) BG_2p5V"));
  Serial.println();
  Serial.print(F("\t\t\t\t\t\t\t\t\t\t  (93) CLK_FREQ_P"));
  Serial.println();
  Serial.print(F("\t\t\t\t\t\t\t\t\t\t  (94) CLK_FREQ_P"));
  Serial.println();
  Serial.print(F("\t\t\t\t\t\t\t\t\t\t  (95) CLK_FREQ_P"));
  Serial.println();
  Serial.println();
  Serial.println();
  Serial.println();
  Serial.println();
  Serial.println();

}

//*******************************************
//**      Function: menuChoice
//**      Passes: nothing
//**      Returns: integer for menu choice
//*******************************************

int menuChoice()
{
  int selection = 0;

  while (Serial.available() == 0);
  {
  selection = Serial.read();
  Serial.print("You entered: ");
  (int)Serial.println(selection, DEC);
  }
  return selection;
}

49, 13 and 10 are ASCII codes of characters you send from Serial Monitor

Hi Juraj...I understand these are ASCII codes, but it doesnt make sense if I enter 1, I get a 49 (1),13(carriage return), 10 returned (new line). Do have any idea how I can resolve this?

Why are you saying that it doesn't make sense? The codes that you receive are exactly what you typed and sent.

why are you not printing the value of choice right after choice = menuChoice();? .... that is a simple way of debugging the program

I think the issue is with the menuChoice() function. Try replacing it with this:

int menuChoice()
{
  int selection = 0;
  const byte bufferSize = 16;
  char inputBuffer[bufferSize + 1];

  if(Serial.available() > 0){
    // 50 bytes more in compile size using parseInt() vs
    // char buffer and atoi().
    // selection = Serial.parseInt();
    Serial.readBytesUntil('\n', inputBuffer, bufferSize);
    selection = atoi(inputBuffer);
    memset(inputBuffer, 0, sizeof(inputBuffer));
    Serial.print("You entered: ");
    Serial.println(selection, DEC);
  }

  return selection;
}

Of course, you could use parseInt() instead of the char buffer and atoi(), but the compile size is 50 bytes more.

Thanks VE7JRO! The parseInt() function fixed most of this problem. It still seems to pick up the carriage return; I would normally capture the carriage return with cin.get() in C/C++, but I don't know of a similar function available for Arduino. I did try to run the code you provided above, but the menu loops endlessly. Anyway...thanks again for bringing parseInt()to my attention...it helped a bunch!


text:
Can I power a Wemos D1 R2 via the VIN and GND pins?
Can I power a Wemos D1 R2 via the VIN and GND pins?
If so, at what voltage?

Wemos D1 R2 has on-board regulator with input from power jack and Vin pin. The regulator is for 9 to 24 V.


text:
LED not turning on with following code
LED is not turning on with the following code. Have tried multiple LED's and double checked wiring. What's wrong? Using an uno.
int ldr = A1;
int  ldrVal = ldr;
int led = 6;
int lvalue = 900;

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

  Serial.begin(9600);

delay(1000);

}

void loop() {

Serial.println(analogRead(ldrVal));
if (ldrVal > lvalue) {

digitalWrite(led, HIGH);
}
delay (50);

if (ldrVal < lvalue)
{
  digitalWrite(led, LOW);
}
delay (1000);

}

Start by using good names for the variables. Use the term "pin" in the name of a variable that is a pin numer. For example ledPin and ldrPin. Do not mix the value of a sensor with the pin number. The level at which the led is turned on can be called "triggerLevel" or "switchLevel" or something else. Do not use two statements in a single line (for example Serial.print and analogRead). Use the same style for the text everywhere. Use text indents in the same way.

This is incorrect: int  ldrVal = ldr; and this: Serial.println(analogRead(ldrVal)); There is an example sketch (AnalogInput.ino) that comes with the IDE which would be a great starting point.

Your code is wrong. analogRead(ldrVal) does not read the analog pin's value and store it into ldrVal, it is a function who's result is the analog pin value.
Try this edit:
void loop() {

int newValue = analogRead(ldrVal);
Serial.println(newValue);
if (newValue > lvalue) {  //Check newValue, not ldrVal
    digitalWrite(led, HIGH);
}
delay (50);

if (newValue < lvalue)
{
    digitalWrite(led, LOW);
}
delay (1000);
}

Apart from the bad indentation and the bad variable naming, which makes your code not only look ugly, but messy and poorly readable, you have multiple problems in your few lines of code.
One problem is the variable lvalue never gets set, meaning its value remains 900 no matter what's the value you are reading through analogRead().
A second mistake is your ldrVal, which should represent the boundary between lit and powered off, is set to A1, which in turn is a macro define for a valid integer, but a very small value (less than 20).
In other words the code that should decide to turn on/off the LED continously compare 900 and 20 with no opportunity for those values to change: not surprising the LED won't change state, do you agree?
BTW, 50ms is a very short time interval: if you want to be able to see the LED turn on and then off, increase the delay to 200 or more.


text:
Arduino Uno Force-Sensitive Resistor
Would any one know how many Force-Sensitive Resistors that a Arduino Uno can handle being hooked up to at one time?

Theoretically as many as you like. You just have to set your bounds.

what is Force-Sensitive Resistor ..... how does it transmit its data?

@jsotola: it think he's talking about stretchy bands, like used in the power glove. To answer, about 8 without adding additional complexity or cost to the UNO.


text:
No matching function call for timer?
I am using the Timer library here with the Adafruit feather m0:
https://github.com/JChristensen/Timer
https://playground.arduino.cc/code/timer
I cannot figure out why I am getting the error:
no matching function for call to 'Timer::every(int, void (&)())'
Here is that part of the code:
void setup(){
      everyAlt = t.every(100, readAltimeter);
      everyLaunch = t.every(500, detectLaunch);
      t.oscillate(blueled, 500, HIGH);
    }

    void readAltimeter(){
      alts[altPlace] = bmp.readAltitude()-zeroAlt;
      altPlace++;
    }

    void detectLaunch(){
      tempSpeed = 0;
      int x = 0;
      while (x < 5){
        tempSpeed += abs((alts[x]-alts[x+1])*10);
      }
      if (tempSpeed/5 > 5){
        t.stop(everyLaunch);
      }
    }

I am pretty new to arduino so any help would be much appriciated!

I cannot reproduce your problem with this code: https://pastebin.com/WQBCb1AQ Does the code above compile correctly?

Yea, I still have the same compiling error. https://pastebin.com/W63QC2r4

You and me are using two different versions of the library. The every function has e.g. an overload int8_t every(unsigned long period, void (*callback)(void*), void* context); in your library but not the current master version (https://github.com/JChristensen/Timer/blob/master/Timer.h#L40). Please uninstall your old Timer library from the library manager, download the newest ZIP from the Github repo, reinstall the lib and retry.

Had the wrong version. Correct version downloaded from the current master: github.com/JChristensen/Timer


text:
RGB LED lights and Arduino
I am doing my thesis project which is a kinetic light/sound sculpture. My first step is to learn how to work with RGB LED lights and how to choose them and what other kinds of equipment I need.
I started to learn Arduino uno and learned how to light an LED, now I need to expand it much bigger.
I want to be able to control each LEDs.
I want 30 meters LED light divided to 7 channels, in which each channel have a unique function that will trigger 7 channels of sound.
I hope I could use your help and thanks in advance for your time :)

I suggest you to use RGB Led Driver like: WS2812.
You can build led strip as long as you want.
There are a lot of example/tutorial using Arduino and Strip Led composed by WS2812 Led Driver (For example, here there is a tutorial).
NB: You pay attention that using 30 meters strip led, you need an external power supply and you can't use 5V pin of Arduino, because Arduino doesn't supply sufficient power for supply a strip led too long.

Thank you so much. do I also need these? I found it on 1 tutorial :
-1 x 220-440 Ohm Resistor (anything between these two values is fine)
-1 x 100-1000 microFarad Capacitor (anything between these two values is fine)
-5V power supply

Yes, how many strip do you need?

it is complicated if I am gonna just explain it without showing you any layouts but I try my best. So 30 meters stripe divided into 7 channels, each channel has a unique function and is made of 8 to 16 pieces from 10 cm to 60 cm. It's a modular/ parametric/algorithmic design.

Ideally, you would have a resistor between the Arduino pin and the first WS2812B for each strip. 7 strips  could be driven from 7 pins. Everytime you update a strip, the # of LEDs x 3 is how many bytes of data get sent out. You could also do it as one very long strip - the amount of data being sent out for a color change is then 7 times as much.  Adafruit.com has a  neopixel library for driving these LEDs, and fastled.h is another option.  Ex: here are four rings with 43 or 44 WS2812B each that I made, all are connected via individual wires to a 5V/10A supply, each has its own data line

https://www.youtube.com/watch?v=CGOxbehyoM4&t=37s

and another question is that I have 6 PWM pins, can I add one to it ?


text:
How to convert a delimited string of hex numbers to an int array
I am sending a string to the Arduino via serial, I made the program that sends the data, so I can change it to anything, but for now it sends a string of hex numbers delimited by ':', so for example 00:AA:FF and I need to get that into an int array onto the Arduino, the main problem is I don't always know how big the array will be, sometimes just 2 indexes, other times 16 indexes.
As I said, I made the program sending the data so I can make the data anything, I just need to get an int array to the Arduino and get it back as an int array via serial

is this a school assignment?

Do you know an upper limit on how many there will be?

You could store the hex numbers in a int array using strtok() and strtol().
char str[] = "00:AA:FF:7FFF";
int intArray[16]; // Maximum number of hex numbers.

void setup(){

  Serial.begin(9600);

  int counter = 0;
  char * pch = strtok(str, ":");

  while(pch != NULL){
    intArray[counter] = strtol(pch, NULL, 16);
    pch = strtok(NULL, ":");
    counter++;
  }
  Serial.print("Item Count = ");
  Serial.println(counter);

  for(int i = 0; i < counter; i++){
    Serial.println(intArray[i]);
  }

}

void loop(){}


text:
Avrdude & micro clone
I am trying to program a Pro Micro clone (black PCB, 5v), using this command
avrdude.exe -p atmega32u4 -c avr109 -U flash:w:pro_micro_ISP_B6_10.hex:i -P COM3

but this is the (obviously incorrect) output I get:
Connecting to programmer: .
Found programmer: Id = "╞ ("; type = b
    Software Version =  . ; Hardware Version =  .
avrdude.exe: error: buffered memory access not supported. Maybe it isn't
a butterfly/AVR109 but a AVR910 device?

It has never been flashed before. All three lights are illuminated when I plug it in. I am pretty sure COM3 is the right port.
What's going on here? Is my USB cable bad or something? I actually had this problem on two separate units, so I know the board itself is fine.

can you upload from Arduino IDE?

I actually had this problem on two separate units, so I know the board itself is fine ..... that conclusion makes no sense .... maybe you have two bad units


text:
Powering L298N drivers from mains power supply
I am powering 2 stepper motors with an L298N driver each (from a 9V 2A external power supply powered from the mains: https://www.amazon.co.uk/BERLS-Power-Adapter-Elegoo-Connectors/dp/B07GSM6YLX/ref=sr_1_5?ie=UTF8&qid=1550859082&sr=8-5&keywords=AC%2FDC+Power+Adapter+for+Arduino).
I am wondering how I can connect the driver 5V and GND pins to the power supply?
Thanks in advance!

You would not connect the +5V lead to the power supply. Connect the ground between the driver, the Arduino, and the power supply. Connect the 9V from the power supply to the driver. Connect the logic lines from the Arduino to the inputs on the driver.

Thanks Duncan for your advice. However, given that the external 9V DC adaptor is connected through the barrel jack to the Arduino Mega, how could i connect this to the driver directly? Similarly, how would the ground connect to this power supply adaptor?

If you're going to use the same power supply for both you should probably build a splitter out of a female power jack and 2 male cables. You'd connect one to the Arduino and the other to the motor driver. The Arduino would regulate the 9V down to 5V and the motor driver would use the 9V directly. They would have common grounds.

You might need to add a fairly large electrolytic capacitor between 9V and ground right near the barrel connector for the Arduino. This would serve to even out dips in voltage as the motor driver turns the motor coils on and off, and prevent the Arduino from dropping out. (That would really only be needed if the voltage to the Arduino's barrel connector drops below around 7V at peak current demand from the motor driver, and would likely only happen if your peak current gets close to the 2A limit of your power supply.)

i see many thanks for your advice ille take a look into that

You'll need another supply, or a step-down supply for the 5v; same ground for all.
Also H-bridges are really inefficient to drive steppers, you should get a dedicate stepper driver.

Thanks for your advice. How exactly would the step-down supply be connected from the power supply to the driver, given that the 9V DC adaptor is connected to the Arduino barrel jack?

@Anonymous well in that case you are actually using the arduino's voltage regulator, IIRC as long as your under the power budget you can power the driver boards logic from the 5v line of the Arduino, and connect 9v to both the Arduino and the motor in on the driver.