text:
Analog Reference (AREF) pin on Arduino MKR1000 not working?
Has anyone successfully used the AREF pin on MKR1000?
I'm trying to use an EXTERNAL voltage reference (I need 1.5V instead of the default 5V) with:
analogReference(EXTERNAL)

But when I compile I receive the following error message:

MKR_001:161: error: invalid conversion from 'int' to 'eAnalogReference {aka _eAnalogReference}' [-fpermissive]

In the documentation (for analogReference) I found the following:

DEFAULT: the default analog reference of 5 volts (on 5V Arduino boards) or 3.3 volts (on 3.3V Arduino boards)
  INTERNAL: an built-in reference, equal to 1.1 volts on the ATmega168 or ATmega328 and 2.56 volts on the ATmega8 (not available on the Arduino Mega)
  INTERNAL1V1: a built-in 1.1V reference (Arduino Mega only)
  INTERNAL2V56: a built-in 2.56V reference (Arduino Mega only)
  EXTERNAL: the voltage applied to the AREF pin (0 to 5V only) is used as the reference.

Thanks,
Corrado

What doesn't work. What have you tried and in what way did it fail?

Please edit your question with this information and any more that you have. Also, try to make your question more specific.

Voted to reopen, you've edited the question and I think it's a very good question now.

The compiler error
MKR_001:161: error: invalid conversion from 'int' to 'eAnalogReference {aka _eAnalogReference}' [-fpermissive]

Is actually really simple once you understand what it means.
analogReference(EXTERNAL);

The function analogReference takes an integer as a parameter, but you are passing it EXTERNAL which is an enumeration.  Its probably an enumeration that uses integers for its values, but to the compiler there is a difference.
If you want to disable the warning then you can use the -fpermissive flag on the compile command line, this is not a good idea because it invalidates the "type-safeness" of the language for the whole program.  Instead it is better to address them on a case by case basis and just cast EXTERNAL to an int.
analogReference((int)EXTERNAL);

Interesting, it's somewhat a bug of the 'analogReference()' function to expect an int (could be much more than just one of the enum values)?

Its not a bug, its a feature :)
I think it stems from the tightening of implicit type conversion within the gcc compiler.  I knew it straight away, because I see it so often at work, dragging some legacy code into this century.   Someone could raise it as a fault and have it changed, but its not going to be a priority.

Well, yeah, if you keep it too long out there, people will go use integers to choose the reference. And then correcting it may break those peoples code again. But your answer is a very good one.

In fact, the documentation suggests that for SAMD boards (MKR1000 is based on Zero) a different enumeration should be used where each value is prefixed with AR_ so for example you should use analogReference(AR_EXTERNAL);.


text:
Built-in LED turns on when I touch the input port
I'm a beginner. I bought a new Arduino and I uploaded the basic example button code.
const int buttonPin = 2;
const int ledPin =  13;
int buttonState = 0;

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

void loop() {
  buttonState = digitalRead(buttonPin);
  if (buttonState == HIGH) {
    digitalWrite(ledPin, HIGH);
  } else {
    digitalWrite(ledPin, LOW);
  }
}

But the problem is that when I touch port 2 the output is getting so I changed the port number 2 to 3 even though without any supply the output is getting on.
Give me some suggestion.

Try pinMode(buttonPin, INPUT_PULLUP) and if (buttonState == LOW).... An input pin that is not connected is floating and touching it may give enough voltage to make it go HIGH.

Follow the basic Button tutorial: https://www.arduino.cc/en/Tutorial/Button

That's is to be expected if you leave the input floating.

When you are reading digital data through a pin you must make sure that you are steering that input pin to a stable state when no input is present.
You can do this by using either a pullup or a pulldown resistor which you can connect externally or you can use the in built pullup.
You can use a 10k ohm resistor to pulldown by connecting it to the button end where your digital pin is connected and the other to ground.
By doing this your above code must work fine.
I think by touching the pin you are actually pulling the voltage state down.
Hope this helps

source: Stack Exchange

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

sort: votes


text:
ENC28J60 is not getting ping
I bought a new ENC28J60 module and I tried to communicate with the PC through Arduino Uno board.
When I tried to ping the address that I gave in the program it's not getting the ping. Give me some solution.
I used the web server example that is in the example section of Arduino. I even turned off my firewall setting.
The code that I used is:
/*
  Web Server

 A simple web server that shows the value of the analog input pins.
 using an Arduino Wiznet Ethernet shield.

 Circuit:
 * Ethernet shield attached to pins 10, 11, 12, 13
 * Analog inputs attached to pins A0 through A5 (optional)

 created 18 Dec 2009
 by David A. Mellis
 modified 9 Apr 2012
 by Tom Igoe
 modified 02 Sept 2015
 by Arturo Guadalupi

 */

#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
};
IPAddress ip(192, 168, 1, 20);

// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip);
  server.begin();
  Serial.print("server is at ");
  Serial.println(Ethernet.localIP());
}

void loop() {
  // listen for incoming clients
  EthernetClient client = server.available();
  if (client) {
    Serial.println("new client");
    // an http request ends with a blank line
    boolean currentLineIsBlank = true;
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        Serial.write(c);
        // if you've gotten to the end of the line (received a newline
        // character) and the line is blank, the http request has ended,
        // so you can send a reply
        if (c == '\n' && currentLineIsBlank) {
          // send a standard http response header
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("Connection: close");  // the connection will be closed after completion of the response
          client.println("Refresh: 5");  // refresh the page automatically every 5 sec
          client.println();
          client.println("<!DOCTYPE HTML>");
          client.println("");
          // output the value of each analog input pin
          for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
            int sensorReading = analogRead(analogChannel);
            client.print("analog input ");
            client.print(analogChannel);
            client.print(" is ");
            client.print(sensorReading);
            client.println("
");
          }
          client.println("");
          break;
        }
        if (c == '\n') {
          // you're starting a new line
          currentLineIsBlank = true;
        } else if (c != '\r') {
          // you've gotten a character on the current line
          currentLineIsBlank = false;
        }
      }
    }
    // give the web browser time to receive the data
    delay(1);
    // close the connection:
    client.stop();
    Serial.println("client disconnected");
  }
}

"Give me some solution." Say please.

Use EtherCard library

since 2020 you can use my EthernetENC library

You have an ENC28J60 based module. Your code is for the Wiznet-based module. The two are not interchangeable.
See this: http://nathanhein.com/2013/02/getting-arduino-online-with-an-enc28j60/
Good luck.

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

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


text:
How to fade an LED in response to a sensor?
As the sensor "sees" an object nearby, it makes the LED go to full brightness and it remains like that for as long as the sensor keeps on sensing the object. Then, as soon as the sensor stops sensing it, the LED goes OFF instantly... and so on, endlessly. This part of the code works perfectly as it is right now.
MY PROBLEM:
I need all of this ON and OFF switching to happen with smooth PWM fades instead of with abrupt "instant ON" and "instant OFF" changes. I need to have a 1.5 seconds PWM fade-in of the LED from 0% to 100% as soon as the sensor gets activated; and then a 3.5 seconds fade-out as soon as the sensor stops sensing something nearby. As long as the sensor is activated, the LED needs to remain at full brightness. So, simply put: I need the LED to dim smoothly between the sensor's state-changes, instead of changing instantly in an abrupt manner.

Look at the Fade example sketch under Examples/Basics.

But i am not getting how to synchronize it with the sensor,, i want that as the sensor remains high the LED should remain high Fade in and vice versa

In the loop function, check the value of the sensor.  Based on that value set a goal for the led brightness of 0 or 255.  Maintain another variable for the current brightness, if the current brightness is not equal to the goal brightness, move it a little closer and do an analogWrite.  Put a delay at the bottom of the loop to make the fade transition more gradual (delay = time to go from 0 to 100 in milliseconds divided by 256).  The PWM will be 0..255 which corresponds to 0..100%.

This is the typical problem which calls for a finite state machine.
You create a “state” variable to keep track of the LED state, which can
be OFF, FADING_IN, ON or FADING_OUT. You also need another
variable to remember when you started the fade-in or the fade-out. I
would start the program some declarations like the following:
const uint8_t  LED_PIN       = 3;
const uint32_t FADE_IN_TIME  = 1500;
const uint32_t FADE_OUT_TIME = 3500;

static enum { OFF, FADING_IN, ON, FADING_OUT } led_state;
static uint32_t fade_start;

Now that you know the LED state, you use it to condition the LED
handling on the current state. For example, the brightness at any given
time can be computed as:
/* Compute the LED brightness after the given fade time */
static uint8_t led_brightness(uint32_t fade_time)
{
    int mapped;
    switch (led_state) {
        case FADING_IN:
            mapped = map(fade_time, 0, FADE_IN_TIME, 0, 255);
            return constrain(mapped, 0, 255);
        case FADING_OUT:
            mapped = map(fade_time, 0, FADE_OUT_TIME, 255, 0);
            return constrain(mapped, 0, 255);
        case ON:
            return 255;
        default:
            return 0;
    }
}

where fade_time would be millis() - fade_start. Note the use of the
standard map() function to generate a linear ramp, and constrain()
to avoid overflowing the range 0 – 255.
Now, switching the LED on or off is just a matter of setting the correct
state... and updating fade_start as necessary:
/* Set the LED pin to HIGH or LOW, through fading. */
void ledWrite(uint8_t value)
{
    uint32_t now = millis();
    if (value == HIGH) {
        if (led_state == OFF) {
            fade_start = now;
        }
        else if (led_state == FADING_OUT) {
            fade_start = now - map(now - fade_start,
                    0, FADE_OUT_TIME,
                    FADE_IN_TIME, 0);
        }
        if (led_state != ON)
            led_state = FADING_IN;
    }
    else {
        if (led_state == ON) {
            fade_start = now;
        }
        else if (led_state == FADING_IN) {
            fade_start = now - map(now - fade_start,
                    0, FADE_IN_TIME,
                    FADE_OUT_TIME, 0);
        }
        if (led_state != OFF)
            led_state = FADING_OUT;
    }
}

A few things worth noting:

trying to switch the LED on has no effect if it's already on or fading
in, and trying to switch it off has no effect if it's either off or
fading out
if you switch it on while it's fading out, it will move to the state
FADING_IN, and the fade_start time will be set to a value that
ensures continuity of the brightness; same thing when switching from
FADING_IN to FADING_OUT.

There is one more thing to do. Your program should periodically update
the LED state, not only to update its brightness, but also to enforce
the transitions FADING_IN → ON and FADING_OUT → OFF when needed:
/* This should be called periodically to update the LED. */
void update_led()
{
    uint32_t fade_time = millis() - fade_start;
    if (led_state == FADING_IN && fade_time >= FADE_IN_TIME)
        led_state = ON;
    else if (led_state == FADING_OUT && fade_time >= FADE_OUT_TIME)
        led_state = OFF;
    analogWrite(LED_PIN, led_brightness(fade_time));
}

With all this in place, you can write the main program just as you did
with no fading, only with the extra call to update_led() on every loop
iteration:
void setup()
{
    // Initialize the sensor.
    sensor.begin();
}

void loop()
{
    // Set the LED as per the sensor reading.
    if (sensor.detects_object())
        ledWrite(HIGH);
    else
        ledWrite(LOW);

    // Update the LED brightness on every loop iteration.
    update_led();
}

Oh, and beware not to do anything blocking in loop() (e.g., no calls
to delay()). Otherwise the LED brightness would be “jumpy”.

Do analogRead(sensor) and check what range of values you are getting. Arduino has 10 bit adc which means you can get 0-1023 in readings. However the sensor might not go complete LOW (0) or complete HIGH (1023). So just measure what's the range you are getting. Assume the range is 125 - 980.
PWM on arduino - This one is 8 bit, which means you can write 0-255. 0 means LED is OFF and 255 means LED is fully ON. Now you need to map 125-980 to 0-255 (as far as I can understand from your comments about synchronizing it with the sensor).
Here is what your code will look like:
/* Map an analog value (125-980) to 8 bits (0 to 255) */

    void loop()
    {
      int val = analogRead(0); //sensor attached to A0
      val = map(val, 125, 980, 0, 255);
      analogWrite(9, val); //LED attached to D9
    }

Thank you very much for your support this is what i tested and its working fine


text:
Can't get MMC3416xPJ to work
I needed a magnetometer with a high Output Data Rate (ODR). This is because I wanted to measure AC magnetic fields of around 20-80 Hz. So I decided to go with the MMC3416xPJ prototyping board which has an ODR of 800 Hz (https://au.mouser.com/new/memsic/memsic-mmc3416xpj-sensors/). I have never written an I2C interface for a sensor myself so I probably messed up. The datasheet for my sensor can be found here. I can get the product ID from the sensor correctly so that means the wiring is correct and some of the code is correct. But when I print out the measurements, they give me overflow values instead of the Earth's magnetic field. BTW I am developing this on Arduino board. Any help would be appreciated.
My code can be seen below -
Magnetometer.h

#ifndef MAGNETOMETER_H
#define MAGNETOMETER_H

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

#define MAGNETOMETER_I2C_ADDRESS 0x30
#define X_OUT_LOW 0x00
#define X_OUT_HIGH 0x01
#define Y_OUT_LOW 0x02
#define Y_OUT_HIGH 0x03
#define Z_OUT_LOW 0x04
#define Z_OUT_HIGH 0x05
#define STATUS 0x06
#define INTERNAL_CONTROL_0 0x07
#define INTERNAL_CONTROL_1 0x08
#define RO 0x1b
#define R1 0x1c
#define R2 0x1d
#define R3 0x1e
#define R4 0x1f
#define PRODUCT_ID 0x20

class Magnetometer
{
  public:
    Magnetometer();
    void Setup();
    void Test();
  private:
    void TestConnnection();
    void ReadRawData();
};

#endif

Magnetometer.cpp
#include "Magnetometer.h"

Magnetometer::Magnetometer()
{

}

void Magnetometer::Setup()
{
    Wire.begin(SDA, SCL);
    TestConnnection();

    Wire.beginTransmission(MAGNETOMETER_I2C_ADDRESS);
    Wire.write(INTERNAL_CONTROL_1);
    Wire.write(0x00);
    Wire.endTransmission();

    Serial.println("Magnetometer Setup");
}

void Magnetometer::Test()
{
    ReadRawData();
    Serial.println("Magnetometer Test");
    delay(1000);
}

void Magnetometer::ReadRawData()
{
    int16_t RawMx, RawMy, RawMz;
    byte status = -1;

    // 1-3
    Wire.beginTransmission(MAGNETOMETER_I2C_ADDRESS);
    Wire.write(INTERNAL_CONTROL_0);
    Wire.write(0x01);
    Wire.endTransmission();

    // 4-7
    Wire.beginTransmission(MAGNETOMETER_I2C_ADDRESS);
    Wire.write(STATUS);
    Wire.requestFrom(MAGNETOMETER_I2C_ADDRESS, 1);
    status = Wire.read();
    Serial.print("status = "); Serial.println(status);
    while ((status%2) != 1)
    {
        status = Wire.read();
        Serial.println("Data not ready");
    }
    Serial.println("Data ready");
    Wire.endTransmission();

    // 8-17
    Wire.beginTransmission(MAGNETOMETER_I2C_ADDRESS);
    Wire.write(X_OUT_LOW);
    Wire.endTransmission();
    Wire.requestFrom(MAGNETOMETER_I2C_ADDRESS, 6);
    RawMx = Wire.read();
    RawMx |= Wire.read()<<8;
    RawMy = Wire.read();
    RawMy |= Wire.read()<<8;
    RawMz = Wire.read();
    RawMz |= Wire.read()<<8;

    Serial.print("RawMx: "); Serial.print(RawMx);
    Serial.print(" RawMy: "); Serial.print(RawMy);
    Serial.print(" RawMz: "); Serial.println(RawMz);

    float scaleFactor = 2048;
    float convertToMircoTelsa = 100;
    float Mx, My, Mz;

    Mx = (float) RawMx / scaleFactor * convertToMircoTelsa;
    My = (float) RawMy / scaleFactor * convertToMircoTelsa;
    Mz = (float) RawMz / scaleFactor * convertToMircoTelsa;

    Serial.print("Mx: "); Serial.print(Mx);
    Serial.print(" My: "); Serial.print(My);
    Serial.print(" Mz: "); Serial.println(Mz);

    // Serial.print("Wire.ava = "); Serial.println(Wire.available());
}

void Magnetometer::TestConnnection()
{
    byte id = -1;
    while (id != 6)
    {
        Wire.beginTransmission(MAGNETOMETER_I2C_ADDRESS);
        Wire.write(PRODUCT_ID);
        Wire.requestFrom(MAGNETOMETER_I2C_ADDRESS, 1);
        id = Wire.read();
        Wire.endTransmission();

        if (id != -1)
        {
            Serial.println("Cannot connect to Magnetometer");
        }
    }
    Serial.println("Magnetometer TestConnnection Success");
}

If you guys suggest me any other magnetometers that have a high ODR (at least above 300 Hz), it would be really appreciated.

Add print-out when you run the sketch. What are the raw values?

That is not fast, that is slow, because the I2C bus is slow and the Wire.endTransmission and Wire.requestFrom are blocking functions, they wait until everything has finished. You might use Wire.setClock to set the bus to 400kHz, but a magnetometer with SPI interface avoids all these problems. Which arduino board do you use ? I see a few mistakes with the Wire functions, you have to read in the Arduino Wire reference how to use them.

@MikaelPatel I get overflow values

@Jot I am using a Wemos D1 mini which based on the Esp8266. Can you give me pointers on the mistakes I made? Thanks in advance.

@Jot Do you know where I can find a magnetometer which has an odr of above 300 Hz and uses SPI for data transfer?

The wire.endtransmission is used when writing data: https://www.arduino.cc/en/Reference/WireEndTransmission The LIS3MDL is used with arduino and has spi and i2c and 1kHz in fast_odr mode. The LSM9DS1 is also often used with arduino, has also spi and i2c and is 952Hz. I don't know if the internal circuit is also that fast, that speed is just the interface.

Perhaps a set/reset before configuring the device helps:
writeRegister(MMC34160PJ_CTRL0, 0x80);          // refill cap
delay(50);
writeRegister(MMC34160PJ_CTRL0, 0x20);          // set
//delay(10);
writeRegister(MMC34160PJ_CTRL0, 0x80);          // refill cap
delay(50);
writeRegister(MMC34160PJ_CTRL0, 0x40);          // reset
//delay(10);

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


text:
Is this the right way of using an RF communication?
I have a 433Mhz Superheterodyne receiver and a hand set remote of similar frequency, I'm using the RC-Switch library and I couldn't find a better way than using the "numbers" that I'm receiving like this:

#include <RCSwitch.h>

RCSwitch mySwitch = RCSwitch();

void setup() {
  Serial.begin(9600);
  mySwitch.enableReceive(0);  // Receiver on interrupt 0 => that is pin #2
  pinMode(13, OUTPUT);
}

void loop() {
  if (mySwitch.getReceivedValue() == 7264305) {
    digitalWrite(13, LOW);
  }
  if (mySwitch.getReceivedValue() == 7264308) {
    digitalWrite(13, HIGH);
  }
  if (mySwitch.getReceivedValue() == 7264306) {
    mySwitch.resetAvailable();
  }
}

Is there any other (better?) way than just using the "numbers" simply like that or everyone are using their remote commands like I'm using?

all data is just numbers ... your transmission data appear to be 24 bits long ... for example decimal 7264305 translates to 24 bit binary 011011101101100000110001, which can be described in hexadecimal as 6ED831 .... some of the bits are the switch states and the rest are probably a predetermined filler that could be used to check the validity of the transmission or they may be the address of the transmitter

for the received values of 7264305, 7264306 and 7264308, the last 4 bits of the received data are 0001, 0010 and 0100 respectively

Credits for this answer are mainly for jsotola (see his remarks above). But I want to show an alternative to the if statements, and a way to get the last 4 bits:

In case you want to check for the least significant bits, use ((mySwitch.getReceivedValue() & 0xFFFFF0)
TO check for the least significant four bits (the data you want to act upon), use ((mySwitch.getReceivedValue() & 0xF)
Use a switch statement instead of the if statement; also in theory (I don't know the code of mySwitch.getReceivedValue() does not need to be executed multiple times.

So you get something like this:
void loop()
{
  unsigned long receivedValue = mySwitch.getReceivedValue(); // Call function only once

  if ((receivedValue & 0xFFFF0) == 0x6ED830)
  {
    // Process action
    switch (receivedValue & 0xF)
    {
    case 0x5:
      digitalWrite(13, LOW);
      break;

    case 0x8:
      digitalWrite(13, HIGH);
      break;

    case 0x6:
      mySwitch.resetAvailable();
      break;

    default: // All other values
      break; // Ignore
  }
}


text:
Data type conversion problem
I have a Wemos D1 board with a OLED display using the u8g2 library.
I am printing my MAC-adress on the serial port & would like to print the same information on the OLED:

#include <ESP8266WiFi.h>
#include <U8g2lib.h>
byte mac[6];
setup(){
  Serial.println(WiFi.macAddress());
  WiFi.macAddress(mac);
  u8g2.drawStr(1,10,WiFi.macAddress());
  u8g2.sendBuffer();
}

This does not work. It prints the MAC-address on the serial port but not on the OLED.
I get: no known conversion for argument 3 from 'String' to 'const char*
How can I print the MAC-information on my oled using the u8g2-library?

Hint: WiFi.macAddress().c_str() https://www.arduino.cc/reference/en/language/variables/data-types/string/functions/c_str/

As said by @Mikael Patel
You need to append .c_str() to u8g2.drawStr(1,10,WiFi.macAddress()); creating the line: u8g2.drawStr(1,10,WiFi.macAddress().c_str());
The problem is that WiFi.macAddress() returns a String not the needed const char* by the drawStr function. c_str converts the String object into a const char*.
Please look at the documentation of the u8g2 library for the drawStr function.
link
And here the documentation for String
link


text:
There's an error I don't know how to fix
I basically have a bread board with an rgb led and a peizo buzzer with a photocell.
I have the codes for both. If I put a code for the rgb, it works. If I put the code for the peizo, it works. Once I paste both codes onto it it says there's an error because "void setup" and "void loop" are already defined. What do I do to get both things to work?
rgb led code:
/*
Adafruit Arduino - Lesson 7. RGB Fader
*/
int redLEDPin = 11;
int greenLEDPin = 10;
int blueLEDPin = 9;
int redSwitchPin = 7;
int greenSwitchPin = 6;
int blueSwitchPin = 5;
int red = 0;
int blue = 0;
int green = 0;

void setup()
{
  pinMode(redLEDPin, OUTPUT);
  pinMode(greenLEDPin, OUTPUT);
  pinMode(blueLEDPin, OUTPUT);
  pinMode(redSwitchPin, INPUT_PULLUP);
  pinMode(greenSwitchPin, INPUT_PULLUP);
  pinMode(blueSwitchPin, INPUT_PULLUP);
}

void loop()
{
  if (digitalRead(redSwitchPin) == LOW)
  {
    red ++;
    if (red > 255) red = 0;
  }
  if (digitalRead(greenSwitchPin) == LOW)
  {
    green ++;
    if (green > 255) green = 0;
  }
  if (digitalRead(blueSwitchPin) == LOW)
  {
    blue ++;
    if (blue > 255) blue = 0;
  }
  analogWrite(redLEDPin, red);
  analogWrite(greenLEDPin, green);
  analogWrite(blueLEDPin, blue);
  delay(10);
}

peizo code:
int speakerPin = 12;
int photocellPin = 0;

void setup()
{
}

void loop()
{
  int reading = analogRead(photocellPin);
  int pitch = 200 + reading / 4;
  tone(speakerPin, pitch);
}

you can have only one setup() block and only one loop() block .... you have to merge the code from each pair of the blocks into one block

Putting all other possible issues aside such as pin and timing conflicts.
Rename the sketch setup() and loop() functions, for instance, rgb_led_setup() and rgb_led_loop(), and peizo_setup() and peizo_loop(), then rewrite:
void setup() {
  rgb_led_setup();
  peizo_setup();
}

void loop() {
  rgb_led_loop();
  peizo_loop();
}

Cheers!


text:
Powering via an I/O Line
I have an SPI 128x64 OLED display. Is it safe to power this display's VCC from a digital I/O pin? I would like to do this so I can connect it flush to my arduino's header, and so I can control the power going to the display for a "low power" sleep mode.
Thanks for any responses.

Unlikely. An IO pin can only provide 25mA sustained, and 40mA peak. A display is likely to require more than that. However check the datasheet for the display. If by chance it should not need more than 25mA maximum (all pixels white) then yes it may be possible.


text:
Using analog in to read a push button
I'm working on a project in which I use a lot of the pins on the Arduino;  I have run out of most of the pins and and I need to read the value of a push button.
Is it possible to read the value of the switch in the analog in pins on the board??
If so how can I implement this?

Is it possible to read the value of the switch in the analog in pins on the board??

Yes. Analog input pins are also digital IO pins. You can use them exactly the same way as all the other pins on the board.

e.g. digitalRead(A1)

On ATmega640/ATmega1280/ATmega1281/ATmega2560/ATmega2561 devices (with Arduino Mega using an ATmega640 or 2560), the analog input pins have their analog capabilities in addition to standard digital capabilities.  They can be used to read or write digital values, like other digital pins on the device.
On ATmega48A/PA/88A/PA/168A/PA/328/P devices (with Arduino Uno using an ATmega168- or 328-family device) analog inputs A0 ... A5 have standard digital capabilities, but A6 and A7 do not.  A6 and A7 on an Uno or Nano is limited to analog input.  However, you can use a circuit like the following to multiplex several buttons.  With this circuit attached to A6,  you would get 1 V at A6 when you press S1; 2 V when you press S2; 3 V when you press S3; and so forth.  You get 0 V at A6 when all the switches are open.

One would first use a fast analog read (about 13 μs) to decide if any switch is pressed; for example, if the first reading is above 1/2 V.  In some systems, a fast reading may be good enough by itself to decode switch number; if not, take a second reading via ordinary analog read.  In any case, given an analog reading ar, and letting CPS be the expected step in counts from one switch to the next (in this case either 256/5 or 1024/5 depending upon use of 8 or 10 bits of readings), compute switch number via something like s = (ar+CPS/2)/CPS;.

Is it possible to read the value of the switch in the analog in pins
  on the board??

As other answers say, you can use digitalRead on most Analogue pins.  But to answer the question, yes you can read analogue input, which is useful on pins like A6/A7 which cannot be used as digital pins.
You should connect the pin with a pull up resistor - for arduino pins A0-A5 (depending on board, i'm referring to a Nano) this can be done internally using:
pinMode(5, INPUT_PULLUP); // Enable internal pull-up resistor on pin 5

If you are working on pins A6/A7 you cannot access the internal pull-up resistor, so you need to add your own to prevent a floating input.  A 10K resistor should go between the input pin and VCC.
Lastly, an example of reading the input:
const int buttonPin = A7;     // the number of the pushbutton pin
const int ledPin =  13;      // the number of the LED pin

void loop() {
  // read the state of the pushbutton value:
  buttonState = analogRead(buttonPin);

  Serial.println(buttonState);

  // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
  if (buttonState > 512) {
    // turn LED on:
    digitalWrite(ledPin, HIGH);
  } else {
    // turn LED off:
    digitalWrite(ledPin, LOW);
  }
}

Same things happens with me.
Here, it's my code. It's works for me.
const int kPinBtn = A0;  // Push-Button connected to Analog pin A0
const int kPinLED = 13;  // LED connected to to Digital Pin 13

void setup()
{
  pinMode(kPinBtn, OUTPUT); // Generally, in push-button we take INPUT as a parameter but here we take OUTPUT because ANALOG PIN

  digitalWrite(kPinBtn, HIGH); // Make button condition HIGH

  pinMode(kPinLED, OUPUT);
}

void loop()
{
  // Now, normal push-button operation, LED blink when we press push button

  if(digitalRead(kPinBtn) == LOW)  // If button pressed
  {
    digitalWrite(kPinLED, HIGH);   // Blink LED
  }
  else digitalWrite(kPinLED, LOW); // Else LED is off
}


text:
Time displays on serial monitor but not my LCD
#include <TimeLib.h>
#include <Wire.h>
#include <DS1307RTC.h>  // a basic DS1307 library that returns time as a time_t

#define PIN_SCE   7
#define PIN_RESET 6
#define PIN_DC    5
#define PIN_SDIN  11
#define PIN_SCLK  13

#define LCD_COMMAND    LOW
#define LCD_DATA     HIGH

#define LCD_X     84
#define LCD_Y     48

String now_time;
char printTime;

void gotoXY(int x, int y) {
  LCDWrite(0, 0x80 | x);  // Column.
  LCDWrite(0, 0x40 | y);  // Row.  ?
}

//This takes a large array of bits and sends them to the LCD
void LCDBitmap(char my_array[]){
  for (int index = 0 ; index < (LCD_X * LCD_Y / 8) ; index++)
    LCDWrite(LCD_DATA, my_array[index]);
}

//This function takes in a character, looks it up in the font table/array
//And writes it to the screen
//Each character is 8 bits tall and 5 bits wide. We pad one blank column of
//pixels on each side of the character for readability.
void LCDCharacter(char character) {
  LCDWrite(LCD_DATA, 0x00); //Blank vertical line padding

  for (int index = 0 ; index < 5 ; index++)
    LCDWrite(LCD_DATA, ASCII[character - 0x20][index]);
    //0x20 is the ASCII character for Space (' '). The font table starts with this character

  LCDWrite(LCD_DATA, 0x00); //Blank vertical line padding
}

//Given a string of characters, one by one is passed to the LCD
void LCDString(char *characters) {
  while (*characters)
    LCDCharacter(*characters++);
}

//Clears the LCD by writing zeros to the entire screen
void LCDClear(void) {
  for (int index = 0 ; index < (LCD_X * LCD_Y / 8) ; index++)
    LCDWrite(LCD_DATA, 0x00);

  gotoXY(0, 0); //After we clear the display, return to the home position
}

//This sends the magical commands to the PCD8544
void LCDInit(void) {

  //Configure control pins
  pinMode(PIN_SCE, OUTPUT);
  pinMode(PIN_RESET, OUTPUT);
  pinMode(PIN_DC, OUTPUT);
  pinMode(PIN_SDIN, OUTPUT);
  pinMode(PIN_SCLK, OUTPUT);

  //Reset the LCD to a known state
  digitalWrite(PIN_RESET, LOW);
  digitalWrite(PIN_RESET, HIGH);

  LCDWrite(LCD_COMMAND, 0x21); //Tell LCD that extended commands follow
  LCDWrite(LCD_COMMAND, 0xAF); //Set LCD Vop (Contrast): Try 0xB1(good @ 3.3V) or 0xBF if your display is too dark
  LCDWrite(LCD_COMMAND, 0x04); //Set Temp coefficent
  LCDWrite(LCD_COMMAND, 0x14); //LCD bias mode 1:48: Try 0x13 or 0x14

  LCDWrite(LCD_COMMAND, 0x20); //We must send 0x20 before modifying the display control mode
  LCDWrite(LCD_COMMAND, 0x0C); //Set display control, normal mode. 0x0D for inverse
}

//There are two memory banks in the LCD, data/RAM and commands. This
//function sets the DC pin high or low depending, and then sends
//the data byte
void LCDWrite(byte data_or_command, byte data) {
  digitalWrite(PIN_DC, data_or_command); //Tell the LCD that we are writing either to data or a command

  //Send the data
  digitalWrite(PIN_SCE, LOW);
  shiftOut(PIN_SDIN, PIN_SCLK, MSBFIRST, data);
  digitalWrite(PIN_SCE, HIGH);
}

void setup(void) {
   LCDInit();
   LCDClear();
   Serial.begin(9600);
   while (!Serial) ; // Needed for Leonardo only
   setSyncProvider(RTC.get);   // the function to get the time from the RTC
   if (timeStatus() != timeSet)
     Serial.println("Unable to sync with the RTC");
   else{
     Serial.println("RTC has set the system time");
      digitalClockDisplay();
   }
}

void loop(void) {
  if(timeStatus() == timeSet)
  {
    delay(1000);
    digitalClockDisplay();
  }
}
void digitalClockDisplay(){
  // digital clock display of the time
  if(minute() < 10)
  {
    now_time = String(hour()) + ":0" + String(minute());
  }
  else if(minute() >= 10){
    now_time = String(hour()) + ":" + String(minute());
  }
  Serial.println(now_time);
   LCDClear();
   LCDString("Time: ");
   for(int i = 0; i <= now_time.length()-1; i++)
   {
      printTime = now_time.charAt(i);
      LCDString(printTime);
   }

}

void printDigits(int digits){
  // utility function for digital clock display: prints preceding colon and leading 0
  LCDString(":");
  if(digits < 10)
    LCDString('0');
  LCDString(digits);
}

When I run the code the time will display perfectly on the Serial Monitor but when I connect it to my Nokia LCD screen the words "Time: " will appear along with some random characters. Anyone know why this is?

LCDString expects a c-string not a single character.

I assume you are writing now_time one Char at a time because the LCD library does not accept the String object as input? LCDString assumes you will pass a C-style string -- that is a pointer to an array of char. When you pass in one character, it's not a pointer to a C-style string, but the LCDString function is assuming that it's a pointer to some bit of memory elsewhere.
Try not sending one Char at a time, but:
LCDString(now_time.c_str());

authors: Кирилл Немынов


text:
GY91 IMU module, Interrupt?
Are there interrupt Pin in the GY91 Module?
If not, are there good alternative for periodic sensor reading?
(apart from mcu schedule/external timer)

No. The INT pin of the MPU-9250 is not presented on the IO header of the GY-91.
The only way of knowing what is going on inside the MPU-9250 at any time is to go and look. I.e., periodic polling of the sensor.
If you want to use the interrupt pin you will have to shop around for a different module that gives you access to that pin.


text:
Undefined reference to Class::function()
I have three files:

main.cpp
RotaryEncoder.h
RotaryEncoder.cpp

Note that the RotaryEncoder class acts as a wrapper to the Encoder library. I am getting the following build report and I haven't been able to find the bug for the past couple days:
Build output from PlatformIO on VS Code
Processing uno (platform: atmelavr; board: uno; framework: arduino)
--------------------------------------------------------------------------------------------------------------------------------------------------------------------
Verbose mode can be enabled via `-v, --verbose` option
CONFIGURATION: https://docs.platformio.org/page/boards/atmelavr/uno.html
PLATFORM: Atmel AVR 1.15.0 > Arduino Uno
HARDWARE: ATMEGA328P 16MHz, 2KB RAM, 31.50KB Flash
PACKAGES: toolchain-atmelavr 1.50400.190710 (5.4.0), framework-arduinoavr 4.1.2
LDF: Library Dependency Finder
LDF Modes: Finder ~ chain, Compatibility ~ soft
Found 7 compatible libraries
Scanning dependencies...
Dependency Graph
|-- <Encoder>
Building in release mode
Compiling .pio/build/uno/src/main.cpp.o
Linking .pio/build/uno/firmware.elf
/var/folders/t1/fyh283nd1m7dxbrjlkjtf_kc0000gn/T//ccZN56Tq.ltrans0.ltrans.o: In function `main':
<artificial>:(.text.startup+0x2dc): undefined reference to `RotaryEncoder::getCount()'
collect2: error: ld returned 1 exit status
*** [.pio/build/uno/firmware.elf] Error 1

Explicit Error

In function 'main':
  :(.text.startup+0x2dc): undefined reference to 'RotaryEncoder::getCount()'.

main.cpp
#include <Arduino.h>
#include "RotaryEncoder.h"

#define cartEncoderPhaseA 3
#define cartEncoderPhaseB 4
#define pendulumEncoderPhaseA 2
#define pendulumEncoderPhaseB 5

// Initialize encoders
const double ENCODER_PPR = 2400.0;
RotaryEncoder cartEncoder(cartEncoderPhaseA, cartEncoderPhaseB, ENCODER_PPR);
RotaryEncoder pendulumEncoder(pendulumEncoderPhaseA, pendulumEncoderPhaseB, ENCODER_PPR);

void setup()
{
  Serial.begin(9400);
}

void loop()
{
  long cartCount = cartEncoder.getCount();
}

RotaryEncoder.h
#pragma once

#include <Encoder.h>

class RotaryEncoder
{
private:
    Encoder encoder;
    double encoderPPR;
    double angleLowerBound;
    double angleUpperBound;

    double convertEncoderCountToRadians(long encoderCount);
    double normalizeAngle(double angle);

public:
    RotaryEncoder(int phaseA, int phaseB, double encoderPPR);
    long getCount();
    double getRadiansAndOffsetBy(double angleOffset);
    void setAngleLowerAndUpperBounds(double lowerBound, double upperBound);
};

RotaryEncoder.cpp
#include "RotaryEncoder.h"

RotaryEncoder::RotaryEncoder(int phaseA, int phaseB, double encoderPPR)
: encoder(phaseA, phaseB), encoderPPR(encoderPPR)
{}

inline long RotaryEncoder::getCount()
{
    return encoder.read();
}

inline double RotaryEncoder::getRadiansAndOffsetBy(double angleOffset)
{
    long encoderCount = getCount();
    double angleInRadians = angleOffset + convertEncoderCountToRadians(encoderCount);
    angleInRadians = normalizeAngle(angleInRadians);

    return angleInRadians;
}

inline double RotaryEncoder::convertEncoderCountToRadians(long encoderCount)
{
    return ((double)encoderCount / (encoderPPR)) * (2.0 * PI);
}

inline double RotaryEncoder::normalizeAngle(double angle)
{
    // Constrain an angle between [-pi, pi). Output is in radians
    // see: https://stackoverflow.com/questions/11498169/dealing-with-angle-wrap-in-c-code

    angle = fmod(angle + PI, 2 * PI);

    if (angle < 0)
        angle += 2 * PI;

    return angle - PI;
}

inline void RotaryEncoder::setAngleLowerAndUpperBounds(double lowerBound, double upperBound)
{
    angleLowerBound = lowerBound;
    angleUpperBound = upperBound;
}

Have you tried it without inlines? It's kinda pointless to have inline modifier in cpp file as it's compiled into RotaryEncoder.o and everything else is compiled separately and won't see any inline...

@KIIV Thank you so much, that worked. I didn't even think of that being the issue. If you want to post as an answer I will accept it

The inline modifier doesn't make a sense for methods definitions in separate cpp file. And obviously it makes the code compilable but methods aren't recognized as methods definitions and also it's not recognized as error (that's kinda weird).
Anyway, if you wan't inline methods, do it directly inside of class definition.


text:
What is the format specifier for string in arduino
I have a string formattedDate.
When I am trying to give sprintf(payload,"{\"timestamp\":\"%s\",\"temperature\":%f,\"humidity\":%f}",formattedDate,t,h);
Its not printing the date and time.

Are you certain that formattedDate contains data?

is formattedDate a String? then use formattedDate.c_str()

When I use this I am able to print date and time --> Serial.println(formattedDate);

Actually, I am trying to send DHT11 data to AWS cloud. I am able to send temperature and humidity. I want time also to get imported for visualization. I am using NTP for date and time, so included the NTP libraries and this is working --> formattedDate = timeClient.getFormattedDate();
Serial.println(formattedDate);  --> But i want it to print in JSON format. So I am printing like this sprintf(payload,"{"timestamp":%s,"temperature":%f,"humidity":%f}",formattedDate,t,h); But here i am unable to print date and time some random boxes and question marks are being printed.

println has a version for String sprintf doesn't

Can you please give me an idea to print the formatted date in JSON format so that I can visualise the data in quicksight

read my first comment


text:
Ethernet.begin() conflicts with build-in LED on Arduino Nano
I have Arduino Nano "clone" which I would like to use with Ethernet ENC28J60 shield. I have noticed that when I include/use UIPEthernet.h library, build-in LED does not work properly. I have written the following sketch which I have uploaded to Arduino and run both with and without Ethernet shield with the same result: LED is not blinking. Once I comment out the line Ethernet.begin(mac), LED starts blinking just fine.
Is there any way to overcome this conflict?
#include <UIPEthernet.h>

EthernetClient ethClient;

uint8_t mac[6] = { 0x90, 0xA2, 0xDA, 0x0D, 0xE2, 0xCD };

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

  // If this line is commented, LED starts blinking:
  Ethernet.begin(mac);

  pinMode(LED_BUILTIN, OUTPUT);

  Serial.println(F("setup() done."));
}

void loop() {
  digitalWrite(LED_BUILTIN, HIGH);
  delay(1000);
  digitalWrite(LED_BUILTIN, LOW);
  delay(1000);
}

No, you can't.
The LED is on pin 13. Pin 13 is the clock pin for SPI. The ENC28J60 is an SPI device.
You either have control over pin 13, or you have SPI. You can't have both.

Thanks for this information! Good to know that. Probably there is some way to "stop" Ethernet and start using LED? Unfortunately, I found no Ethernet.stop() or similar.


text:
Powering Motor shield and Arduino Mega Separately
I'm trying to build a fire fighting robot, that uses 2 BO DC motors, 2 Servos - MG996R and SG90. For them I'm using Motor Shield v1 of Adafruit's make that uses 2 L293D IC's and a 74HC595 shift registers.
Now, I'm placing the motor shield over Arduino Mega and trying to connect other components such as Flame Sensor, Ultrasonic Sensor and submersible DC Water Pump.
As soon as I try to power up ultrasonic sensor, the power indicating LED's on both the shield and Mega goes off.
I've been testing this with simple USB connected power supply and to my understanding the power being supplied is insufficient.
Since it would be a moving cart, I would like to know whether there is any way to power up Shield and Mega separately by a 9v Battery?

On the side of the DC Motor Shield v1, there is an external power - +  2 pin terminal.
This can be used to supplement the shield with power.
Adafruit: "The motor controllers on this shield are designed to run from 4.5V to 25V.
MOST 1.5-3V MOTORS WILL NOT WORK"
If you are lucky to have the motor specs and ratings on hand, you will be able to account for how much power your motor(s) will need in your application.
Adafruit: "The motor driver chips that come with the kit are designed to provide up to 600 mA per motor, with 1.2A peak current. Note that once you head towards 1A you'll probably want to put a heatsink on the motor driver, otherwise you will get thermal failure, possibly burning out the chip."
Here is an important tid-bit for your scenario... (So no 9v Batteries for the motors!):
Adafruit: "You can't run motors off of a 9V battery so don't even waste your time/batteries! Use a big Lead Acid or NiMH battery pack. Its also very much suggested that you set up two power supplies (split supply) one for the Arduino and one for the motors. 99% of 'weird motor problems' are due to noise on the power line from sharing power supplies and/or not having a powerful enough supply!"
...
So makes sense,  get the Arduino powered, by itself, then get another power source for your motor shield.
Your sensors might be able to hop on the Arduino power supply if it's providing enough power.  I'd keep them separate from the motor power line, due to noise interference as suggested.
Try this, and see if the Arduino stays powered.
There is a lot of helpful info here, some new things I've learned just now.
https://learn.adafruit.com/adafruit-motor-shield/power-requirements


text:
Starting DC Pump with Arduinowhen it is powered by 9v Battery
I'm using Arduino Mega, and would like to start a DC Motor Pump. In my circuit, there are several sensors that are going to take up the voltage offered by Mega.
Hence, I would like to know whether there is a way to control the working (start/stop) of the pump using arduino as the controller while the motor being powered by a 9V battery.

use a relay to turn the power on off.  This gives you control over the pump, as well as isolates it from the micro-controller

A 9V battery doesn't give very much current and doesn't give any for very long.  They're usually not good for motors.  Generally AA or AAA would be better.

Thanks, So is there any way to reduce the complexity of the circuit as we don't have space for the relay module! We simply need a switch that gets ON upon Arduino's signal

How strong is your pump? An optocoppler or a simple transistor are smaller alternatives.

Thanks, its of 3.3V. I've connected it to my accessible motor driver shield of Adafruit v1. Hence I am able to switch it on or off just as any other DC Motor!!.


text:
C# Arduino: How to detect if the needed software is present on the computer
I have a digispark that uses trinket keyboard library to send media keys back to the computer using a rotary encoder. I currently have it configured to send normal media keys but about 2 weeks ago i started needing to change binds on what the rotary encoder does so i needed a driver of some sort. i asked and i got answers that i can't use serial ports but i can use unused keys like f13+ keys so i use the f keys now to communicate to c# software (it listens on these f keys and as soon as they are pressed depending on the configuration it does what it needs to do).
I don't think that code is needed for this demonstration but if u need it i'll be happy to edit this.
So i made the software and now comes a problem of what happens when u plug in the device that doesn't have the driver. its useless, so i need a way for the digispark to find out if there is a software that can "reprogram" what the rotary encoder does and if there isn't use the default functions(the media keys).
Questions:

How would i go about finding out if there is the needed driver on that computer where the digispark is plugged in
Is there any way to add my program made in c# to the digispark, i got a usb headset and when i first plugged it in it installed its driver, so when i plug in my digispark can it load the program

Solutions that i think may work but i have no idea how to do them:

using one of these unused keys as Boolean, when its held down lets say by the c# software can the digispark using the trinket or any other compatible Tiny85 library determine if that key is pressed down or not (this may interfere with other software so i don't think its perfect solution)
If anyone here knows any library or custom firmware that allows the digispark(Tiny85) to communicate on serial ports that'd be pretty useful and would solve the whole question.

For the second problem: do i need any other hardware to do this as i only have a Tiny85 digispark and a rotary encoder with a breakout board
If you have a solution please provide me code or links where i may learn how to do this because as of now i have no idea how to do this, i know my way around c# but i'm a noob in arduino programming. I already asked this on stack overflow a week ago but didn't get any comments or answers. I'm sorry if this counts as a duplicate i'll remove the one on stack overflow if needed. thank you for understanding

A usb device can’t check if a key is pressed. What you might be able to check is the status of the capslock key. So my proposed solution would be. On powerup have the digispark send a F17-key press. Then have the c# respond by Turing the capslock on for e.g. 1 second. The digispark will check if the capslock was on for a brief moment, and if so, will know that the C# program is active. (Note that you need a slightly different solution if digispark is already  connected before the pc is turned on)

@Gerben Can it also be done with the scrool lock as i dont find myself using it very often and the problem where your pc isnt loaded can be fixed either by adding a delay on startup like 20 secs to allow the pc and program to start up, or put it in a loop and add a boolean to stop checking everytime it loops if it finds the software

scrolllock would indeed be better.

How big is your software installation package?

And why are you so fixated on such an unsuitable MCU for complex USB work?

you use too many words to ask a question about emulating a USB keyboard using a digispark .... the rotary encoder is not really related to your question ... open another question for the rotary encoder, if you have to  .....  simplify the question text and you may get an answer from more people

@jsotola some people may need the explaining for what keys are sent and received by the program

it is irrelevant what the key presses are for .... the receiving program is also irrelevant ... the question is how to create a keyboard  .... you are losing sight of what you are actually having a problem with

How would i go about finding out if there is the needed driver on that computer where the digispark is plugged in

I can't think of any way to do that. That's like asking if a keyboard you plug into a USB port can tell if you have Photoshop installed or not.

Is there any way to add my program made in c# to the digispark ...

No. The Digispark is a tiny computer based on the Attiny85 which has 8k of program memory, some of which is dedicated to a bootloader which lets you upload new code.

Your project is far too ambitious for the level of hardware you are proposing to use. In fact this video which I watched the other day comes to mind:
https://www.youtube.com/watch?v=s7AXskSxxMk

From a comment:

the it refers to the digispark, when connected the digispark checks if the f17 key is pressed down and if it is that means my program is running in the background so use the functions that are compatible with the program

OK, so you want the host computer (not the Digispark) to pretend it is holding down F17, and then when the Digispark is plugged in it checks if F17 is down, and if so it knows that the desired program is running on the PC. Is that your idea?
The problem here is that the Digispark is a USB device (not a USB host). I suppose it would be possible to write a special device driver on the PC that, once the Digispark connects, would send some special code to say whether or not the program is running. However with the Digispark only having 8 KB of program memory, this extra code (on the Digispark) might be hard to fit in. Plus you would need to write your USB device driver. Plus the device driver would need to be able to query what programs are running.
I think a far simpler solution would be to have an On/Off button on the Digispark. If you plug it into a PC which has this special program running you press the button, then the Digispark sends the alternative commands to your C# program.

First of all i clearly stated that the digispark doesn't have serial so i use one of the unused keys, let's say f17 as a boolean. my c# program holds it down so when the digispark connects it should check if f17 is held down or not, if it's not it should default to volume control and if it is held down it should be f13 and f14 for the rotary encoder rotation(this is already done). i need a way to find if that key is pressed and act according to that. for the second thing ik the digispark doesn't have internal memory so that's why i asked what do i buy to get this functionality

@SenaCarbtc There is absolutely no way for a USB device to query what software is installed on your computer - no matter what device you buy. It's just not physically possible. Only software installed in your computer can know what software is installed in your computer.

@SenaCarbtc The only thing you could possibly do is send some custom message from the USB device that the software responds to, sending a message back. If that message never arrives you can assume the software either isn't installed or isn't running.

I didn't mention "serial" in my answer. I am now uncertain if by Digispark you mean the device you plug into your computer, or some software running on the computer (like the IDE). when the digispark connects it should check if f17 is held down or not - what is "it" in that sentence?

@NickGammon the it refers to the digispark, when connected the digispark checks if the f17 key is pressed down and if it is that means my program is running in the background so use the functions that are compatible with the program, i already got an answer to use the scroll lock key but can this be done with the f17 as no program uses it

See amended answer.


text:
How to post JSON data from Arduino?
I want to post data that I'm getting from the sensor every 5 seconds to my application in JSON format. Initially, I'm getting data as int and converting into String.
For example:
if data=15, it is converting into string.
String st=String(data);

Now I want to post st every 5 seconds.
    int S2 = http.sendRequest("PUT", "{\"itemId\":\"64006A962B71A1E7B3A0428637DA997C.327681\",\"item\":{\"Properties\":{\"AssetSensorDistance\":\"+st+\"}},\"operationType\":\"Update\",\"originalItem\":{\"Work_Order\":{\"ItemId\":\"64006A962B71A1E7B3A0428637DA997C.327681\"},\"Properties\":{\"AssetSensorDistance\":\"+st1+\"}}}");
    Serial.print("Sensor Status: ");
    Serial.println(S2);

st1 is the previous value, it is printing httpcode -2(invalid Syntax).
Can anyone help me with this issue?
Thanks in advance.

I take it, at some other point in your program, you are telling it where to post the data to?

To My Application

please provide detailed information in your question about what you are observing. ... there appears to be a contradiction in your statements

The string
"{\"AssetSensorDistance\":\"+st+\"}"

contains a literal "+st+". If you want to do string concatenation, you
should terminate the string with a double quote character, then add st,
then use another double quote to start the second part of the string:
"{\"AssetSensorDistance\":\""+st+"\"}"

it displaying as +st+ in my application instead of value

@AnneLingesh: That's what I wrote in my answer: you have a literal “+st+” in your string.

I didn't understand @Edgar Bonet 2

it displaying as +st+ in my application instead of value ... your post says that it does not work, that you are getting invalid Syntax ... which is it? you are either getting some data to your application, or you are not getting data to your application.  .... update your question with more information

Getting data but which I'm not expected, I want to display value in my application not st(text)

@AnneLingesh: Please, read my answer again slowly, paying attention to each word and punctuation. If there is still something you do not understand, tell us what exactly you do not understand.


text:
Servos: attach() and write()
Arduino newbie here, so this question might sound too simple. I am trying to run a parallax continuous rotation servo using Arduino Uno. From the reference, I learned that the servo needs to be "attached" to one of digital pins with PWM capability, and the servo's speed can be controlled by write(0~180, 90=stop).
But I am having a hard time understanding the role of the PWM digital pin. If the servo's speed and direction of rotation is determined by write(), what is the role of attach(pin#)?
Thanks in advance!

attach tells the servo library which pin it should be writing to, this is stored somewhere in ram and write will look it up and communicate with the correct pin.
It's possible that you are using the other pwm capable pins for other purposes and suddenly having that library interfere with that is not a good thing.

If you dont use the Servo library  and instead  connect the sertvo signal wire to a pin  then define the pin as output and set the pin low. Then set the pin high for a set number of microseconds the servo will move to the appropriate position. The pin is then set to low it should stay at low for 20milliseconds ( servos are happy at 50Hz i.e one pulse every 20ms.
    #define servopin 9
    t=1000;
    int step=10;
    Setup() {
    pinmode(servopin,OUTPUT);
    digitalWrite(servopin,LOW);
    }
    loop() {

     while (t<2001) {
       digitalWrite(servopin,HIGH);  // with the delay sends a timed pulse
       delayMicroseconds(t);
       digitalWrite(servopin,LOW);
       t+=step;
       delay(19);  // upto next next pulse
     }
     while (t> 999) {
       digitalWrite(servopin,HIGH);
       delayMicroseconds(t);
       t-=step;
       delay(19);
     }
    }

This will cause the the servo to sweep 90deg back and worth continuously.
Changing step will alter the time it takes, reduce it to 1 and it will take much longer.
Exactly what Attach does is unclear but it registers a variable and links it to a timer and to the pin used. The above code uses the built in Millis and Micros timers. The microsecond would be difficult to make unblocking with out affecting the timing. The off delay can be made unblocking so for example you could make two servos to work seemingly together.
Don

First of all, you don't need to connect it to one of the PWM pins. Any digital output pin will work just fine.
Judging by the Arduino reference, attaching the servo to a pin is kind of like to declare a variable. By using myservo.attach(pin) you also give the servo a name (myservo in this case), and you can also add maximum and minimum values to the servo's rotation by adding two extra values to the end: myservo.attach(pin, min, max)
When you then use the myservo.write() function, the Arduino will "remember" what pin myservo is connected to, as well as the maximum/minimum settings for it.

Servos need the pwm on the control line, they compare the duty cycle value to the internal potentiometer and apply torque to correct any discrepancy

@ratchetfreak yes, but what I meant is that you don't have to use one of the pins with PWM labeled onto them. On the Arduino Uno, pin 3, 5, 6, 9, 10 and 11 are PWM pins, but you don't have to use one of these.


text:
How to set Inquire Access Code (IAC) via AT commands on HC-05?
I am trying to set IAC of HC05 via AT Commands, but for some reason, the result is not as desired.
I need to set the IAC as '1234', for which I enter the command:
AT+IAC=1234

The module responds OK, but when I ask AT+IAC?, it replies '01234'.
Now, it has been troubling me for the past few days. I've also tried adding '\r\n' to the end of command, but it sets the IAC as '1234444'
I would be thankful if you could help me with this! I tried searching the net but to no avail.

Are you manually talking to the HC-05 via a direct serial connection or via an Arduino program?

I do it via the serial monitor of the Arduino IDE.

You have to have \r\n in both the set and read command.
Example:
AT+IAC=12345f\r\n
OK

AT+IAC?\r\n
+IAC: 12345f
OK

Thanks MatsK, but I'm afraid it doesn't work. When I enter the code AT+IAC?\r\n , it gives Error(0) which I've looked is for command error. Trying it without \r\n in the inquiry code resulted in +IAC:12344444. Any idea what's cooking up there?


text:
Templated class: How to create instance and work with it?
I have created a class like this:
#ifndef MyList_h
#define MyList_h

#include "Arduino.h"

template <typename T>
class MyList {
public:
  MyList(void);
  ~MyList(void);

  void addItem(T* item);

  //more stuff

};

#endif

And implementation is like this:
#include "Arduino.h"
#include "MyList.h"

template<typename T> MyList<T>::MyList(void) {
  // constructor implementation here
}

template<typename T> MyList<T>::~MyList(void) {
  // desctructor implementation here
}

template<typename T> void MyList<T>::addItem(T* item) {
  // function implementation here
}

// ...more stuff

In my .ino Sketch I'm doing this (found this solution in a C++ example):
#include "MyList.h"
MyList<word>* list = new MyList<word>(); // global scope
//... more stuff

But when compiling, Arduino IDE complains:

Test.ino:5: undefined reference to `MyList::MyList()'

I googled a bit and found this alternative way for creating the instance:
ArrayList<word>* list;

Then there's no error, just compiles file. BUT as soon as I want to use this instance (=adding code) like this:
list->addItem(i);

compiler complains again:

Test.ino:25: undefined reference to `MyList::addItem(unsigned int*)'

What's wrong? Why is this reference undefined?
I tried another way:
ArrayList<word> list; // again global scope

But then the compiler also tells me:

Test.ino:5: undefined reference to MyList<unsigned
  int>::MyList()' /tmp/ccp8qmCz.ltrans0.ltrans.o: In function
  _GLOBAL__sub_D_list':
  /....../Test.ino:5:
  undefined reference to `MyList::~MyList()'

So, how can I create an instance of my class that uses a template?

Environment: Arduino IDE 1.8.3 (I know, I could update...) + Arduino Nano Board.

You need to combine the header and source into a single header file.

I think I found the solution:
According to: https://stackoverflow.com/questions/8752837/undefined-reference-to-template-class-constructor
--> Put all implementation in .h file. That's it. No more compler complains, code runs fine.
I think I have to dig deeper into c/c++ development ...


text:
smoke came out of Arduino Nano
I was working with Arduino and Xbee with LED, circuit LED  + Servomotor
and doing testing for 5 hours (not continuously).
Then once I omitted the Servomotor circuit and I connected flex sensor, which required connecting 10k Resistor and connect it the laptop as usual, smoke came out of the board (from USB side).  I disconnected it immediately, but now the board doesn't light up and the 5V gives 1.5V.
Is there any chance to fix the board?
I discovered that the B2 diode cracked in the middle, the picture is showing a  good Arduino Nano.
I found a very similar in this post about dead NANO

If you can identify which components have fried they can be replaced. Or you just get another board.

I don't know unfortunately, I really don't know what cause it.

I figured out that the chip B2 (next to the USB) exploded and cracked

B2? Are you sure you don't mean D2? I don't know what a "B?" is other than a battery, and it's not that.

Although I don't see a D2 on the schematic, only a D1. Tell you what - maybe a close-up photo of your board showing the broken component would help...?

Please add a photo to help us understand.

I attached  a picture for the backside of arduino nano

Answer edited, I did not understand you had a Nano

If my understanding is correct, the flex sensor was connected between 5V and GND.
This acted like "short circuit" and should not have burned the AVR, but only the power supply side. If you have a multimeter and some soldering skills it should be possible to fix the board.
Supposing you have an genuine arduino UNO, here is a schematic but it may not be the right version

Remove the MCU
Check voltage between GND and XUSB is 5V (if not either your USB port is burned or you have a short on the board or a component)
Check voltage between GND and USBVCC is 5V (if not, replace the fuse)
Check voltage between GND and +5V is 5V (if it's still 1.5V as you mentioned, try replacing transistor T1 but I do not understand why it would burn. If it's 5V replace the MCU)

EDIT for Arduino Nano
I did not understand you had a nano board (schematic)
The component "B2" you mention is the diode D1 (MBR0520). It burned because of the short circuit you created and nothing else should be defect. It acted like a fuse. Simply replace it and it should be fine.
If you are VERY CAREFULL not to overload the nano with external circuitery and never bring external 5V you could just remove it and make a little solder bridge (waiting for replacement part)

The circuit is correct (as I think), but here is was I just noticed, B2 chip is cracked. I don't know what I can do to it

soldering a bride over the diode?  do yu think I can use USB port normally after that?

Yes a bridge over the diode should work but plese be carefull if you do that. The diode is only here to protect USB port if external power is applied (or as fuse as you demonstrate ^^) and a short will work. BUT DO NOT APPLY EXTERNAL POWER SUPPLY IF YOU DO THAT

external power is power by battery right? .. because I read somewhere that it may affect the Laptop's port as well if I shorted the diode and connected the NANO by USB. do yu hav idea about this?

@O2M I'm electronic and software engineer, shorting the diode if you connect nothing else than 1 USB port to your Nano is no risk at all for the PC and the Nano. Diode is here to prevent current flowing into the USB port if you connect external power (battery or other). Your short circuit experience with flex sensor shows that the diode also protects the computer USB from overcurrent by burning (this protection is only side effect, the diode could be shorted instead of open). Thus shorting the diode should only be a temporary solution to confirm nothin other is broken and it should be replaced

very helpful information, thank you so much:) i'll solder it temp. till I receive  a new diode

The Nano has mainly surface-mounted devices on it. You need to be quite skilled to remove faulty ones and replace them, without special equipment.
By the time you have identified which one needs replacing, removed it (no easy task if it is the processor) and replaced it, it would be easier and probably cheaper to just buy a new board.
You may well have fried the main processor (Atmega328P) which I see with a quick search is selling for around $7 to $8 in one-off quantities, whereas you can buy the entire Nano for around $13 for a genuine one, or around $9 for a clone. It just won't be worth the trouble.

hello sir, the  problem is that the circuit seems correct and there is no short circuit anywhere, i'm really afraid to by a new one and burn it as well since i'm going to build the same circuit again. Can you identify whether the cause of burning is by the circuit or no? The flex sensor required 10K-R and lilypad Xbee board both connect to the 5V.  The board orginaly was working fine as I said, but once I removed Servo and I connected the flex Sensor circuit this what happened.

I figured out that the chip B2 (next to the USB) exploded and craked


text:
ATTiny85 and DHT11 - Sensor always returning 0
Good day.
I am making a small weather station using ATTiny85, DHT11, and an OLED display.
There are many, many tutorials that explain how this works, and various libraries that show you how to get the DHT11 to work with the ATTiny85 and others that are dedicated to the SSD1306 Oled displays, some even show you how to combine them together. Well, for the better part of 2 days nothing worked for me.
My schematics is as follows:

And here is a picture of the actual thing, working with a CR2032 Coin Cell:

The Libraries I am using are:

OLED Libraries for ATTiny85 - Source: http://www.14core.com/wiring-digispark-attiny85-with-096-oled-screen-display/
Rob Tillaart DHT Library - Source: https://github.com/RobTillaart/Arduino/tree/master/libraries

My Code is as follows:
    //OLED Libraries for ATTiny85 - Source: http://www.14core.com/wiring-digispark-attiny85-with-096-oled-screen-display/

#include <font6x8.h>
#include <font8x16.h>
#include <num2str.h>
#include <ssd1306xled.h>
#include <ssd1306xled8x16.h>
#include <SSD1306_minimal.h>
#include <TinyWireM.h>
#include <USI_TWI_Master.h>

#define DEG "\xa7" "C"

SSD1306_Mini oled;

char strHum[4];
char strTemp[4];

#include <dht.h>
dht DHT;
#define DHT11_PIN 1

void setup()
{

  TinyWireM.begin(); // initialize I2C lib - comment this out to use with standard arduinos
  oled.init(0x3c);
  oled.clear();

}

void loop()
{

  //            DHT Code goes here                              //

  DHT.read11(DHT11_PIN); //Calling the read function

  float hu  = (DHT.humidity, 1);
  float te  = (DHT.temperature, 1);

  //            OLED Start -- DO NOT CHANGE ANYTHING            //

  //oled.clear();

  oled.startScreen();
  oled.cursorTo(10, 0);
  oled.printString("ATTiny85 & DHT11");

  oled.startScreen();
  oled.cursorTo(12, 9);
  oled.printString("Temp & Humidity");

  oled.startScreen();
  oled.cursorTo(10, 18);
  oled.printString("www.MDChaara.com");

  oled.startScreen();
  oled.cursorTo(0, 27);
  oled.printString("mdchaara@gmail.com");

  oled.startScreen();
  oled.cursorTo(0, 45);
  oled.printString("Humidity(%): ");

  oled.startScreen();
  oled.cursorTo(110, 45);
  oled.printString( itoa(int(hu), strHum, 10));

  oled.startScreen();
  oled.cursorTo(0, 55);
  oled.printString("Temperature(c): ");

  oled.startScreen();
  oled.cursorTo(110, 55);
  oled.printString( itoa(int(te), strTemp, 10));

  //            OLED End          //

  delay(5000);
}

Now I know that the OLED code works, and it was a very interesting round or research to get it to work. The DHT code is another story. I have tried 6 different libraries and none of them worked. They all either return 0, 1, or blank readings on the screen.
I have checked if the sensor is working with an Uno and a Nano, works well! I checked the connections, and the soldered parts and did continuity tests, but the issue still remains.
I am asking because I am hoping a fresh set of eyes can pin-point the issue that I am facing. Any help will be highly appreciated.

Arduino IDE: 1.8.2
OS: Windows 7 64 bits
Micro controller: ATTiny85-20PU

Sketch is uploaded to the micro controller using Arduino Uno as a programmer.
Sketch is uploaded at Internal 8MHz clock setting.
Thank You.

Is that second pin of the DHT, the one that goes to the ATTiny pin, supposed to also be connected to +3V like that?  Pretty sure there was supposed to be a resistor there.  You should probably also include some decoupling caps on the power lines.  0.1uF as close as you can get to the power pins of the ATTiny.

@Delta_G - Thank you for your comment. I have a 10K resistor connected to the data pin of the DHT11 sensor. My understanding is that the pull-up resistor is needed because the data line to the sensor is bidirectional. I have tested the sensor itself with an UNO and it worked well (with and without the resistor, powered with 5v and 3v3 volts) which yielded different results of course but that is expected. I think my issue could be in the software itself.

Why is the line DHT.read11(DHT11_PIN); commented? You have to perform a read before accessing the variables...

itoa()  is for converting an integer to ascii, but you are giving it a float.  It works on a PC (Visual Studio), but you might want to check it works under GCC.  Also what happens if itoa returns more than 4 characters?  You might want to consider putting the strings in flash?  I think you prefix them with T?? (Please someone help!!)

@frarugi87 - That is commented because it's from another library. I will actually remove it from the code. Thank you for highlighting this.

@CodeGorilla - You are right, but changing the type does not help. I did try to read it from DHT as an int (didn't work), pass it to itoa() as an int (didn't work), and as a float (also didn't work). itoa() would never pass more than 4 characters, but I have non the less changed a few things in the code. Please have a look and check if you can spot something. Thank you for the comment, and the call for help.

@MDChaara you said that you are using Rob Tillaart's library. This library (actually there are two, but they work the same) REQUIRES you to call the read function before getting the results from the object. See this example

@frarugi87 - Thanks for the example. The function is called but the result remains the same. I have updated the code. Thanks for your help. I appreciate it.

@MDChaara Have you tried printing a literal string rather than iota output (which should be a perfectly good string, but...).  i.e. try printing the temp as "42" and make sure it appears where you expect it to.  All the other strings work so this should too.  I appreciate its probably pointless, but...

@MDChaara the pinmode on the dht pin input is useless (the library manages that for you). Try checking also the return value of the read11 function (like they do in the example)

@CodeGorilla : You might actually be onto something :) When I print a number it comes in binary. I tried 30 and it printed 11110 on the screen :)

@frarugi87 Thanks. I will remove it and try the code.

Ok i tried something like that for myself and thanks to this and ..many other posts and forums/videos i could make myself something that works but with a little other setting like in the start post (other libs ect)
in my case the main reason for the "1" output on the oled was this:
  float hu  = (DHT.humidity, 1);    //original

  hu  = (DHT.humidity);       //what worked for me

Maybe you can figure out more Problems, my code is shure not perfekt! But maybe it helps someone for a vew steps
#include <dht.h>
#include <U8x8lib.h>
#define DHT11_PIN 1
dht DHT;
int temp = 0;
int humi = 0;
char strTemp[4];
char strHumi[4];

U8X8_SSD1306_128X64_NONAME_SW_I2C u8x8(/* clock=*/ 2, /* data=*/ 0, /* reset=*/ U8X8_PIN_NONE);         // Digispark ATTiny85 Pin 0 Data, Pin 2 clock

void setup(void)
{

  u8x8.begin();
  u8x8.setPowerSave(0); //enegergiesparen 0 aus

}

void loop(void)
{

  int chk = DHT.read11(DHT11_PIN);

  temp = (DHT.temperature);
  humi = (DHT.humidity);

  u8x8.setFont(u8x8_font_chroma48medium8_r);
  u8x8.drawString(0,0,"~~~~~~~~~~~~~~~~");
  u8x8.drawString(0,1,"Temperatur");
  u8x8.drawString(1,2,( itoa(int(temp), strTemp, 10)));
  u8x8.drawString(4,2,"Grad Celsius");
  u8x8.drawString(1,3,"--------------");
  u8x8.drawString(0,4,"Luftfeuchtigkeit");
  u8x8.drawString(1,5,( itoa(int(humi), strHumi, 10)));
  u8x8.drawString(4,5,"Prozent");
  u8x8.drawString(0,6,"~~~~~~~~~~~~~~~~");
  delay(200);
}

The DHT works, by specification, with a 3.5V minimally. I think you can expect anything if you don't provide the appropriate voltage, which seems to be only 3V from the picture you show.
source:
https://components101.com/dht11-temperature-sensor

The DHT11 is notoriously slow to respond and often returns null for readings sporadically.
I notice in your second circuit you have resistors by the sensor but I cant see what pins they are connected to.
You will need pullup for the sensor data line 4K7 usually does the trick.


text:
Using Arduino UNO to retrieve ATMega328P-PU chip signature
Good day.
I have successfully built and tested an Arduino-on-breadboard about 2 days ago.
The device is rather straight forward, I have added a voltage divider and an LED to indicate power.
The schematics are as follows:

And this is a picture of the actual board:

I am using an ATMega328P-PU as a Microcontroller chip.
I uploaded quite a few sketches on the board and all seemed to work well. I was trying to upload a sketch yesterday but I got:
 "avrdude: Yikes! invalid device signature".
I rebooted the computer, rebuilt the entire board again, and tried once again to load a sketch using Arduino as ISP. The message changed again to:
avrdude: Expected signature for ATmega328P is 1E 95 0F
         Double check chip, or use -F to override this check.
Wrong microcontroller found.  Did you select the right board from the Tools > Board menu?
I did a search online and I have found many forums suggesting that I change the avrdude.conf file parameters to different signatures "Although these are mainly targeted at people using ATMega328-PU, not ATMega328P-PU" but this also did not help.
I tried burning the bootloader again but I still get the same error message.
I tried to find a way to "retrieve" the chip signature, but I didn't.
I know that there is a chance that I have bricked the chip somehow, but how do I know for sure? and is there anyway that one can use and Arduino as a tool to retrieve the chip signature or verify if the chip itself is dead?
Thank You

In the arduino setting enable verbose output. After that the device signature should be visible, along with a whole lot of other information, when you try to upload.

There are two easy ways than that Method 1 - Using Atmel Studio Click-here Method 2 - Without Atmel Studio Click-here I Did using method 2 successfully .For method 2 if your are using Atmel Studio 7.0you need AVRISP MKII firmware 1.18 Download-Here If above webpages not available you can get those in PDF format below from my google driv

There is a nice explanation here about Atmel chip signatures.
It sounds like you already know this, so for others looking for help:
It says that there are different signatures in the Atmel chips you mention.  That you can over ride the Avrdude program using an "-F" switch.  Or you can change the Avrdude configurations to use the "other" Atmel chip (however, the consequences if any were unknown by the author).
This may be an obvious step, but double check to make sure the IDE's target board settings are correct.
You may also want to check the communications between the programmer and the target.  You might look into dropping the speed.  But the better way is to scope the lines to see if data is being sent to the target and if the target is talking back.  From that you can infer if the problems is a bad connection or if the chip has been damaged.
If you want to dig further using software tools you could look into driving Avrdude for your self.  There is a easy to read tutorial here and what appears to be an everything you wanted to know and more document here.
In the 1st tutorial (from ladyada.net) we see a test which they purposely try the wrong signature:

Just for kicks try running this command avrdude -c usbtiny -p atmega8
  -U flash:w:test_leds.hex

You'll see that it stops at step 2, once the signature is different
  than the expected one it stops. This is because code that is compiled
  for an attiny2313 wont run on an atmega8 (this is true of most
  microcontrollers, the .hex files are not cross compatible)

But more interestingly, Avrdude prints out the signature read back from the target!  So, if you run the same test, you could tell if Avrdude is able to communicate at all with the target.  That is, you may see all zeros or all ones or even an alternate message from Avrdude. Which could be an indication that the target is not talking.

Thank you for the detailed answer. I have accepted the answer as it did point me to some very interesting findings. One of the findings is the fact that even a "Briked" ATMEGA328P-PU or any AVR chip for this matter can have it's "Virginity" restored according to This Post

More than a year down the road, I learned a few things, and I am answering my own question so that if anyone faces the problem I faced (and I know how stressful it is) can give this a go. It may help.
One of the most interesting things I have learned is Mr. Nick Gammon's (Someone have actually called him Mr. Arduino) wonderful collection of sketches designed to do exactly this sort of thing.
If you ever need to find out what is the signature of your ATMega328 (or any arduino micro controller chip for this matter, visit this site.
The main reason I asked the question was to "un-brick" my ATMega328s, and I have actually done some thing wrong that to this day I can not figure out that resulted in 4 chips giving the error in the question. Just when I was about to give up, I found this link from Mr Gammon's website which sorted out the problem in 3 out of the 4 ATMegas, the fourth I am keeping to test a high voltage programmer in the future.
Thank you.

when you try to change the signature there are 2 areas where the code 1E 95 0F is displayed. If you try changing the signature in the wrong position, then will it show the error message 'microcontroller not found'. I did the same mistake once. I would suggest you rely on the find option in the Edit menu and search for the code.
Edit > Find > Search 1E 95 0F > ( opt for 'down') search next.


text:
How do I connect a vibration sensor/switch to a breadboard?
I have the following vibration sensor:

It has one short/firm-er terminal and one long/flimsy terminal.  Now the shorter terminal slides easily into my breadboard but the flimsy one clearly does not.  A few related questions:
1) How do I go about connecting this to my breadboard (simply plugging it in doesn't work)?  Do I have to solder a wire onto the flimsy end?
2) Why is this switch manufactured this way (with a flimsy end)?
3) Is it right to assume that the longer end is positive (+) and the shorter end is negative (-)?
Thanks!

It appears from this information source:
http://www.electrodragon.com/product/vibration-switch-sensor-sw-18020p/
that the sensor is an electrical contact on the firmer side surrounded by a very sensitive spring within the enclosure. The coil spring is by design made of a smaller diameter wire to provide sensitivity to movement. Rather than manufacture a translation to a heavier piece of material, the thinner lead is brought out of the enclosure.
I suspect that it will not work on your breadboard, due to the flimsy end being too small to make solid contact within the breadboard. You could resolve that aspect by soldering on a heavier segment.
Because it is designed as a simple switch, there is no plus or minus.

Thanks!  That worked.  I soldered the flimsy end, plugged everything into a breadboard and now I'm getting a whole bunch of readouts.  I guess now I'm trying to figure out how to set certain thresholds but the numbers are all over the place.

From the information sheet, it appears that the spring will continue to contact the center post with a frequency based on the magnitude of the vibration. If one considers this to be a push button switch, it has a serious problem with debounce. Perhaps adding a debounce segment of code to your program will help?


text:
How to read wireless doorbell's indicator LED circuit
I have a cheap wireless doorbell. My plan is to include an ESP8266 and power the doorbell from the microcontroller 3.3V output as the doorbell also runs on 3V
I specifically chose a model with a LED, as I thought it should be easy to use the LED as a trigger on the ESP8266 and consume as a digital input.
I've soldered two wires from the LED positive and negative solder points. What I find strange is that I measure 3V between the PCB ground and the positive LED wire when the doorbell is not triggered. If I measure between the negative LED wire and positive LED wire, I see a voltage spike corresponding to each LED flash (it flashes 5 times). I plan to debounce this in software.
I did not expect to measure a voltage when the doorbell is not triggered between the positive LED wire and the PCB ground, and this will definitely not work as I intended.
Disclaimer: I'm not an electronic engineer, and my test equipment consists of a multimeter.
I've included a photo of the PCB. It is labelled "QH-823A-19" but searching for this on the Internet has provided no usable information.
What have I tried?

I've tried to trace the tracks running to the LED solder points, but the tracks run under some components which makes this hard
I've tried to measure different points on the board for a positive 3V spike when the LED flashes, no success

Any advice on how to achieve this? Am I going about this the wrong way?

The LED will be wired so  that the anode is connected to +3V and the cathode is connected to the MCU's output pin. Set to HIGH the LED is off, and set to LOW it's on. This is common since historically microcontrollers have been able to sink more current than they can source, and it may be that this one has a specific current limited pin for driving an LED to reduce the number of external components required.

I measured the voltage between the cathode wire and the PCB ground. It reads as high when the LED is not on, but pulses to LOW when the LED starts flashing
Unless I am misunderstanding you, I don't actually want to switch the LED on from the MCU, but rather, detect from the MCU when the LED is ON. I am thinking then that perhaps I can set the input high and detect when it goes low?

Consider tossing away the store bought door bell kit as the ESP processors normally have build with WIFI radios PCB antennas allowing them to connect to your house network directly.  If battery operated, the WIFI option can be replaced by an ESP-NOW network with a software change to the ESP code.  But you will then need to create some sort of mains powered ESP-NOW to WIFI bridge somewhere in your house.

"I measured the voltage between the cathode wire and the PCB ground. It reads as high when the LED is not on, but pulses to LOW when the LED starts flashing"... so @Majenko is correct.  Actually, it should read 3.3V - the LED diode voltage drop.  So maybe 2.5V when high.

You may want to feed the signal through a comparator to ensure that it gets high enough to register as a HIGH on the ESP. Either that or use an analog input to read the voltage, which won't mind if it's not high enough to be HIGH, since you can define your own threshold in software then.

st2000: Yes, also a viable approach. But this is simple and cheap, you still have a working doorbell, and ESP-NOW brings other complexities. I already have a MQTT broker running, this seemed much simpler

Majenko: hoping I can trigger on LOW then, else, reading the analog input is definitely an option

If you have an MQTT broker already running consider adding NodeRED to the same computer.  This will add a graphical programming interface where you can make complex logical decisions based on any number of inputs.  For instance, you could, upon the door bell ring, check if the sun has set in your part of the world and turn on the porch light for 5 minuts if is has.

You can only trigger on LOW if you also don't trigger on HIGH. LOW is only LOW because it's not HIGH. If your "high" voltage level is not high enough to be an actual HIGH then you can't get it to go from HIGH to LOW. You'll just be stuck in an indeterminate area between HIGH and LOW.

Inputs are generally "Schmitt Triggers". You have two thresholds - a high threshold (VIH) and a low threshold (VIL). You have to get above VIH before it switches the input to HIGH. Then it has to get below VIL to switch to LOW. If it never gets to VIH again it will always be LOW even if it is above VIL.

Thanks Majenko, I've accepted your answer and I need to experiment more. I have much more information now to go on

Your LED is connected between V+ and the GPIO of the microcontroller. This is a common arrangement because historically microcontrollers have been able to sink more current than they can source. It's also easier to make a "low side" constant current source, which this custom chip may have, to reduce the number of external components needed.
To read the state you need to take the voltage at the cathode of the LED referenced to the ground of the doorbell circuit. This will give you a voltage at or near the board supply voltage when the LED is off, and a lower voltage (near zero but probably not zero) when the LED is on.
If the voltages are within the threshold voltages VIH and VIL of the ESP8266 then you can just directly read that level as a logic level. If not then you may need to "condition" the voltage to give proper logic levels.
For example you could use a comparator (an op-amp running in "saturated" mode) to compare that voltage to a single threshold voltage that is roughly half way between the HIGH and LOW voltages. That would then swing the output between the supply and ground voltage levels giving you a much cleaner signal.
Or you may use an analog input (the ESP8266 only has one, and that is quite a crude one with only 1.1V maximum allowed on it, so a voltage divider will be needed) to measure the voltage and do the comparison in software.
Another option would be to remove the LED completely and replace it with an optocoupler, thus making the LED itself an electronically operated button to the ESP8266. This will also keep the ESP8266 ganvalically isolated from  the doorbell.

Some feedback on your suggested solution, Majenko.
It is working fine. I decided to go with the optocoupler route, I added a PC817C, on the input side I use the anode and cathode of the led output from the doorbell circuit with a small resistor of 56E, on the output side I have a small debounce circuit, which feeds into a power latch circuit (P and N channel Mosfet) which powers up the ESP8266, it connects to WiFi and sends an MQTT message, and then sets the latch pin low to switch the circuit off again.

Schmitt Trigger using a Comparator
If you follow @Majenko's advice of using a comparator, you could add some hysteresis to it with a few resistors to create an inverting Schmitt trigger. This will increase the noise immunity and thus reduce the noise going to the ESP8266. The following simulation has a noisy input transformed into square pulses. It also performs a small level shift from an input of 3 V to an output of 3.3 V.

Figure 1 – Schmitt trigger circuit.

Figure 2 – Schmitt trigger simulation.
Hysteresis versus Low-Pass Filtering
There is a subtle difference between hysteresis and low-pass filtering.
The following experimental circuit, Figure 3, demonstrates this difference with an interactive simulation where you can click on the switches to add/remove noise and add/remove filtering.
The low-pass filter has a cut-off frequency of 40 Hz.
I've set the high-going threshold, Vt+, to 2.31 V and the low-going threshold, Vt-, to 1.54 V. I calculated these figures from the 74HC14 datasheet using the thresholds for 3 V at 25°C and scaling them for 3.3 V.

Figure 3 – Circuit showing difference between hysteresis and low-pass filtering.
Hysteresis provides greater noise immunity and reshapes a slowly changing signal into a square wave ready for a digital input. But it can't filter out noise spikes that breach its threshold levels. These spikes would cause the Schmitt trigger to output square pulses. See the orange section of Figure 4.
Low-pass filtering filters out high frequency spikes which could breach the upper and lower thresholds of a Schmitt trigger. See the green section of Figure 4. Note that it also introduces a phase shift. If the noise were created by switch-bounce, then the low-pass filter would be performing debouncing. The blue section represents the ideal world where there is no noise, no need of filtering, and the output is in phase with the input.

Figure 4 – Simulation of hysteresis versus low-pass filtering.

Tim, thanks for the suggestion, I've been trying out a 74HC14 as part of a hardware debounce solution and it seems to work well. As I mentioned, I'm a hobbyist, so no electronics engineering background (I'm a comp sci guy). In your provided circuit diagram, is the input signal coming from the left, where I see the 40Hz? What does the line connect to between the bottom resistor and ground going out to the left?

@Wil777, the 74HC14 is a good choice for cleaning up a slowly changing signal and producing a square wave for a digital input, but it won't perform debouncing. Consider a noise spike that crosses both trigger thresholds - it will output a short square wave. Debouncing is performed by a low-pass filter, either in hardware with an RC filter before the Schmitt trigger, or in software with a debouncing algorithm, or both.

Tim, I do have an RC circuit combined with the 74HC14, but my understanding that the 74HC14 also provides hysteresis was based on an article I read on hackaday called "Embed With Elliot: Debounce Your Noisy Buttons"

@Will777, there is a subtle difference between low-pass filtering for debouncing and hysteresis for signal reshaping. I've updated my post to explain it. I've just looked at Eliot's Hackaday articles. He is saying the same thing: Stage 1 - low-pass filter for debouncing; Stage 2 - hysteresis for signal reshaping; Stage 3 - software debouncing algorithm. BTW, here is my "The Ultimate Debouncer(genuine tm)!" or your money back :-)

Thanks Tim, nice article and I see it caters for a lot of different configurations of software debouncing. Since my MCU is powered down, and I am triggering a power latch to start it up from the doorbell, hardware is prefereable for debouncing. It is working very well


text:
Using Arduino Motor Shield
I'm looking to create a blind controller and have set up the hardware and software as I think it should be.
I had the software working fine using an IC motor driver, but as I am no great at soldering, I decided to use a motor shield. The software (below) now only turns the motor one way. I did amend the code to try to get the motor to turn the other way, and it did but only when the 'BlindOn' was during it's on.
Therefore, the hardware is set up correctly (pins D1 and D3) but there is some modification needed to this program; any help or advice greatly appreciated.
/**********************************************************************************
  * Code for controlling multiple devices connected to one NodeMCU using Amazon Echo
  *
  * Written by Sid for Sid's E Classroom
  *
  * https://www.youtube.com/c/SidsEClassroom
  *********************************************************************************/
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include "fauxmoESP.h"

#define WIFI_SSID "VM0718169" //change your Wifi name
#define WIFI_PASS "8kcgvwSFymjx" //Change your Wifi Password
#define SERIAL_BAUDRATE                 115200

fauxmoESP fauxmo;
//declare switching pins
//Change pins according to your NodeMCU pinouts
#define BlindOp D1
#define BlindCl D3
#define Test D2

volatile bool BlindOpOn = false;  // needs to be volatile since used in ISR
volatile bool BlindClOn = false;
volatile bool TestOn = false;

const unsigned long BlindOpOnTime = 5;    // seconds
const unsigned long BlindClOnTime = 5;     // seconds
const unsigned long TestOnTime = 5;

volatile unsigned long BlindOpStartTime;
volatile unsigned long BlindClStartTime;
volatile unsigned long TestStartTime;

// -----------------------------------------------------------------------------
// Wifi Setup
// -----------------------------------------------------------------------------

void wifiSetup() {

    // Set WIFI module to STA mode
    WiFi.mode(WIFI_STA);

    // Connect
    Serial.printf("[WIFI] Connecting to %s ", WIFI_SSID);
    WiFi.begin(WIFI_SSID, WIFI_PASS);

    // Wait
    while (WiFi.status() != WL_CONNECTED) {
        Serial.print(".");
        delay(100);
    }
    Serial.println();

    // Connected!
    Serial.printf("[WIFI] STATION Mode, SSID: %s, IP address: %s\n", WiFi.SSID().c_str(), WiFi.localIP().toString().c_str());
}
// -----------------------------------------------------------------------------
// Device Callback
// -----------------------------------------------------------------------------
void callback(uint8_t device_id, const char * device_name, bool state) {
  Serial.print("Device "); Serial.print(device_name);
  Serial.print(" state: ");
  if (state) {
    Serial.println("ON");
  } else {
    Serial.println("OFF");
  }
  //Switching action on detection of device name
  if ( (strcmp(device_name, "BlindOp") == 0) ) {
    // adjust the relay immediately!
    if (state) {
      digitalWrite(BlindOp, HIGH);
      BlindOpOn = true;
      BlindOpStartTime = millis();
    } else {
      digitalWrite(BlindOp, LOW);
      BlindOpOn = false;
    }
  }
  if ( (strcmp(device_name, "BlindCl") == 0) ) {
    // adjust the relay immediately!
    if (state) {
      digitalWrite(BlindCl, HIGH);
      BlindClOn = true;
      BlindClStartTime = millis();
    } else {
      digitalWrite(BlindCl, LOW);
      BlindClOn = false;
    }
  }
  if ( (strcmp(device_name, "Test") == 0) ) {
    // adjust the relay immediately!
    if (state) {
      digitalWrite(Test, HIGH);
      TestOn = true;
      TestStartTime = millis();
    } else {
      digitalWrite(Test, LOW);
      TestOn = false;
    }
  }
}

void setup() {
    //Initialize pins to Low on device start
    pinMode(BlindOp, OUTPUT);
    digitalWrite(BlindOp, LOW);
    pinMode(BlindCl, OUTPUT);
    digitalWrite(BlindCl, LOW);
    pinMode(Test, OUTPUT);
    digitalWrite(Test, LOW);

    // Init serial port and clean garbage
    Serial.begin(SERIAL_BAUDRATE);
    Serial.println("FauxMo demo sketch");
    Serial.println("After connection, ask Alexa/Echo to 'turn <devicename> on' or 'off'");

    // Wifi
    wifiSetup();

    // Device Names for Simulated Wemo switches
    fauxmo.addDevice("BlindOp");
    fauxmo.addDevice("BlindCl");
    fauxmo.addDevice("Test");
    fauxmo.onMessage(callback);
}

void loop() {
  unsigned long duration;

  fauxmo.handle();
  if ( BlindOpOn == true ) {
    duration = (millis() - BlindOpStartTime) / 1100;  // convert to seconds
    if ( duration >= BlindOpOnTime ) {
      digitalWrite(BlindOp, LOW);
      BlindOpOn = false;
    }
  }

  if ( BlindClOn == true ) {
    duration = (millis() - BlindClStartTime) / 1100;  // convert to seconds
    if ( duration >= BlindClOnTime ) {
      digitalWrite(BlindCl, LOW);
      BlindClOn = false;
    }
  }
  if ( TestOn == true ) {
    duration = (millis() - TestStartTime) / 1100;  // convert to seconds
    if ( duration >= TestOnTime ) {
      digitalWrite(Test, LOW);
      TestOn = false;
    }
  }

}

if ( BlindClOn == true ) - this strange convention is inexplicably popular in Arduino-related code...

you are using inconsistent programming style .... at one point you use if (state) and  at another point you use the redundant if ( BlindOpOn == true ) ..... the first style is the desirable one to use .....  use if ( BlindOpOn ) for the second one ...... the if ( BlindOpOn == true ) is redundant because it means if ( true == true ) when BlindOpOn is true

Thanks for the replies, I think the mismatch is due to various people editing the original, but this does work when using an IC motor driver...it will only opens when using the shield, and won't close.
Ideally, it would be one device which operates for a set time when turned on to open, and operates for a fixed time to close.
I need to learn more as I find the many }s used confusing, I've not much experience in programming in general