text:
Arduino CC3000 websocket client
I am working for arduino websocket client with CC3000 wifi board from adafruit.
I have usde this websocket example as a reference and modified to work with cc3000 wifi board.
I am not able to connect to echo.websocket.org.
My code shows client is not connected and unavailable to communicate after sending the upgrade headers.
Here is the serial monitor response for the code:
echo.websocket.org -> Errno: 1
174.129.224.73-------------------------------------
Client connected
Sending websocket upgrade headers
Analyzing response headers
client not connected
client not available

here is the Arduino sckech:
#include <Adafruit_CC3000.h>
#include <ccspi.h>
#include <SPI.h>
#include <string.h>
#include <WebSocketClient.h>
#include "utility/debug.h"

// These are the interrupt and control pins
#define ADAFRUIT_CC3000_IRQ   3  // MUST be an interrupt pin!
// These can be any two pins
#define ADAFRUIT_CC3000_VBAT  5
#define ADAFRUIT_CC3000_CS    10
// Use hardware SPI for the remaining pins
// On an UNO, SCK = 13, MISO = 12, and MOSI = 11
Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS, ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT,
SPI_CLOCK_DIVIDER); // you can change this clock speed

#define WLAN_SSID       "UNSTOPPABLE"           // cannot be longer than 32 characters!
#define WLAN_PASS       "8878333344"
// Security can be WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA or WLAN_SEC_WPA2
#define WLAN_SECURITY   WLAN_SEC_WPA2

#define IDLE_TIMEOUT_MS  3000      // Amount of time to wait (in milliseconds) with no data
// received before closing the connection.  If you know the server
// you're accessing is quick to respond, you can reduce this value.

// What page to grab!
#define WEBSITE      "echo.websocket.org"
//#define WEBPAGE      "/testwifi/index.html"

// Here we define a maximum framelength to 64 bytes. Default is 256.
#define MAX_FRAME_LENGTH 64

// Define how many callback functions you have. Default is 1.
#define CALLBACK_FUNCTIONS 1

Adafruit_CC3000_Client www;
WebSocketClient webSocketClient;
/**************************************************************************/
/*!
 @brief  Sets up the HW and the CC3000 module (called automatically
 on startup)
 */
/**************************************************************************/

uint32_t ip;

void setup(void)
{
  Serial.begin(115200);
  Serial.println(F("Hello, CC3000!\n"));

  Serial.print("Free RAM: ");
  Serial.println(getFreeRam(), DEC);

  /* Initialise the module */
  Serial.println(F("\nInitializing..."));
  if (!cc3000.begin())
  {
    Serial.println(F("Couldn't begin()! Check your wiring?"));
    while(1);
  }

  // Optional SSID scan
  // listSSIDResults();

  Serial.print(F("\nAttempting to connect to "));
  Serial.println(WLAN_SSID);
  if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
    Serial.println(F("Failed!"));
    while(1);
  }

  Serial.println(F("Connected!"));

  /* Wait for DHCP to complete */
  Serial.println(F("Request DHCP"));
  while (!cc3000.checkDHCP())
  {
    delay(100); // ToDo: Insert a DHCP timeout!
  }

  /* Display the IP address DNS, Gateway, etc. */
  while (! displayConnectionDetails()) {
    delay(1000);
  }

  ip = 0;
  // Try looking up the website's IP address
  Serial.print(WEBSITE);
  Serial.print(F(" -> "));
  while (ip == 0) {
    if (! cc3000.getHostByName(WEBSITE, &ip)) {
      Serial.println(F("Couldn't resolve!"));
    }
    delay(500);
  }

  cc3000.printIPdotsRev(ip);

  // Optional: Do a ping test on the website
  /*
  Serial.print(F("\n\rPinging ")); cc3000.printIPdotsRev(ip); Serial.print("...");
   replies = cc3000.ping(ip, 5);
   Serial.print(replies); Serial.println(F(" replies"));
   */

  /* Try connecting to the website.
   Note: HTTP/1.1 protocol is used to keep the server from closing the connection before all data is read.
   */
  www = cc3000.connectTCP(ip, 80);
  if (www.connected()) {
    /*    www.fastrprint(F("GET "));
     www.fastrprint(WEBPAGE);
     www.fastrprint(F(" HTTP/1.1\r\n"));
     www.fastrprint(F("Host: ")); www.fastrprint(WEBSITE); www.fastrprint(F("\r\n"));
     www.fastrprint(F("\r\n"));
     www.println();*/
  }
  else {
    Serial.println(F("Connection failed"));
    return;
  }

  Serial.println(F("-------------------------------------"));

  /* Read data until either the connection is closed, or the idle timeout is reached. */
  /*  unsigned long lastRead = millis();
   while (www.connected() && (millis() - lastRead < IDLE_TIMEOUT_MS)) {
   while (www.available()) {
   char c = www.read();
   Serial.print(c);
   lastRead = millis();
   }
   }
   www.close();
   Serial.println(F("-------------------------------------"));*/

  /* You need to make sure to clean up after yourself or the CC3000 can freak out */
  /* the next time your try to connect ... */
  /*  Serial.println(F("\n\nDisconnecting"));
   cc3000.disconnect();*/
  // Handshake with the server
  webSocketClient.path = "/";
  webSocketClient.host = WEBSITE;

  if (webSocketClient.handshake(www)) {
    Serial.println("Handshake successful");
  }
  else {
    Serial.println("Handshake failed.");
    while(1) {
      // Hang on failure
    }
  }
}

void loop(void)
{
  String data;
  if (www.connected()) {

    /*   data = webSocketClient.getData();

     if (data.length() > 0) {
     Serial.print("Received data: ");
     Serial.println(data);
     }*/

    // capture the value of analog 1, send it along
    pinMode(1, INPUT);
    data = String(analogRead(1));

    webSocketClient.sendData(data);

  }
  else {

    Serial.println("Client disconnected.");
    while (1) {
      // Hang on disconnect.
    }
  }

  // wait to fully let the client disconnect
  delay(3000);
}

If anybody can guide me where I am wrong then it would be great help.I have taken reference code from brandenhall/Arduino-Websocket

Can you please add a wireshark sniff of what is going on?

Thanks for reply I am not getting what to do with wireshark. In my case my client code is not communicating with echo server. As I have put debug print, it got disconnected from the client after sending upgrade header.

Then print back the response from the server. And also what you are sending. (That is what wireshark do)

here the problem is i am not recieving anything from server. My client disconnected from the server after sending the Upgrade headers. that's why in wireshark i am not getting anything from server I think so.

Then post what YOU are sending!

here the problem is i am not receiving anything from server. My client disconnected from the server after sending the Upgrade headers. that's why in wire-shark i am not getting anything from server I think so.
here is code which do handshake with server.The problem is i am not receiving anything from server. My client disconnected from the server after sending the Upgrade headers. that's why in wire shark i am not getting anything from server I think so.
here is code which do handshake with server:

bool WebSocketClient::analyzeRequest() {
    String temp;
    int bite;
    bool foundupgrade = false;
    unsigned long intkey[2];
    String serverKey;
    char keyStart[17];
    char b64Key[25];
    String key = "------------------------";
    randomSeed(analogRead(0));
    for (int i=0; i<16; ++i) {
        keyStart[i] = (char)random(1, 256);
    }
    base64_encode(b64Key, keyStart, 16);
    for (int i=0; i<24; ++i) {
        key[i] = b64Key[i];
    }
    Serial.println(F("Sending websocket upgrade headers"));
    socket_client->print(F("GET "));
    socket_client->print(path);
    socket_client->print(F(" HTTP/1.1\r\n"));
    socket_client->print(F("Upgrade: websocket\r\n"));
    socket_client->print(F("Connection: Upgrade\r\n"));
    socket_client->print(F("Host: "));
    socket_client->print(host);
    socket_client->print(CRLF);
    socket_client->print(F("Sec-WebSocket-Key: "));
    socket_client->print(key);
    socket_client->print(CRLF);
    socket_client->print(F("Sec-WebSocket-Protocol: "));
    socket_client->print(protocol);
    socket_client->print(CRLF);
    socket_client->print(F("Sec-WebSocket-Version: 13\r\n"));
    socket_client->print(CRLF);
    Serial.println(F("Analyzing response headers"));
    //here it got disconnected
    while (socket_client->connected() && !socket_client->available()) {
        delay(100);
        Serial.println("Waiting...");
    }
    // TODO: More robust string extraction
    while ((bite = socket_client->read()) != -1)
    {
        temp += (char)bite;
        if ((char)bite == '\n')
    {
     #ifdef DEBUGGING
            Serial.print("Got Header: " + temp);
     #endif
            if (!foundupgrade && temp.startsWith("Upgrade: websocket"))
            {
                foundupgrade = true;
            }
            else if (temp.startsWith("Sec-WebSocket-Accept: "))
            {
                serverKey = temp.substring(22,temp.length() - 2); // Don't save last CR+LF
            }
              temp = "";
            }
if (!socket_client->available()) {
          delay(20);
        }
    }
key += "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
    uint8_t *hash;
    char result[21];
    char b64Result[30];
    Sha1.init();
    Sha1.print(key);
    hash = Sha1.result();
    for (int i=0; i<20; ++i) {
        result[i] = (char)hash[i];
    }
    result[20] = '\0';
    base64_encode(b64Result, result, 20);
    // if the keys match, good to go
    return serverKey.equals(String(b64Result));
}


text:
Xbee power issue
I want to power xbee s2 module through atmel 328p digital output pin. And I am powering atmel 328p IC using 3.7 li-ion cell 5500 mAh. In sleep mode atmel consume current in micro Amp but xbee consuming around 40 mA. I want to reduce it. I tried xbee in power down mode but its not working for me. Is der any way to switch xbee automatically with as atmel sleep & wake-up. Circuit works properly when I power xbee through 3.7 v li-ion cell but consume power continuously.

The best solution would be to determine why your Xbee is not being switched into power down mode.
But, if you wish to turn the Xbee power off using the Arduino then there are many ways of doing this. One method is shown on the diagram below {from here}. This requires two transistors and three resistors. Almost any small transistors would work. Good choices if buying new components would be BC337 / BC817 for T1 and BC327 / BC807 for T2. The first part number in each pair is a through hole part and the second number is the equivalent surface mount part. If buying these try to get the -40 suffix versions, although in this case any version would work OK.
This circuit was drawn for use with a PIC processor controlling a 12V supply, but the Arduino works equally well controlling a 3.7V LiIon supply. The load is shown as a light bulb - that's where you'd connect the XBee.

Input low turns 1 off which turns T2 off. To enable/disable the XBee you have to raise / lower the input pin.

I would use a sleep mode, e.g. PIN sleep, in order to reduce the power consumption of the Xbee. At the hardware level, the XBee uses pin 9 as a control pin. This pin can be used to sleep the radio: setting it to 3,3V (“high” or “asserted”) causes the radio to sleep; setting it to 0V (“low” or “deasserted”) wakes the radio up. You can find some useful hints on the following websites http://citizen-sensing.org/2013/08/xbee-sleeping/ or https://www.digi.com/wiki/developer/index.php/Designing_a_Sleeping_XBee_Sensor  or here http://www.johnhenryshammer.com/WOW2/pagesHowTo/xbeeSeries1.php#index.

Welcome to Arduino SE! Can you please edit your answer to include how exactly to do this and any relevant code/diagrams/etc.? Thanks!

source: Stack Exchange

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

sort: votes


text:
Arduino non-blocking software PWM LED fader not working
I am trying to write a simple software PWM to fade some LEDs because I don't have enough PWM I/O Ports.
The code evaluates how long you want the LED to fade, and breaks it down into a number of steps. During each step, it will evaluate the period the LED should be on.
I have the following code:
class Led{
  public:
    Led(int pin);
    void setup();
    // void updateFadeDirection();
    void updateBrightness();

  private:
    int _pin;
    unsigned long _currentTime;
    unsigned long _startTime; // Very beginning of fade period
    unsigned long _fadePeriod; // How long to fade on and off
    int _fadeStep; // current fade step i.e. 1/255
    int _fadeSteps; // How many steps to take until full brightness
    int _fadeDirection; // low to high or high to low?
    float _T_on; // Amount of time to turn LED on
    float _T_fadeStep; // Amount of time per step increment of brightness
    unsigned long _stepTime; // Start of current step period

    bool _evaluated;
};

Led::Led(int pin){
  _pin = pin;
}

void Led::setup(){
  pinMode(_pin, OUTPUT);
  _startTime = micros();
  _fadePeriod = 2*1000000; //microseconds(us)
  _fadeStep = 50; // start at 0 brightness here
  _fadeSteps = 100;
  _fadeDirection = 1;

  _T_fadeStep = _fadePeriod/_fadeSteps; // i.e. 2000000us/100steps = 20000us/step of brightness
  _T_on = (_fadeStep/_fadeSteps) * _T_fadeStep; // i.e. 20/100 * 20000us = 4000us on

  _stepTime = micros();
  delayMicroseconds(200);
}

void Led::updateBrightness(){
  _currentTime = micros();

  if(_currentTime - _startTime < _fadePeriod){
    if (_currentTime - _stepTime > _T_on){
      digitalWrite(_pin, LOW);
    } else {
      digitalWrite(_pin, HIGH);
    }

    if(_currentTime - _stepTime >= _T_fadeStep){
      // _fadeStep++;
      _stepTime = _currentTime;
      _T_on = (_fadeStep/_fadeSteps) * _T_fadeStep;
    }
  }
  else{
    digitalWrite(_pin, HIGH);
  }
}

Led LED0(0);

void setup() {
  LED0.setup();
}

void loop() {
  LED0.updateBrightness();
}

The current behaviour when powered on is the single LED will be turned off, then will turn on after 2 seconds.
In particular, it never seems to enter the else part
  if (_currentTime - _stepTime > _T_on){
    digitalWrite(_pin, LOW);
  } else {
    digitalWrite(_pin, HIGH);
  }

The problem is that the LED will never hit HIGH until the outer else is triggered.
I believe it has to do with _T_on being an int and the timestamps being unsigned long and me not casting it.
The expected behaviour is 2 seconds of dimmed (50%) light, and then a full 100% when it hits the outer else.

Nothing to do with int/unsigned long - I've just tried it. Not sure why you didn't try it if you thought that was the problem!

I'm going through this now and I'm slightly confused as to precisely what you're trying to achieve. Ultimately do you want to be able to choose starting brightness, end brightness, and the time it takes to go from one to the other? That seems the most obvious, but it also seems like you want to specifiy how many individual brightness levels there are inbetween. Also, do you have any timers spare that you aren't using?

I think you have your logic completely arse about face (to use a colloquial expression). I see nothing there that would actually perform any PWM operation at all, only turning the LED ON or OFF at something like 2 seconds.

@Majenko: the LED HIGH at 2 seconds it just to show timestamps in microseconds work for my chip. The inner conditional block is what evaluates the duty cycle during each period (read: not the 2 second fadePeriod). @CharlieHanson: yes it's an LED fader using PWM, which you can set duration from 0 to full brightness, as well as how many steps in that duration (to simulate smoothness or harsh steps). I did try the int/unsigned long, but didn't work so thought I'd throw it up here for anyone to correct me. I am not using OCR1A/B.

Turns out the clock speed for my chip can't handle the software PWM that's fully asynchronous using timestamps. The amount of instructions exceed the individual periods of each duty cycle. Got it working and will do  a write up on my findings in I have time.

 _fadeStep/_fadeSteps always evaluates to zero unless  _fadeStep >= _fadeSteps.

float _T_on; - variable names starting with an underscore and followed by an upper-case letter are reserved by the C++ standard. I suggest you stop using them. Put trailing underscores in, if you want to indicate class variables.

@ott--: didn't even see that. Thanks.

As @ott-- has mentioned, because of the int datatype, _fadeStep/_fadeSteps will always evaluate to 0.
Here's the updated code along with some timing tweaks:
float fadeSteps = 150; // How many steps to take until full brightness

class Led{
  public:
    Led(int pin, float fadeStep=0);
    void setup();
    // void updateFadeDirection();
    void updateBrightness();

  private:
    int _pin;
    unsigned long _currentTime;
    unsigned long _startTime; // Very beginning of fade period
    unsigned long _fadePeriod; // How long to fade on and off
    float _fadeStep; // current fade step i.e. 1/255
    int _fadeDirection; // low to high or high to low?
    unsigned long _T_on; // Amount of time to turn LED on
    unsigned long _T_fadeStep; // Amount of time per step increment of brightness
    unsigned long _stepTime; // Start of current step period

    bool _evaluated;
};

Led::Led(int pin, float fadeStep){
  _pin = pin;
  _fadeStep = fadeStep;
}

void Led::setup(){
  pinMode(_pin, OUTPUT);
  _startTime = micros();
  _fadePeriod = 2000000; //microseconds(us)
  _fadeDirection = 1;

  _T_fadeStep = _fadePeriod/2/fadeSteps; // i.e. 2000000us/100steps = 20000us/step of brightness
  _T_on = (_fadeStep/fadeSteps) * _T_fadeStep; // i.e. 20/100 * 20000us = 4000us on

  _stepTime = micros();
}

void Led::updateBrightness(){
  _currentTime = micros();
  if (_currentTime - _stepTime > _T_on){
    digitalWrite(_pin, LOW);
  } else {
    digitalWrite(_pin, HIGH);
  }

  if(_currentTime - _stepTime >= _T_fadeStep){
    _fadeStep += _fadeDirection;
    _stepTime = _currentTime;
    _T_on = (_fadeStep/fadeSteps) * _T_fadeStep;
  }

  if(_fadeStep >= fadeSteps-1) {
    _fadeDirection = -1;
  } else if(_fadeStep <= 1) {
    _fadeDirection = 1;
  }
}

Led LED0(0);
Led LED1(1,fadeSteps/5);
Led LED2(2,2*fadeSteps/5);
Led LED3(3,3*fadeSteps/5);
Led LED4(4,4*fadeSteps/5);

void setup() {
  LED0.setup();
  LED1.setup();
  LED2.setup();
  LED3.setup();
  LED4.setup();
}

void loop() {
  LED0.updateBrightness();
  LED1.updateBrightness();
  LED2.updateBrightness();
  LED3.updateBrightness();
  LED4.updateBrightness();
}

Some refactoring is needed to be more modular, but will fade (using software PWM) LEDs asynchronously on every digital OUT port on an attiny85. Can also set the starting brightness so that you can make an LED fading chaser.

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


text:
Possible arduino burned (5V shorted to Vin), explanations and suggestions
Please apologize my english.
I am working in a project using an original arduino uno, one generic servo (no factory marks) and one HC-SR04 sensor.
I make a circuit like the one here: http://s24.postimg.org/43jra5l9h/mycircuit_bb.png ([url=http://postimg.org/image/lgu1p0gkh/][img]http://s24.postimg.org/lgu1p0gkh/mycircuit_bb.jpg[/img][/url], sorry, upload of image not allowed due reputation)
As you can see from the picture I accidentally connected green into Vin instead of GND. (If the image won't load, that means that my positive is connected to arduino 5V and the ground of the circuit is connected to arduino Vin)
Now my board turn on the lights but I am unable to execute the program already in the microcontroller as aslo I cannot upload a new program to it. (It gives some error message of failed to connect).
I think I burned the microcontroller(mc) by short circuiting 5V and Vin.
That said, I have three questions:
1 - Is there any way to find out if I really burned my board using just a low budget multimeter? And if I did, which parts I need to replace?
I have access to some spare ATMEL mc and I think I could replace and reprogram them by using another arduino board. However, I am affraid that I may have burned few other items and just by replacing the mc will not give me back all the funcionallities of a new board.
2 - I have basic knowledge of electronics, could someone explain to a beginner like me which impact did that mistake could/have make in all components of the circuit? (Arduino board, the servo and the sensor)
3 - Even before the accident, the circuit just work well for few minutes. I read tons of pages and tried a lot of suggestions, most of them related with power supply (capacitors to avoid flutuations, One battery just for the servo, one battery just for the sensor...) and none gave me good results.
I am wondering what are the alternatives to power up this simply circuit, in particular I am looking for this possibilities: Complete external power supply (by using AC to DC adapters), Complete internal power supply (Using just batteries) and a mix of those two (Using AC to DC and batteries). I have no access to a external DC power supply generator other than batteries.

How was your Arduino powered when this accident happened? USB or power plug?

If you have another Uno then your best bet is either:
1) Swap the suspect processor into the known good board, test it.
2) to buy a replacement chip (ATMega 328-PU), use this link to flash it, if it works you win, if not you can at least use the new processor again.
I have done this myself & it worked well, it isn't easy to be sure any other way as the chip needn't fail in a predictable manner. The chances are it will take a large current if it's dead, until it burns out & goes open circuit. Once the magic smoke has come out you know it's dead... the Arduino power supply is reasonably capable of looking after itself so your chances are good.

Before replacing the target processor, it's also important to verify that the USB-serial chip still works - can the computer recognize the device as connected?  Can the serial port be opened without error (even though no data will be received in return).  If not, the interface chip (FTDI, ATmega6u2 or whatever) may be dead, and while replaceable it is a bit more tricky to do so.


text:
Why so different not connected analog inputs?
I took just Arduino Uno board, connected Ethernet Shield to it and compiled Web Server example. And it works.
But it outputs:
analog input 0 is 1023
analog input 1 is 1023
analog input 2 is 789
analog input 3 is 663
analog input 4 is 525
analog input 5 is 449

Why so different values? Shouldn't it be zeros? Is this static electricity or what?

Floating inputs, EMI, high input impedance and sample-and-hold capacitor. It can measure anything at this point (usually electro static charge is split between pin capacity and S&H capacitor. It can be used even for touch sense pins...


text:
How can BMP180 measure a temperature too?
I got the following device

(sorry for imperfect focus)
and found, that it can measure not only pressure, but also a temperature too. The code was taken from common sketches for Adafruit BMP085 and they were working. I checked, that temperature value rises if I touch sensor with finger.
Simultaneously, on Bosch site for BMP180 I can't find any notes it can measure temperature, only pressure.
How can it be?
1) Bosch's BMP180 has undocumented feature to measure a temperature
2) The device on picture has additional component to measure temperature
3) The device on picture has completely different sensor, which has the name of "BMP180" just by coincidence.
4) Something else....

If you read the data sheet (on the site you point to) you see plenty of references to temperature:

The BMP180 is designed to be connected directly to a microcontroller of a mobile device via the I 2 C
  bus. The pressure and temperature data has to be compensated by the calibration data of the
  E 2 PROM of the BMP180.

and

The BMP180 consists of a piezo-resistive sensor, an analog to digital converter and a control unit with EEPROM and a serial I2C interface. The BMP180 delivers the uncompensated value of pressure and temperature. The E 2 PROM has stored 176 bit of individual calibration data. This is used to
  compensate offset, temperature dependence and other parameters of the sensor.

And many many more.

The BMP085 Barometric Pressure/Temperature/Altitude Sensor- 5V ready page at adafruit.com says the BMP180 is a drop-in replacement for the BMP085.
The  BMP180 Barometric Pressure/Temperature/Altitude Sensor- 5V ready page at adafruit.com says the BMP180  is completely identical to the BMP085 in terms of firmware/software/interfacing.
In addition, while Bosch's web page for the BMP085 doesn't mention temperature, the data sheet itself – the final reference, typically, for a device like this – says “Temperature measurement included” on page 2, and on page 14 refers to measuring temperature in steps of 0.1°C, and on other pages shows temperature register numbers, etc.  To get the data sheet, click the Documents & Drivers tab, then the BST-BMP180-DS000-12 Datasheet link.

See, for example, Adafruit BMP085 library (it's work with BMP180 too), function
void Adafruit_BMP085_Unified::getTemperature(float *temp)

in file Adafruit_BMP085_u.cpp line 330


text:
How to distinguish identical Arduinos from Linux?
I have two identical (but with different software) Arduinos connected to Linux box. Their serals are identical
# udevadm info -a -n /dev/ttyUSB1 | grep '{serial}'
    ATTRS{serial}=="0000:00:1d.0"

# udevadm info -a -n /dev/ttyUSB0 | grep '{serial}'
    ATTRS{serial}=="0000:00:1d.0"

Can I make these Arduinos to differ somehow programmatically?

What Arduinos do you have?

request some info over Serial

If you want the same firmware for both Arduinos, you could make a simple hardware solution: use a jumper and connect and input pin to select a 0V or 5V value as input.

You can't change the USB information programmatically. The fact that you're referencing /dev/ttyUSB* means you have hardware USB interface chips (CH340, PL2302, FT232, etc) which you can't change from your sketch (some can be adjusted using tools provided by the chip manufacturer though, so you may be able to tweak it using that).
Instead your only option is to have some kind of "fingerprint" that software on your computer can request from your firmware. If you stick to a common serial protocol for all your firmwares you can implement a standard "Firmware Version" command which will respond with what code and version you have installed.
It's up to you to decide how best to implement such a system, of course.

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


text:
Problem in Serial Communication between nodeMCU and arduino
I am trying to send some messages from nodeMCU to Arduino using Serial communication (aka UART). Following is the code on nodeMCU side:
#include <ESP8266WiFi.h>

const char* ssid = "my-ssid"; // SSID i.e. Service Set Identifier is the name of your WIFI
const char* password = "my-pasword"; // Your Wifi password, in case you have open network comment the whole statement.

int ledPin = 13; // GPIO13 or for NodeMCU you can directly write D7
WiFiServer server(80); // Creates a server that listens for incoming connections on the specified port, here in this case port is 80.

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

          pinMode(ledPin, OUTPUT);
          digitalWrite(ledPin, LOW);

          // Connect to WiFi network
          WiFi.begin(ssid, password);
          //Trying to connect to wifi
          while (WiFi.status() != WL_CONNECTED) {
            delay(500);
          }
          Serial.println("$Wifi Connected#");
          server.begin();
        }

        void loop() {
          // Check if a client has connected
          WiFiClient client = server.available();
          if (!client) {
            return;
          }

          // Wait until the client sends some data
          while(!client.available()){
            delay(1);
          }
          // Read the first line of the request
          String request = client.readStringUntil('\r');
          client.flush();

          int value = LOW;
          if (request.indexOf("/LED=ON") != -1)  {
            digitalWrite(ledPin, HIGH);
            Serial.println("$Led High#");
            value = HIGH;
          }
          if (request.indexOf("/LED=OFF") != -1)  {
            digitalWrite(ledPin, LOW);
            Serial.println("$Led Low#");
            value = LOW;
          }

          // Return the response
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println(""); //  do not forget this one
          client.println("<!DOCTYPE HTML>");
          client.println("");

          client.print("Led pin is now: ");

          if(value == HIGH) {
            client.print("On");
          } else {
            client.print("Off");
          }
          client.println("

");
          client.println("<button>Turn On </button>");
          client.println("<button>Turn Off </button>
");
          client.println("");
          delay(1);
        }

Following is the code on Arduino side:
String msgFromNodeMCU;
void setup() {
  pinMode(13,OUTPUT);
  Serial.begin(115200);
}

void loop() {
  msgFromNodeMCU=Serial.readString();
  Serial.println(msgFromNodeMCU);
}

which was working fine until I modified that code to:
String msgFromNodeMCU;

void setup() {
  pinMode(13,OUTPUT);
  Serial.begin(115200);
}

void loop() {
  msgFromNodeMCU=Serial.readString();
  delay(10);
  String wifi_connected="$Wifi Connected#";
  String led_High="$Led High#";
  String led_Low="$Led Low#";
    if (msgFromNodeMCU.equalsIgnoreCase(wifi_connected)) {
      Serial.println("Wifi Connected");
      delay(10);
    }
    if (msgFromNodeMCU.equalsIgnoreCase(led_High)) {
      digitalWrite(13,HIGH);
    }
    if (msgFromNodeMCU.equalsIgnoreCase(led_Low)) {
      digitalWrite(13,LOW);
    }
}

With this code, I see no "Wifi Connected" message on my Serial monitor and there is no response on pin 13. This implies msgFromNodeMCU is not heard. What can I do for msgFromNodeMCU to be heard? Any sort of help is highly appreciated. :D

+Look Alterno Removing delay() or adding millis() was not helpful. It would be nice if as soon as any message comes to the Serial buffer, it interrupts the target device (arduino in this case). Is there a way to create such interrupt?

Serial is ESP or USB?

@Juraj  Serial is ESP. Not USB

My question was educational. you write "I see no 'Wifi Connected' message on my Serial monitor". how is Serial Monitor connected? I am sure it is USB.


text:
TimerOne.h library for nodeMCU
Following is the code I found in Arduino example files. It compiled fine on Arduino UNO. But there was an error when I tried to compile it for nodeMCU 1.0(ESP 12E Module).
#include <TimerOne.h>
void setup() {
  pinMode(13,OUTPUT);
  Timer1.initialize(5000000);//5 sec
  Timer1.attachInterrupt(timerIsr);
}
void loop() {}
void timerIsr(){
  digitalWrite(13,!digitalRead(13));
}

Following was the error message. I had this kind of error previously on OneWire.h and I solved it by replacing the OneWire.h library with another OneWire.h library that was made especially for nodeMCU.
Error msg:
Arduino: 1.8.3 (Windows 8.1), Board: "NodeMCU 1.0 (ESP-12E Module), 80 MHz, 115200, 4M (3M SPIFFS)"

In file included from D:\iox Prime\TEC project\code\building modules\timerIsrDemo\timerIsrDemo.ino:1:0:

C:\Program Files (x86)\Arduino\libraries\TimerOne/TimerOne.h:39:20: fatal error: avr/io.h: No such file or directory

 #include <avr/io.h>

                    ^

compilation terminated.

exit status 1
Error compiling for board NodeMCU 1.0 (ESP-12E Module).

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

I searched the library everywhere in the internet to solve this error but end up with no success. I wish somebody modifies the existing library for me. Thank you for the help.

I have found a solution. There is a library called Ticker.h
I found this on github: https://github.com/esp8266/Arduino/tree/master/libraries/Ticker
Following is my demo code:
#include <Ticker.h>
Ticker ticker;
void setup() {
  pinMode(D7,OUTPUT);
  ticker.attach(1,isrFunc);//tickerObj.attach(timeInSecs,isrFunction)
}

void loop() {}
void isrFunc(){
  digitalWrite(D7,!digitalRead(D7));
}

For me, this code worked seamlessly on nodeMCU. Thank you.

The TimerOne library is specifically for Timer 1 on the AVR microcontrollers1. No other microcontroller has the exact same timer structure, so the library cannot be used with them.
You need a library that works with the timers the ESP8266 has, or you need to manually manipulate the timer registers, for which you will need to consult and understand the datasheet.

1: It also appears to have #defines in it for ARM (Teensy 3.x) chips.

There is a another Ticker.h for non ESP processors like UNO, see below:
// Filename: Ticker_Example - Does'nt work on ESP)
// this is based upon published version V3 of 3/2018
// refer to : https://github.com/sstaub/Ticker/blob/master/examples/Example.ino
// Complete example. Here we created five timers, you can run it and test the result
// in the Serial monitor and the on board LED.
#include "Ticker.h"

void printMessage();
void printCounter();
void printCountdown();
void blink();
void printCountUS();

bool ledState;
int counterUS;

/*
Creates a Ticker object          Constructors / Destructor
Ticker(fptr callback, uint32_t interval, uint16_t repeats = 0, resolution_t resolution = MICROS)
    parameter callback for the function name you want to call
    parameter interval sets the interval time in ms or us when using MICROS_MICROS with the resolution parameter
    parameter repeats sets the number of repeats the callback should executed, 0 is endless
    parameter resolution sets the internal resolution of the Ticker, it can MICROS, MICROS_MICROS or MILLIS
or in Ray's simpler terms...  Ticker (give it a name)(the callback function, interval, number of times, resolution)
*/
Ticker timer1(printMessage, 0, 1);      // once, immediately
Ticker timer2(printCounter, 1000, MILLIS);  // internal resolution is milli seconds
Ticker timer3(printCountdown, 1000, 5);   // countdown 5 times, every second
Ticker timer4(blink, 500);          // changing led every 500ms
// Ticker timer5(printCountUS, 100, 0, MICROS_MICROS); // originally used 'MICRO_MICROS' so the the interval time would be 100us
                                             //with a internal resolution of micro seconds BUT this did not compile
Ticker timer5(printCountUS, 2000, 0, MICROS);  // now set to 2 seconds

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  Serial.begin(9600);
  delay(2000);
  timer1.start();
  timer2.start();
  timer3.start();
  timer4.start();
  timer5.start();
  }

void loop() {
  timer1.update();
  timer2.update();
  timer3.update();
  timer4.update();
  timer5.update();
  }

void printCounter() {
  Serial.print("Counter ");
  Serial.println(timer2.getRepeatsCounter());
//  Serial.println(timer2.counter()); // this original line did not compile
  }

  void printCountdown() {
    Serial.print("Countdown ");
    Serial.println(timer3.getRepeats() - timer3.getRepeatsCounter());
    // Serial.println(4 - timer3.counter());  // this original line did not compile
    }

void printMessage() {
  Serial.println("Hello!");
  }

void blink() {    // blink every 500ms
  digitalWrite(LED_BUILTIN, ledState);
  ledState = !ledState;
  }

void printCountUS() {
  counterUS++;
 // if (counterUS == 10000) {
 // Serial.println("10000 * 100us");
  if (counterUS == 5) {
    Serial.print("5 * 2000mS when millis = ");
    Serial.println(millis());
    counterUS = 0;
    }
  }

/*
Functions called in format 'timer1.start();' for the Ticker previously named timer1

void start()
Start the Ticker. Will count the interval from the moment that you start it. If it is paused, it will restart the Ticker.

void resume()
Resume the Ticker. If not started, it will start it. If paused, it will resume it. For example, in a Ticker of 5 seconds, if it was paused in 3 seconds, the resume in continue in 3 seconds. Start will set passed time to 0 and restart until get 5 seconds.

void pause()
Pause the Ticker, so you can resume it.

void stop()
Stop the Ticker.

void update()
Must to be called in the loop(), it will check the Ticker, and if necessary, will run the callback

status_t state()
Returns the state of the Ticker.

uint32_t elapsed()
Returns the time passed since the last tick, ms or us depending from the resolution.

uint16_t counter()
Returns the number of executed callbacks.
  */


text:
ESP8266-01 wrong flow control settings
Changed ESP8266-01 to wrong settings by mistake. It was working ok
at 115200 (its default settings). It was connected like this:
PC->(USB)->Arduino->ESP8266.
Using Arduino as bridge

Pins 0 and 1 (RX/TX) connected directly to ESP8266 since I didnt have
USB to TTL adapter.
MCU removed so I could make that scenario work

It was just for testing AT commands. I did it like that because I realized that I was getting errors all the time trying to connect
using SerialSoftware (and different pins in Arduino).
Found out later that SerialSoftware does not work correctly at 115200...
So I issued the following AT command:
         AT+UART_DEF=9600,8,1,0,3

Now I cannot connect to the ESP8266 to correct that setting. All I get is garbage characters. I understand it's because of the flow control settings. I set it to both RTS and CTS which I also read later ESP8266 does not support?
Have tried:

Using Putty to change settings of COM port at connect. Have tried all speeps and flow control settings combinations I could think of. I get nothing or garbage characters.
Changing COM port setting from Device Manager (Windows 7)
Flashing ESP8266 using official tool (ESPFlashDownloadTool_v3.6.1.0).It won't sync with the ESP8266. It does not allow me to adjust speed to 9600. Minimun speed that show is 115200
Changing settings in ESPFlashDownloadTool_v3.6.1.0 so it will sync at 9600 (file: spi_download.conf)

I cannot think of anymore ideas. Have I completely messed up my ESP8266?
Is there a way that I'm not aware of that could fix this problem? How?
Thanks in advance!
Jorge

Maybe https://arduino.stackexchange.com/a/31610/20513 can help? Seems like it helps in some situations at least.

AT+UART_DEF=9600,8,1,0,3

Are you aware that this configuration (3) as a rule would require both RTS and CTS extra physical signals to work ? That means, if you do not connect anything there, the level present at some pin configured anywhere would prevent ESP8266 from receiving further data from serial.
In general people use "no flow control" (0)
AT+UART_DEF=9600,8,1,0,0

andre,
As I stated in my post I did it by mistake. Nonetheless I was able to fix it by using a different flashing tool that used just one .bin file instead of many like the official ESP8266 tool does.
Can anyone please explain me why is that? Why are there different tools to flash the ESP8266? In concrete, why one requires just one file that will update the SDK and AT firmware in one pass, and the other requires many differente files? Or just a link to a site o post so I can better understand the differences?
The tool I ended up usign is "ESP8266 Flash Downloader"

The file I used: AiThinker_ESP8266_DIO_8M_8M_20160615_V1.5.4.bin
Thanks!


text:
Using SoftwareSerial.h in .cpp file
I am trying to modularize the different components in my arduino build by using objects, but am having trouble with the one controlling a wireless transceiver, which uses SoftwareSerial.h
I believe I am (generally) setting up the use of these objects correctly because I have other objects that build correctly in other files.
I think my issue is somehow part of SoftwareSerial.h, but I am not knowledgeable enough to get in and diagnose it... I think my core issue is that SoftwareSerial is not being brought in properly.
Transciever.cpp
/*
   This code controls the HC-12 transciever
*/
#include <Arduino.h>
#include <SoftwareSerial.h>

enum class TransReadStatus {
  RELAY_OFF,
  RELAY_ON,
  NO_DATA
};

class TranscieverHandler {
  public:
    TranscieverHandler(
      int txPinIn,
      int rxPinIn,
      int setPinIn,
      int baudRateIn
    ): txPin(txPinIn),
      rxPin(rxPinIn),
      setPin(setPinIn),
      baudRate(baudRateIn)
    {
      SoftwareSerial hc12(txPin, rxPin);
    }

    void init() {
      hc12.begin(baudRate);
      pinMode(setPin, OUTPUT);
      digitalWrite(setPin, HIGH);  // HC-12 normal, transparent mode
    }

    TransReadStatus checkForSignal() {
      while (hc12.available()) {             // If HC-12 has data
        incomingByte = hc12.read();          // Store each icoming byte from HC-12
        readBuffer += char(incomingByte);    // Add each byte to ReadBuffer string variable
      }
      delay(100);

      if (onBytes.equals(readBuffer)) {
        readBuffer = "";
        return TransReadStatus::RELAY_ON;
      } else if (offBytes.equals(readBuffer)) {
        readBuffer = "";
        return TransReadStatus::RELAY_OFF;
      }
      readBuffer = "";
      return TransReadStatus::NO_DATA;
    }

    TransReadStatus getLastRecievedStatus() {
      TransReadStatus newStatus = checkForSignal();

      if (newStatus == TransReadStatus::NO_DATA) {
        return lastStatus;
      }
      lastStatus = newStatus;
      return lastStatus;
    }

  protected:
    const int txPin;// = 10;
    const int rxPin;// = 11;
    const int setPin;// = 12;
    const int baudRate;// 9600
    /*
       Constants for signals
    */
    const String setOnBytes = String("SET RELAY ON");
    const String setOffBytes = String("SET RELAY OFF");
    const String onBytes = String("STATUS: RELAY IS ON");
    const String offBytes = String("STATUS: RELAY IS OFF");

    SoftwareSerial hc12;

    byte incomingByte;
    String readBuffer = "";
    TransReadStatus lastStatus = TransReadStatus::NO_DATA;
    unsigned long lastSendOnSignal = millis();

};

Output from failed compilation:
Arduino: 1.8.9 (Linux), Board: "Arduino/Genuino Uno"

/home/greg/other/arduino-1.8.9/arduino-builder -dump-prefs -logger=machine -hardware /home/greg/other/arduino-1.8.9/hardware -tools /home/greg/other/arduino-1.8.9/tools-builder -tools /home/greg/other/arduino-1.8.9/hardware/tools/avr -built-in-libraries /home/greg/other/arduino-1.8.9/libraries -libraries /home/greg/Arduino/libraries -fqbn=arduino:avr:uno -ide-version=10809 -build-path /tmp/arduino_build_227628 -warnings=default -build-cache /tmp/arduino_cache_459309 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=/home/greg/other/arduino-1.8.9/hardware/tools/avr -prefs=runtime.tools.avr-gcc-5.4.0-atmel3.6.1-arduino2.path=/home/greg/other/arduino-1.8.9/hardware/tools/avr -prefs=runtime.tools.arduinoOTA.path=/home/greg/other/arduino-1.8.9/hardware/tools/avr -prefs=runtime.tools.arduinoOTA-1.2.1.path=/home/greg/other/arduino-1.8.9/hardware/tools/avr -prefs=runtime.tools.avrdude.path=/home/greg/other/arduino-1.8.9/hardware/tools/avr -prefs=runtime.tools.avrdude-6.3.0-arduino14.path=/home/greg/other/arduino-1.8.9/hardware/tools/avr -verbose /home/greg/GitRepos/WirelessSwitch/SwitchController/SwitchController.ino
/home/greg/other/arduino-1.8.9/arduino-builder -compile -logger=machine -hardware /home/greg/other/arduino-1.8.9/hardware -tools /home/greg/other/arduino-1.8.9/tools-builder -tools /home/greg/other/arduino-1.8.9/hardware/tools/avr -built-in-libraries /home/greg/other/arduino-1.8.9/libraries -libraries /home/greg/Arduino/libraries -fqbn=arduino:avr:uno -ide-version=10809 -build-path /tmp/arduino_build_227628 -warnings=default -build-cache /tmp/arduino_cache_459309 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.avr-gcc.path=/home/greg/other/arduino-1.8.9/hardware/tools/avr -prefs=runtime.tools.avr-gcc-5.4.0-atmel3.6.1-arduino2.path=/home/greg/other/arduino-1.8.9/hardware/tools/avr -prefs=runtime.tools.arduinoOTA.path=/home/greg/other/arduino-1.8.9/hardware/tools/avr -prefs=runtime.tools.arduinoOTA-1.2.1.path=/home/greg/other/arduino-1.8.9/hardware/tools/avr -prefs=runtime.tools.avrdude.path=/home/greg/other/arduino-1.8.9/hardware/tools/avr -prefs=runtime.tools.avrdude-6.3.0-arduino14.path=/home/greg/other/arduino-1.8.9/hardware/tools/avr -verbose /home/greg/GitRepos/WirelessSwitch/SwitchController/SwitchController.ino
Using board 'uno' from platform in folder: /home/greg/other/arduino-1.8.9/hardware/arduino/avr
Using core 'arduino' from platform in folder: /home/greg/other/arduino-1.8.9/hardware/arduino/avr
Detecting libraries used...
/home/greg/other/arduino-1.8.9/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10809 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/cores/arduino -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/variants/standard /tmp/arduino_build_227628/sketch/SwitchController.ino.cpp -o /dev/null
/home/greg/other/arduino-1.8.9/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10809 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/cores/arduino -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/variants/standard -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src /tmp/arduino_build_227628/sketch/SwitchController.ino.cpp -o /dev/null
Using cached library dependencies for file: /tmp/arduino_build_227628/sketch/Buttons.cpp
Using cached library dependencies for file: /tmp/arduino_build_227628/sketch/LEDs.cpp
Using cached library dependencies for file: /tmp/arduino_build_227628/sketch/Switches.cpp
/home/greg/other/arduino-1.8.9/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10809 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/cores/arduino -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/variants/standard -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src /tmp/arduino_build_227628/sketch/Transciever.cpp -o /dev/null
/home/greg/other/arduino-1.8.9/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10809 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/cores/arduino -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/variants/standard -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src /home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.cpp -o /dev/null
Generating function prototypes...
/home/greg/other/arduino-1.8.9/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10809 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/cores/arduino -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/variants/standard -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src /tmp/arduino_build_227628/sketch/SwitchController.ino.cpp -o /tmp/arduino_build_227628/preproc/ctags_target_for_gcc_minus_e.cpp
/home/greg/other/arduino-1.8.9/tools-builder/ctags/5.8-arduino11/ctags -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives /tmp/arduino_build_227628/preproc/ctags_target_for_gcc_minus_e.cpp
Compiling sketch...
Using previously compiled file: /tmp/arduino_build_227628/sketch/Buttons.cpp.o
Using previously compiled file: /tmp/arduino_build_227628/sketch/Switches.cpp.o
/home/greg/other/arduino-1.8.9/hardware/tools/avr/bin/avr-g++ -c -g -Os -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10809 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/cores/arduino -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/variants/standard -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src /tmp/arduino_build_227628/sketch/SwitchController.ino.cpp -o /tmp/arduino_build_227628/sketch/SwitchController.ino.cpp.o
/home/greg/other/arduino-1.8.9/hardware/tools/avr/bin/avr-g++ -c -g -Os -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10809 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/cores/arduino -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/variants/standard -I/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src /tmp/arduino_build_227628/sketch/Transciever.cpp -o /tmp/arduino_build_227628/sketch/Transciever.cpp.o
Using previously compiled file: /tmp/arduino_build_227628/sketch/LEDs.cpp.o
/tmp/arduino_build_227628/sketch/Transciever.cpp: In constructor 'TranscieverHandler::TranscieverHandler(int, int, int, int)':
Transciever.cpp:23:26: error: no matching function for call to 'SoftwareSerial::SoftwareSerial()'
       baudRate(baudRateIn)
                          ^
In file included from /tmp/arduino_build_227628/sketch/Transciever.cpp:5:0:
/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.h:92:3: note: candidate: SoftwareSerial::SoftwareSerial(uint8_t, uint8_t, bool)
   SoftwareSerial(uint8_t receivePin, uint8_t transmitPin, bool inverse_logic = false);

   ^
/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.h:92:3: note:   candidate expects 3 arguments, 0 provided
/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.h:50:7: note: candidate: constexpr SoftwareSerial::SoftwareSerial(const SoftwareSerial&)
 class SoftwareSerial : public Stream

       ^
/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.h:50:7: note:   candidate expects 1 argument, 0 provided
/tmp/arduino_build_227628/sketch/Transciever.cpp: In member function 'void TranscieverHandler::init()':
/tmp/arduino_build_227628/sketch/Transciever.cpp:29:26: warning: passing 'const SoftwareSerial' as 'this' argument discards qualifiers [-fpermissive]
       hc12.begin(baudRate);
                          ^
In file included from /tmp/arduino_build_227628/sketch/Transciever.cpp:5:0:
/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.h:94:8: note:   in call to 'void SoftwareSerial::begin(long int)'
   void begin(long speed);

        ^
/tmp/arduino_build_227628/sketch/Transciever.cpp: In member function 'TransReadStatus TranscieverHandler::checkForSignal()':
/tmp/arduino_build_227628/sketch/Transciever.cpp:36:29: warning: passing 'const SoftwareSerial' as 'this' argument discards qualifiers [-fpermissive]
       while (hc12.available()) {             // If HC-12 has data
                             ^
In file included from /tmp/arduino_build_227628/sketch/Transciever.cpp:5:0:
/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.h:104:15: note:   in call to 'virtual int SoftwareSerial::available()'
   virtual int available();

               ^
/tmp/arduino_build_227628/sketch/Transciever.cpp:37:34: warning: passing 'const SoftwareSerial' as 'this' argument discards qualifiers [-fpermissive]
         incomingByte = hc12.read();          // Store each icoming byte from HC-12
                                  ^
In file included from /tmp/arduino_build_227628/sketch/Transciever.cpp:5:0:
/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.h:103:15: note:   in call to 'virtual int SoftwareSerial::read()'
   virtual int read();

               ^
In file included from /home/greg/GitRepos/WirelessSwitch/SwitchController/SwitchController.ino:32:0:
/tmp/arduino_build_227628/sketch/Transciever.cpp: In constructor 'TranscieverHandler::TranscieverHandler(int, int, int, int)':
Transciever.cpp:23:26: error: no matching function for call to 'SoftwareSerial::SoftwareSerial()'
       baudRate(baudRateIn)
                          ^
In file included from /tmp/arduino_build_227628/sketch/Transciever.cpp:5:0,
                 from /home/greg/GitRepos/WirelessSwitch/SwitchController/SwitchController.ino:32:
/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.h:92:3: note: candidate: SoftwareSerial::SoftwareSerial(uint8_t, uint8_t, bool)
   SoftwareSerial(uint8_t receivePin, uint8_t transmitPin, bool inverse_logic = false);

   ^
/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.h:92:3: note:   candidate expects 3 arguments, 0 provided
/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.h:50:7: note: candidate: constexpr SoftwareSerial::SoftwareSerial(const SoftwareSerial&)
 class SoftwareSerial : public Stream

       ^
/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.h:50:7: note:   candidate expects 1 argument, 0 provided
In file included from /home/greg/GitRepos/WirelessSwitch/SwitchController/SwitchController.ino:32:0:
/tmp/arduino_build_227628/sketch/Transciever.cpp: In member function 'void TranscieverHandler::init()':
/tmp/arduino_build_227628/sketch/Transciever.cpp:29:26: warning: passing 'const SoftwareSerial' as 'this' argument discards qualifiers [-fpermissive]
       hc12.begin(baudRate);
                          ^
In file included from /tmp/arduino_build_227628/sketch/Transciever.cpp:5:0,
                 from /home/greg/GitRepos/WirelessSwitch/SwitchController/SwitchController.ino:32:
/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.h:94:8: note:   in call to 'void SoftwareSerial::begin(long int)'
   void begin(long speed);

        ^
In file included from /home/greg/GitRepos/WirelessSwitch/SwitchController/SwitchController.ino:32:0:
/tmp/arduino_build_227628/sketch/Transciever.cpp: In member function 'TransReadStatus TranscieverHandler::checkForSignal()':
/tmp/arduino_build_227628/sketch/Transciever.cpp:36:29: warning: passing 'const SoftwareSerial' as 'this' argument discards qualifiers [-fpermissive]
       while (hc12.available()) {             // If HC-12 has data
                             ^
In file included from /tmp/arduino_build_227628/sketch/Transciever.cpp:5:0,
                 from /home/greg/GitRepos/WirelessSwitch/SwitchController/SwitchController.ino:32:
/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.h:104:15: note:   in call to 'virtual int SoftwareSerial::available()'
   virtual int available();

               ^
In file included from /home/greg/GitRepos/WirelessSwitch/SwitchController/SwitchController.ino:32:0:
/tmp/arduino_build_227628/sketch/Transciever.cpp:37:34: warning: passing 'const SoftwareSerial' as 'this' argument discards qualifiers [-fpermissive]
         incomingByte = hc12.read();          // Store each icoming byte from HC-12
                                  ^
In file included from /tmp/arduino_build_227628/sketch/Transciever.cpp:5:0,
                 from /home/greg/GitRepos/WirelessSwitch/SwitchController/SwitchController.ino:32:
/home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.h:103:15: note:   in call to 'virtual int SoftwareSerial::read()'
   virtual int read();

               ^
Using library SoftwareSerial at version 1.0 in folder: /home/greg/other/arduino-1.8.9/hardware/arduino/avr/libraries/SoftwareSerial
exit status 1
no matching function for call to 'SoftwareSerial::SoftwareSerial()'

: hc12(txPin, rxPin),..

@Juraj I figured I was doing something simple wrong. If you make that an answer, I'll mark it as accepted

The member initialization is intended for objects construction. For ints you can do an assignment in the constructors body
TranscieverHandler(int txPinIn, int rxPinIn, int setPinIn, int baudRateIn)
    : hc12(txPin, rxPin) {
  txPin = txPinIn;
  rxPin = rxPinIn;
  setPin = setPinIn;
  baudRate = baudRateIn;
}

Good to know, it had been a while since I last touched real c++ code

https://www.learncpp.com/cpp-tutorial/8-5a-constructor-member-initializer-lists/

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


text:
Adafruit RTC begin() not returning false
I am programming my arduino with the capability to keep time with the DS3231 from Adafruit. I do not have the module yet, but am trying to figure out the rest of the build without it.
However, it seems like the way to determine RTC is working does not work, as it returns true, even without the module.
Example code from the Adafruit RTC library for using this module:
// Date and time functions using a DS3231 RTC connected via I2C and Wire lib
#include <Wire.h>
#include "RTClib.h"

RTC_DS3231 rtc;

char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

void setup () {

#ifndef ESP8266
  while (!Serial); // for Leonardo/Micro/Zero
#endif

  Serial.begin(9600);

  delay(3000); // wait for console opening

  if (! rtc.begin()) { // part that fails. begin() returns true when should return false
    Serial.println("Couldn't find RTC");
    while (1);
  }

  if (rtc.lostPower()) {
    Serial.println("RTC lost power, lets set the time!");
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
    // This line sets the RTC with an explicit date & time, for example to set
    // January 21, 2014 at 3am you would call:
    // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
  }
}
....

If you look at the library source code it will be clear why begin() returns true.
From https://github.com/adafruit/RTClib/blob/1.2.0/RTClib.cpp#L434-L437:
boolean RTC_DS3231::begin(void) {
  Wire.begin();
  return true;
}

I suppose they plan to eventually make the return value of begin() mean something but for now it does not.

This should not happen anymore.
Actually, if you have a look at the last version of the source code on GitHub (1.13.0), you will see that now the developers implemented also a case in which the method returns false.
from https://github.com/adafruit/RTClib/blob/1.13.0/RTClib.cpp#L1537-L1543 :
boolean RTC_DS3231::begin(void) {
  Wire.begin();
  Wire.beginTransmission(DS3231_ADDRESS);
  if (Wire.endTransmission() == 0)
    return true;
  return false;
}


text:
Passing function as argument, with capture, what type to declare in function?
This probably has a simple resolution, but can't find the right combination.
I'm trying to setup a function (setupScreen) to take as an argument a function to do the actual setup:
void ScreenHelpers::setupScreen(void (*setupFunc)(ThinkInk_290_Tricolor_Z10*)){
    ScreenHelpers::waitTilCanRefreshScreen();

    (* setupFunc)(&display_two);

    lastUpdateTime = millis();
}
//...
void ScreenHelpers::displayErrorMessage(const String message){
    const char* text = message.c_str();
    ScreenHelpers::setupScreen([text](ThinkInk_290_Tricolor_Z10* screen) {
        screen->clearBuffer();
        ScreenHelpers::simpleDisplayText(
            screen,
            text,
            EPD_RED
        );
     });
}

This works, until I added the [text] to capture the text variable in the lambda, where it resulted in:
ScreenHelpers.cpp: In static member function 'static void ScreenHelpers::displayErrorMessage(String)':
ScreenHelpers.cpp:45:4: error: no matching function for call to 'ScreenHelpers::setupScreen(ScreenHelpers::displayErrorMessage(String)::<lambda(ThinkInk_290_Tricolor_Z10*)>)'
   });
    ^
ScreenHelpers.cpp:21:6: note: candidate: 'static void ScreenHelpers::setupScreen(void (*)(ThinkInk_290_Tricolor_Z10*))'
 void ScreenHelpers::setupScreen(void (*setupFunc)(ThinkInk_290_Tricolor_Z10*)){
      ^~~~~~~~~~~~~

What should my function declaration look like to accept this?

This is not an Arduino specific question, it is a pure C++ issue. Please ask this at [so], if you still don't know how to do it, after doing the necessary research.

I have to disagree, Arduino's C++ is an odd subset of the language. I'd argue it is reasonable to look to Arduino-specific places for advanced language features.

The compiler used by the Arduino is a standard GNU C++ compiler targeting the AVR or ARM processor. As such it is not really limited in the language, and we program in standard C++. But the accompanied C++ libraries can be incomplete, for example <functional> might be missing, granted. -- So it had helped if you had mentioned your specific Arduino target.

ScreenHelpers::setupScreen() expects its argument to be a plain
function. A capturing lambda is not a plain function: it is rather a
functor, i.e. an object that is callable like a function.
The standard way of passing such a lambda in C++ is to declare the
parameter to be of type std::function:
#include <functional>

void ScreenHelpers::setupScreen(std::function<void(ThinkInk_290_Tricolor_Z10*)> setupFunc) {
    ...
}

This may or may not work depending on the Arduino board you are using.
AVR-based boards rely on a C library that only minimally supports C++.
You cannot use <functional> on those boards. If you are using one of
those boards, your options are:

Try to find an implementation of of the C++ STL for AVR-based boards.
I have seen at least one floating around in the Net.

Use the standard C idiom for defining a callback with a void*
parameter:

void ScreenHelpers::setupScreen(
      void (*setupFunc)(ThinkInk_290_Tricolor_Z10*, void*),
      void *callback_data) {
   setupFunc(&display_two, callback_data);
   //...
}

// elsewhere:
ScreenHelpers::setupScreen([](ThinkInk_290_Tricolor_Z10 *screen, void *data) {
   const char *text = (const char *) data;
   // ...
}, (void *) text);

Thanks! Looks like my board supports the lambdas, making things easy!
The second option crossed my mind too, was also thinking maybe making the *data param a varargs.


text:
Problem with LED (Builtin) connected to pin 13
This is Aakash. Student of Electrical Engineering in a University.
I want to ask some information. Today I Purchased Arduino UNO R3 board. and facing some problem which are :
          "**Builtin LED at pin#13 is always ON on my board**".

Is there any problem with the board ?
I tried to upload these sketches and got these results::
1)...with empty setup(){} and empty loop(){}, Still LED is ON.
2)...When I uploaded these command "pinMode(LED_BUILTIN,OUTPUT);" in setup() and "digitalWrite(LED_BUILTIN,LOW);" in loop(), LED turned OFF
3)...If i touch pin13 and Ground both by a wet finger at back of board, LED turns OFF.
4)...but on uploading empty or any other code, BUILTIN_LED turns ON again and do not turns OFF.
Kindly reply me ASAP! So that if i have got faulty Board then i might go for claim.

Possible duplicate of Uno pin 13 LED mysteriously always ON at 0.14V unless pinMode OUTPUT, also see https://arduino.stackexchange.com/questions/18263/arduino-in-built-led-is-not-turning-off

This is a normal thing. All my arduino boards do the same. The reason for this is that the micro controller don't care about the pins that aren't defined in the code. When they aren't defined they all have a HIGH on them. Here is my board with this code:
void setup() {
}
void loop() {
}


text:
Serial communication between two microcontrollers w/ separate power supplies
Fair warning: I'm an electronics n00b.
I'm trying to get an Arduino Uno R3 to send data over 9600 baud serial to a Wemos D1 Mini Pro.
What worked (mostly):
Powering (5V) Arduino off a 4 AA barrel jack battery pack.  Measured voltage between Vin and GND as ~4.5V (the batteries were somewhat old).  4.5V is low enough to be safe as 5V input for the (3.3V) Wemos, which can be powered off its 5V pin (it's the input to the board's 3.3V regulator).  I tied the Arduino's GND and Wemos's, took the Arduino's Vin pin to Wemos's 5V pin (providing it ~4.5V), and connected Arduino's TX to Wemos's RX via a voltage divider (a 2.2 kΩ resistor and a 4.7 kΩ; verified <3.3V with a multimeter).
And, everything worked, for a few brief, glorious minutes.  Arduino sent 1 byte over serial every 3 seconds, alternating the builtin LED each time.  Wemos read them and served up a web page showing the latest values.  But, after a few minutes, the Wemos started to read data the Arduino shouldn't be sending (0x00 bytes; the Arduino program was only sending uppercase ascii letters).  I noticed that the Arduino builtin LED, that's supposed to be alternating every 3s, was blinking rapidly.  I think I drained the batteries too far to provide both the Wemos and the Arduino with enough power, and the Arduino got stuck in a boot cycle (and I suppose it's sending 0x00 over its TX pin while booting).
What didn't work:
Since changing batteries frequently would be a pain, I tried plugging the Wemos into a micro USB wall adaptor, and the Arduino into a 12V 1A barrel jack wall wart, and unplugging Arduino's Vin from Wemos's 5V (leaving GND tied together).  Plugged both adaptors into a single power strip, and turned it on.  Both boards powered up, and were running their programs (I could connect to the Wemos over WiFi and it would serve me a page; the Arduino builtin LED was alternating every 3 seconds as expected).  A multimeter read the voltage between Wemos RX and GND as 3.34V, but the Wemos wasn't receiving any serial data.
After that experiment, I switched back to the battery pack, wired Arduino Vin to Wemos 5V again, swapped out 2 of the 4 batteries, and everything works.
TLDR:
I powered a 5V Arduino off 12V and a 3.3V Wemos off 5V, and the Wemos couldn't read serial data being transmitted by the Arduino.  When I powered them both off a 4.8V battery pack, everything worked.  Why didn't it work when they had separate supplies and a common ground?
Sorry for the wordy question; I'm confused enough to not know which details are relevant!

wasn't the 5 V usb adapter some smart type charger with usb communication to negotiate the charging current?

power the wemos Vin (5 V) from 5 V of arduino with arduino connected to 12 V adapter

Not sure about the smartness of the USB charger... I've gotten the impression that the Arduino's 5V regulator might not be able to source enough current to power a Wemos. I found a reference earlier today to ESP8266's drawing up to 850 mA under heavy WiFi load, and https://electronics.stackexchange.com/questions/67092 says that the Arduino 5V can source less than 900 mA if Vin is above 7V. Anyway, I'm not really looking for workarounds (I plan on trying a USB power bank next) - I'm more interested in learning why it didn't work.

I do not believe that 850 mA. The 5 V pin is not a workaround, it is it's purpose. 2) You could try for wemos a simple AC/DC (USB) adapter without data lines connected. The data lines go over USB chip to Rx/Tx pins. 3) Charging power banks turn off if only small current is drawn.


text:
interrupt not triggered correctly
I have an arduino uno and want to react to three sensors, which should trigger an ISR.
I wrote the following program, and for sensor 3 it works, however the other two sensor don't seem to trigger an interrupt. I checked the sensors by connected each one to pin A5, and every sensor worked.
Is there a better way to check which pin caused the interrupt than digitalRead()? Is this maybe even my problem?
#define pinDrehen 12
#define pinRevDrehen 13

volatile boolean triggeredAngleSensor1 = false;
volatile boolean triggeredAngleSensor2 = false;
volatile boolean triggeredAngleSensor3 = false;
volatile unsigned int triggeredTimeAngleSensor1;
volatile unsigned int triggeredTimeAngleSensor2;
volatile unsigned int triggeredTimeAngleSensor3;

ISR (PCINT1_vect) // handle pin change interrupt for for A0 to A6 and reset [only A3 to A5 are enabled]
{
  if (digitalRead(A3)){//angle sensor 1
    triggeredAngleSensor1 = true;
    triggeredTimeAngleSensor1 = millis();
  }
  if(digitalRead(A4)){//angle sensor 2
    triggeredAngleSensor2 = true;
    triggeredTimeAngleSensor2 = millis();
  }
  if(digitalRead(A5)){//angle sensor 3
    triggeredAngleSensor3 = true;
    triggeredTimeAngleSensor3 = millis();
  }
}

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

  // pin change interrupt
  PCMSK1 |= bit (PCINT13) | bit (PCINT12 | bit (PCINT11));  // want pin A5 or A4 or A3
  PCIFR  |= bit (PCIF1);    // clear any outstanding interrupts
  PCICR  |= bit (PCIE1);    // enable pin change interrupts for A0 to A6 and reset

  pinMode(pinDrehen, OUTPUT);
  pinMode(pinRevDrehen, OUTPUT);

  //start turning machine:
  digitalWrite(pinDrehen, HIGH);
  digitalWrite(pinRevDrehen, HIGH);
}

void loop() {
  if(triggeredAngleSensor1){
    triggeredAngleSensor1=false;
    Serial.print("Sensor 1 interrupt at time: ");
    Serial.println(triggeredTimeAngleSensor1);
  }
  if(triggeredAngleSensor2){
    triggeredAngleSensor2=false;
    Serial.print("Sensor 2 interrupt at time: ");
    Serial.println(triggeredTimeAngleSensor2);
  }
  if(triggeredAngleSensor3){
    triggeredAngleSensor3=false;
    Serial.print("Sensor 3 interrupt at time: ");
    Serial.println(triggeredTimeAngleSensor3);
  }
  delay(5);
}

This line:
PCMSK1 |= bit (PCINT13) | bit (PCINT12 | bit (PCINT11));  // want pin A5 or A4 or A3

is probably not what you want.
Let's break it down and look at just what you have there.
bit (PCINT13)

The bit function returns the bitmask for a specific bit.  So if you pass it 3 you get a value with the third (counting from 0) bit enabled (1 << 3, or 0b1000, or 0x08).
PCINT13 is 5.  So you have 1 << 5, or 0x20.
So far so good.  Now you OR that with:
bit (PCINT12 | bit (PCINT11))

And this is the bit that's wrong.  Inside is bit (PCINT11) which, with PCINT11 being 3, results in 0x08.  That is then ORed with PCINT12, which is 4.  The result is 8+4. That's 12. The value 12 is then fed through another bit() function, which gives you 1<<12. That, of course, overflows outside of an 8-bit value, so you end up with 0.
The final result is ORed together with the 0x20 from before, which of course remains as 0x20.
What you probably wanted (and intended) is to have:
PCMSK1 |= bit (PCINT13) | bit (PCINT12) | bit (PCINT11);  // want pin A5 or A4 or A3

the logic in the isr is incorrect.
generally, you want to set up the pcint pins so that they respond to an edge.
in the isr (with multiple pin changes), you will need to either 1) preserve and maintain the previous state so to determine which pins have experienced a state change; or 2) use pin change flags.
what you have there can lead to false determination of triggers.

In my application a sensor will be triggered only for a short time (at least while i am reacting to interrupts) and two sensors can not deliver HIGH at the same time, therefor i don't think this is an issue. However i am curious about your two possibilities. Wouldn't i realisiere the first one with (boolean) flags, which would be the second one? (Or are pin change flags some bits in a hardware register and you don't mean flags i set on my own?)


text:
5-bit communication method?
OK, I'm working on a project where I want to have multiple toggle switches create a "code" to determine further actions. This is essentially 5-bit communication process that will create output with a 32-bit range of outcomes from 00000 to 11111.
I'm testing the method with three switches, so if the first and third switch are HIGH/on it will read 101. Second and third, 011 etc. I'm not versed enough to know if there is a better method here, but is there a better way to do this?
    // Define the pins being used
int pin_switch = 10;
int pin_switch2 = 11;
int pin_switch3 = 12;

// create int for 3-digit code
int code = 000;

void setup()
{
    Serial.begin(9600);
    pinMode(pin_switch, INPUT);
    pinMode(pin_switch2, INPUT);
    pinMode(pin_switch3, INPUT);
}

void loop()
{

if pin_switch == HIGH;
    {code += 100;}

if pin_switch2 == HIGH;
    {code += 10;}

if pin_switch3 == HIGH;
    {code += 1;}

Serial.print(code);

// operate based on code output
if code == 101;
    {do 101 stuff}

if code == 001
    {do 001 stuff}

// reset code for next loop so numbers don't keep rising
code = 000;
}

Note: don't write leading zeros in a decimal number in C or C++ (or a bunch of other languages) - the numbers will be treated as octal rather than decimal which is very rarely what you want.

It would be more convenient and less typing if you put all your switch pins in an array. That way you can loop over it to configure the ports and read them rather than copy/pasting the "same" code over and over.
The calculation of the resulting code is a classic "shift and add" loop. I put both the decimal version you seem to want and the more "usual" binary version in the snippet below.
The idea behind that sort of loop is:

start with an empty (zero) code
multiply the code by 10 (or left-shift once for binary)
read a switch, add 1 to the code if it is HIGH
go back to step 2 if there are more switches.

The value of the switches already read get "pushed" one slot to the left before reading the next switch, resulting in the code you want.
The order in which you list the ports in the array is important: the first port in the array will change the leftmost (most significant) digit/bit in the code.
const uint8_t switch_pin[] = { 10, 11, 12 };
const uint8_t num_switches = sizeof(switch_pin)/sizeof(switch_pin[0]);

void setup() {
  // Set all switch pins to input mode
  for (uint8_t i = 0; i < num_switches; ++i) {
    pinMode(switch_pin[i], INPUT);
  }
  Serial.begin(9600);
}

void loop() {
  int code = 0;
  // Read each switch and compute the code
  for (uint8_t i = 0; i < num_switches; ++i) {
    // If the code is supposed to be in decimal
    code = code * 10;
    code += digitalRead(switch_pin[i]);
    /* For a binary version, code only needs to be 8 bits long:
    code <<= 1;
    code |= digitalRead(switch_pin[i]);
    */
  }

  // Do stuff with the code
  Serial.println(code);
  delay(200);
}

Oh thank you Mat, I think Shift and Add is the terminology I was lacking!
I think I do want to go Binary, I'm thinking I will expand this to five switches so the shifting aspect simplifies that in my mind.
Looking at your code here: code <<= 1;
How would I shift and add for the other parts of the code? The prior would output 010, right? Would I just need to do <<<=1; AND <<= 1 to get 110?
Thank you for the help.

If code is 1010, code <<= 1 (which is the same as code = code << 1) will result in 10100 (shift left, insert a zero at the right). The code |= 1; would "fill" the last position to 10101. code |= 0; would do nothing.

Unfortunately your code is all over the place. You have to use C/C++ syntax, which you don't. Also you don't actually read any input.

if statements look like this:
  if(condition){
      my_code();
  }

if(pin_switch == HIGH) (corrected syntax) will always be false, since pin_switch is of value 10. Its just the pin number. To actually read the pin, you need to use digitalRead() like this:
  if(digitalRead(pin_switch) == HIGH)

or even simpler
  if(digitalRead(pin_switch))

It seems that you want to manipulate the bits with code += 100;, but the compiler takes numbers as decimal. So you are adding 100 to code. Please look into the bitwise operators. Also: You can actually write numbers in binary or hex by using 0b101 or 0xF3 respectively (the values here are just examples). This also means, that int code = 000; is the same as int code = 0;.

To build the 3 digit code from input you could put them together via bitwise operators:
code = (digitalRead(pin_switch3) << 2) | (digitalRead(pin_switch2) << 1) | digitalRead(pin_switch);

Depending on your used Arduino and the used pins you can get this even easier. The pins are sorted into ports. Each port has a Special Function register, which holds the current state of the pins. You can mask away any unwanted pins and shift the number to be right justified. For example: On the Uno and Nano pins 2 to 7 belong to PORTD. So, if you use pins 2 to 4 for your 3 switches, you could get the code like:
code = (PIND & 0b00011100) >> 2;

This is a bit more difficult to understand, but it will help you later on, when pursuing Arduino more.

For deciding what action to do based on the code, it is normally easier to use a switch case statement:
switch(code){
    case 0b101:
        do_something();
        break;
    case 0b011:
        do_something_else();
        break;
}

Thank you! Yes my code was thrown together hastily from an example to test the method.
Really appreciate the direction here, I'll dig into bitwise operators more!

@Mulcch oops, corrected a small error. I used PORTD instead of PIND. The former is used to set the output state of a pin, the latter reflects the current input state.

Thanks for catching! I'm not sure I'll go that route, but really helpful to know about that.


text:
Why isn't my ESP32 staying in Deep Sleep longer than 35 minutes?
I've been having an odd issue with a new custom ESP board. I can't push deep-sleep time past 35 minutes no matter how I adjust the timing.
Below is my current pertinent code, but basically the device wakes up, reads several environmental sensors, sends them to the cloud and then turns off. I'm aiming to sleep for an hour between readings to preserve battery power.
 #include <esp_deep_sleep.h>

int SLEEP_TIME;

#define uS_TO_S_FACTOR 9e9  //Conversion factor for micro seconds to seconds
#define TIME_TO_SLEEP  9e8 //Time ESP32 will go to sleep (in seconds)

SLEEP_TIME = (uS_TO_S_FACTOR * TIME_TO_SLEEP);
esp_sleep_enable_timer_wakeup(SLEEP_TIME);

esp_deep_sleep_start();

use uint64_t instread of int. and prefix hex constants with 0x

@Juraj Thank you! This worked great.


text:
Arduino: using digital pins to emulate USB device
Is there any "easy" way to emulate USB keyboard or gamepad using digital pins on Arduino Mega? I looked at Uno-Joy/Mega-Joy, but I dont find firmware changes appealing.

No.  There is not anything like that.

@Delta_G - that's not really true.  It is possible, see V-USB.  But perhaps not "easy".  Reprogramming the ATmega8u2/ATmega16u2 on boards having that for their USB-serial interface is also an option.

There is (or was) an implementation of software-only USB for the Arduino. I think it was called V-USB, though I am having trouble finding it now.
I think it may be this library though nothing has happened with that for a number of years.
Personally, I wouldn't recommend it, though, and would suggest using a board with a real USB interface, such as the Arduino Leonardo, chipKIT Lenny, or Teensy 3.x.

How much easier would it be with different hardware, say Leonardo?

Much easier. You just use the Joystick library: https://github.com/MHeironimus/ArduinoJoystickLibrary

Nice. However, there is one more problem: I am using Mega at the moment, because I need to read voltages off 8 different sources and make it to digital output. Is there any device that would have at least 8 analog pins?

Teensy 3.6, and you don't want the Joystick library - it has its own USB stack that works differently: https://www.pjrc.com/teensy/td_joystick.html

Thanks, but its a bit pricy, it would be cheaper to use two arduinos.

Or multiplex your analog inputs, or use an external ADC chip.

Right, didnt think about that. Leonardo it is, then. Also, according to arduino.cc, you can use some digital pins as analog pins.

Teensy 3.6 is probably overkill, check the number of analog inputs on the Teensy 3.2 or Teensy LC.

@VojtaDoležal You can get a Pro Micro for $4. It uses the same MCU as a Leonardo.


text:
Attiny85 not able to understand data from 433Mhz using VirtualWire.h
The basic plan is to have a Attiny85 pass information from a 433Mhz RF module to another chip/Arduino via I2C using VirtualWire and Wire libraries. I have been able to make this system work on their own using Arudino Nano's to debug, but the Attiny85 (A85) seems unable to grab the data from the RF 433 Mhz.
So have spent a few days doing some more research, and basically putting each component separate, to make sure what is being sent is correct.

433 Mhz transmitter is working by sending a 9 digit number, using VirtualWire.h.
Nano with a 433 Mhz receiver is receiving 9 digit
number, VirtualWire.h.
Attiny85 is sending either a no data, or the 9 digit number, to another Nano using Wire.h.
The Nano is getting only No Data, so the I2C is working between A85 and Nano.

Attiny85, on Pin 1 (pin 6 on chip) is not getting any data from the 433 Mhz, which works on (2). I connect the GND of the 433 RX to the chip.
Here is the Receiver code:
#include <VirtualWire.h>
#include <Wire.h>
void setup() {
  pinMode(A3, OUTPUT);
  Wire.begin(); // join i2c bus (address optional for master)
  vw_set_ptt_inverted(true); // Required for DR3100
  vw_setup(4000);   // Bits per sec
  vw_set_rx_pin(1);
  vw_rx_start();       // Start the receiver PLL running
}
void loop() {
  uint8_t buf[15];
  uint8_t buflen = 15;
  if (vw_get_message(buf, &buflen)) // Non-blocking
    {
      digitalWrite(A3, LOW);
      Wire.beginTransmission(8); // transmit to device #8
      for (int i = 0; i < buflen; i++) {
        Wire.write(buf[i]);
      }
      Wire.endTransmission();    // stop transmitting
    } else {
      digitalWrite(A3, HIGH);
      Wire.beginTransmission(8); // transmit to device #8
      Wire.write("no DATA");
      Wire.endTransmission();    // stop transmitting
     }
}

Here is the Transmitter code:
#include <VirtualWire.h>
int xPin = A7;
int yPin = A6;
int buttonPin = 2;

int xPosition = 0;
int yPosition = 0;
int buttonState = 0;
const char *controller;
void setup() {
  Serial.begin(9600);
  pinMode(12,OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(yPin, INPUT);
  pinMode(xPin, INPUT);
  pinMode(buttonPin, INPUT_PULLUP);
  vw_set_ptt_inverted(true); //
  vw_set_tx_pin(12);
  vw_setup(4000);// speed of data transfer Kbps
}

void loop(){
   xPosition = analogRead(xPin);
   yPosition = analogRead(yPin);
   buttonState = digitalRead(buttonPin);
if(xPosition > 0 || yPosition > 0) {
  String Data = (xPosition + yPosition);
  controller = Data;
  vw_send((uint8_t *)controller, strlen(controller));
  vw_wait_tx(); // Wait until the whole message is gone

} else {
  digitalWrite(13, 0);
  digitalWrite(4, 1);
  controller = "#s0_0";
  vw_send((uint8_t *)controller, strlen(controller));
  vw_wait_tx(); // Wait until the whole message is gone
}

Serial.println(controller);

}

So basically the A85 is not getting past if (vw_get_message(buf, &buflen)) { on pin 1. But does when using the Nano on pin D2, from the same transmitter, but not at the same-time of-course.
Am I using the wrong Pin on the A85? Chip pin 5 and 7 are used for the I2C so it only leaves analog pins so not sure they would work either. I also tried 8 Mhz and 1 Mhz when loading the A85.
I  have tried different Cores as suggested from Google, different versions of VirtualWire and clocked the Attiny 1Mhz, 8Mhz and 16Mhz. None of have worked.

Not sure what else I am missing?

@ChrisStratton Hi, the Nano is just for debugging, rather than using LED's as I wanted to make sure the numbers being transmitted are correct.  The end product will eventually be a Attiny84a.  The issue is Servo.h and VirtualWire.h do not mix (Both use Timer1), hence the work around, and to make the circuit smaller.

Have you tried using the Radiohead  library? I know you said you tried different versions of Virtual Wire. The RH_ASK class works on a 328p and a nano for sure and they claim a simple Rx program can run on a ATTiny85. They have documentation under RH_ASK regarding the changes you need make to the library.
Another possible fix is to edit the Virtual Wire library files, they might have variables like "Max_payload" (Radiohead does) whose size can be decreased.
I haven't actually read the Virtual wire library, but I am sure Radiohead should fix your problems.
If this doesn't work, do you have an oscilloscope? Maybe we can try debugging it like that.
Edit: Maybe try commenting out the vw_set_ptt_inverted line first. I don't think you are using the DR3100. Might not make a difference because you haven't actually set a pin for ptt.
Next thing you can try is just connecting the data pin of the Tx to the Rx. You should be able to check if the module is actually connected to the ATTiny with this.


text:
What is better approach for non blocking pid algorithm?
I'm developing software side for 3 axes robot where are 360° continuous rotating servos used Documentation here
these servos have its own feedback system so it's possible to control it's position via pid system, when im using only one PID algorithm in clear sketch just for this pid everything working OK but when I want to use multiple PIDs there are problem with delays and every next function that is used in the sketch will result in bigger delays that make these servos flicking because it's executed in main function
int pinFeedback = pin_comes_here;

float tHigh = 0;
float tLow = 0;
int tCycle = 0;
float dc = 0;
float angle = 0;
float dcMin = 2.9;
float dcMax = 97.1;

void setup() {
  pinMode(pinFeedback, INPUT);
}

void loop() {
    while(1) //From Parallax spec sheet
    {                                       //There is core of the problem
      tHigh = pulseIn(pinFeedback, HIGH);
      tLow = pulseIn(pinFeedback, LOW);
      tCycle = tHigh + tLow;
      if ( tCycle > 1000 && tCycle < 1200)
        {
          break; //valid tCycle;
        }
    }

  dc = (100 * tHigh) / tCycle; //From Parallax spec sheet, determine the percentage of the HIGH in the pulse

  angle = ((dc - dcMin) * 360) / (dcMax - dcMin + 1); //From Parallax spec sheet

  if (angle < 0)
  {
    angle = 0;
  }
  else if(angle > 359)
  {
    angle = 359;
  }

    //This is just angle calculation part, we have angle as output value from this algorithm so its possible to calculate error how much to left or right value from out target angle value and adjust servo position via standard servo library

}

Reason why i need non blocking angle calculating is that because with everything this, i need to be able to control angles from firmata protocol and not just firmata but there can't be anything else done in sketch and i mentioned everything else causing bigger delays between reading signal, calculating angle, adjusting position, and every next function that could be placed in main loop.
So i came to the point that i need to use timer and interrupts like servo library uses by creating something like basic servo library wraper where i create PID class that inherit Servo class members for sake of accesing servo members from one object (attach, write) and two different approaches came to my mind

This PID class could instead of waiting in while loop for pulseIn sacrifices another one Timer that could divide feedback signal period which is long 1,1millisecond (see documentation, heading: feedback signal) by checking if it's up or down every several microseconds and counting total signal uptime for period and then calculate angle and error and adjust position with inherited write() member for every object from one timer
Using attachInterrupt that could behave similar like pulseIn but outside of main loop for every object(with same approach with PID class with inherted servo class)

The main issue you have is that pulseIn() is completely blocking - and your while loop doesn't help much either.
The "proper" (or what I would consider the "proper") way of dealing with this is to use a timer in gated mode. Actually you need two timers, but the Arduino already provides you micros() that will do for one of them.
Basically your pulsed signal is input into the gate input of a timer. That timer, when the gate input is HIGH, will count the number of ticks from whatever clock source you configure it for (system clock, etc, with or without prescaler, etc). It also needs to be configured so that the timer triggers an interrupt at the falling edge of the gate.
That interrupt reads the count from the timer and resets the count to 0 ready for the next pulse. It also uses micros() to work out the time between successive falling edges (should be about 1100us).  A little bit of maths is needed to calculate the time from the count.
It's not something I have ever done with an Arduino - I have only used a PIC32 for it - though I assume that AVR timers have a gated mode (they should have; they are fairly comprehensive timers). Check the datasheet to be sure - as well as for how to configure it.  On the PIC32 I used two timers both running at the same speed from the same clock source - one in gated mode to count the HIGH time and one in free-running mode to count the full period time. The duty % is then the ratio of the two counts and you don't care about the actual time in human-created units.
Of course, it goes without saying that you need a gated timer for each servo you want to sense...


text:
Power Down Interrupt Arduino
Does anyone know a way to call an interrupt when an Arduino loses power to have it fire a small function real quick?
It'd be a quick EEPROM write of one variable.
I know you can use interrupts on certain pins when they get pulled low, I'm just not sure if it's possible on the power pin.
Or if there would still be enough power in the controller to finish that function.
I have the Node MCU board but it's programmed in Arduino c++.

Not directly, no.  When an Arduino or ESP8266 has lost power it's lost power. You need external circuitry to keep providing power after the power input has been removed, and alert your target chip that power has gone.

simulate this circuit – Schematic created using CircuitLab
C1 wants to be massive. The ESP8266, because of the WiFi interface in it, consumes a lot of power.  Also, writing to EEPROM or Flash (which the ESP8266 has instead of EEPROM) takes extra power.
Ideally, C1 wants to be a small Super-Cap to keep the physical size small.  For an ESP8266 you're probably talking thousands of uF.
An alternative is to use the 47L16 (or similar) EERAM chip which is designed to save its internal SRAM contents to internal EEPROM when power is lost using its own dedicated capacitor-based power reservoir.

Does the 47L16 save to it's own internal EEPROM or to the EEPROM of the MCU?

Internal. RTFM.


text:
Powering up a 16x2 LCD display with only a 9V battery
I'm using an Arduino (Nano 33 IoT) board for a project and apparently this board can only supply with 3.3 volts when a 9V battery is connected to it through Vin and GND pins. In other words, I'm powering the Arduino board with a 9V battery, but I want to power supply an LCD display through my Arduino, but I can't.
This Arduino board only has a 3.3 volts pin. It has a 5V pin but it's only enabled when the Arduino is powered by USB.
The problem: The LCD display only takes up to 5.5V, and its minimum required voltage is 4.5V. I cannot power it from the Arduino board because voltage is too low, and I cannot power it directly from the 9V battery because it's too high.
What can be done?
Note: I don't have a voltage regulator to use between the LCD and battery.
Is it possible to use voltage divider?
Note: The LCD screen that I'm using is connected to I2C protocol module. It has only 4 pins: SCL and SDA pins (connected to arduino), and 2 power pins (GND and VCC).
it should look like this when connected to a regular arduino uno:

What would the circuit look like if I desire to use voltage divider?
Or can I simply use just one resistor between the 9V battery positive pin and the LCD's positive power pin?

You can't use resistor, you need a regulator to bring the 9v down to 5V. BTW, how long do you expecting your 9V battery to last for? With WiFi (Nano 33 IoT has Wifi chip that could take up to 150mA during transmission), plus display, it won't last long.

To add to the list of problems that @hcheung started, you should consider if the LCD you have chosen is able to reliably operate while receiving what is likely a 0 to 3.3 volt data signal.  Some might, others may not. I2C is an open drain bus, but is it pulled up to 3.3 volts on the processor board?  Or is it pulled up to 5 volts on the LCD board? In the latter case, you need to instead ask if the processor is 5 volt tolerant.

... follow up: I could put the above into an answer w/more details if you like.  But, if this were my project, I'd go out and buy an I2C LCD that is designed to work at 3.3 volts.  Otherwise some of the things you would need to do: Buy a 9 to 5 volt regulator, understand how an I2C bus works which might lead to removing SMD parts on the Nano 33 IoT PCB and / or might lead to adding parts to the LCD PCB.

your picture shows a UNO, that would work. Posting the correct frizzy picture would help. Best is to post an annotated schematic.

If it's important to you to have backlighting, you should probably say. Because that will have an impact on any answer you get.

Yeah, battery won't last long. I think if I turn off backlight it would make it last slightly longer.
@st2000 I think that would be a good solution instead of buying a regulator. But most LCDs need 5V to work. If I find one with I2C bus which operates at 3.3, it would be the best solution.

Although it is effectively a 3.3 volt device, the nano 33 iot does have a 5v pin. Ideally, you would use an I2C compatible level shifter between the nano 33 iot and the LCD screen.


text:
How can I display an image as a whole using ILI9488 and M0?
I'd like to display 4 random images out of 100 every day from the built in flash of my M0 microcontroller on my LCD (ILI9488).When I use DFRobot_GDL library "drawUDPicture" example, it only shows pictures line by line. I'm very new to coding. Can someone tell me what to add to the exmaple code to present 4 random images out of 100 and have the images appear right away and not line by line? Thank you so much!
#include <SD.h>
#include <SPI.h>
#include "DFRobot_GDL.h"
#include "DFRobot_Picdecoder_SD.h"

DFRobot_Picdecoder_SD decoder;

//Custom communication pins
/*M0*/

#define TFT_DC  7
#define TFT_CS  5
#define TFT_RST 6

DFRobot_ILI9488_320x480_DMA_SPI screen(/*dc=*/TFT_DC,/*cs=*/TFT_CS,/*rst=*/TFT_RST);

void setup()
{
  //Initialize the serial port
  SerialUSB.begin(115200);
  //Initialize screen
  screen.begin();
  //Initialize the SD card, wait until the initialization is successful
  while(1)
  {
    if (SD.begin())
    {
      SerialUSB.println("initialization done.");
      break;
    }
    SerialUSB.println("initialization failed!");
  }
}

//Store file name of the icon in the read directory
char str[32];

void loop()
{
  /* Set the screen color to white */
  screen.fillScreen(COLOR_RGB565_WHITE);

  decoder.drawPicture(/*filename=*/"picture/219x220.jpg",/*sx=*/0,/*sy=*/0,/*ex=*/screen.width(),/*ey=*/screen.height(),/*screenDrawPixel=*/screenDrawPixel);
  screen.fillScreen(COLOR_RGB565_WHITE);
  decoder.drawPicture(/*filename=*/"picture/RGB565.bmp",/*sx=*/0,/*sy=*/0,/*ex=*/screen.width(),/*ey=*/screen.height(),/*screenDrawPixel=*/screenDrawPixel);

}

//For decoding function calling, this function is used to draw a pixel on the screen
void screenDrawPixel(int16_t x, int16_t y, uint16_t color)
{
  //Draw a point on the screen
  screen.writePixel(x,y,color);
}

To speed things up, consider using a not-compressed image format that is compatible with the library you are using.  Also note that you are likely using a I2C serial device to store images and a serial device to display images.


text:
Arduino Bluepill STM32 spi doesn't work
Has anyone successfully use SPI1 of those pins?
SCLK -> PB3
SDIO -> PB5
SDO -> PB4
MISO CS -> PA15

I've tried to use another side of SPI1 pins on the other sides of the board (PA4, 5, 6, 7) and i can successfully communicate with

Arduino and STM32 Blue pill are not the same, they are different platforms. And you need to supply more details, like the complete code.

i used the stm32arduino core , so i will perform like arduino and the code is very simple just spi output to sensor its not responsing at all until i switch the pin it will work fine

It depends on how you use the SPI object. If you use the SPI object directly like what Arduino Uno without creating an instance object, the SPI construct will default to the PA4 - PA7, see the default pins definition and default Class construct of Blue Pill.
For STM32 Arduino Core (Stm32duino), there are four STM32 Arduino Core specific APIs for configure the alternative SPI pins.
void setMISO(uint32_t miso)
void setMOSI(uint32_t mosi)
void setSCLK(uint32_t sclk)
void setSSEL(uint32_t ssel)

These must be called before the SPI.begin().
Another alternative way of using the alternative SPI pins is to create an SPI object and pass-in the pin assignments like this:
#include <SPI.h>

SPIClass mySPI(PB5, PB4, PB3, PB15); //mosi, miso, sclk, ssel

See the alternative construct API, and further information on STM32duino wiki page.

Thank a lot , you had no idea how many hours i waste on this thing :)