Measure small capacitances with ATtiny85 (Digispark board) I have successfully run the code provided here on an Arduino Nano. If nothing is connected, it will output a very small capacitance (~ 1 pF).

Then I tried to migrate the code to the ATtiny85 (using a Digispark USB Development Board), but I fail to get anything reasonable out of the code. The first analogRead will always give 1023, whereas on the Nano it gives a very small value (again for nothing connected to the input pins).

It's a bit trickier on the ATtiny85 because the pin numbers are different for digital and analog, but I thought I got that right, so what went wrong in the migration?

const int OUT_PIN = 2; // digital pin PB2 is 2, positive pin of C
const int IN_PIN  = 5; // digital pin PB5 is 5, negative pin of C
const int OUT_ANA = 1; // analog read PB2 is 1
const int IN_ANA  = 0; // analog read PB5 is 0

const float IN_STRAY_CAP_TO_GND = 24.48;
const float IN_CAP_TO_GND  = IN_STRAY_CAP_TO_GND;
const float R_PULLUP = 34.8;
const int MAX_ADC_VALUE = 1023;

#include "DigiKeyboard.h"

void setup() {
  pinMode(1, OUTPUT);
  pinMode(OUT_PIN, OUTPUT);
  pinMode(IN_PIN, OUTPUT);
  digitalWrite(OUT_PIN, LOW);
  digitalWrite(IN_PIN, LOW);
  DigiKeyboard.update();
}

void loop() {

    pinMode(IN_PIN, INPUT);
    digitalWrite(OUT_PIN, HIGH);
    int val = analogRead(IN_ANA); // IN_PIN in Nano version
    digitalWrite(OUT_PIN, LOW);

    DigiKeyboard.println(val);
    if (val < 1000) {
      pinMode(IN_PIN, OUTPUT);
      float capacitance = (float)val * IN_CAP_TO_GND / (float)(MAX_ADC_VALUE - val);
      DigiKeyboard.print(capacitance);
      DigiKeyboard.println(" pF");
    } else {
      pinMode(IN_PIN, OUTPUT);
      delay(1);
      pinMode(OUT_PIN, INPUT_PULLUP);
      unsigned long u1 = micros();
      unsigned long t;
      int digVal;

      do {
        digVal = digitalRead(OUT_PIN);
        unsigned long u2 = micros();
        t = u2 > u1 ? u2 - u1 : u1 - u2;
      } while ((digVal < 1) && (t < 400000L));

      pinMode(OUT_PIN, INPUT);
      val = analogRead(OUT_ANA); // OUT_PIN in Nano version
      digitalWrite(IN_PIN, HIGH);
      int dischargeTime = (int)(t / 1000L) * 5;
      delay(dischargeTime);
      pinMode(OUT_PIN, OUTPUT);
      digitalWrite(OUT_PIN, LOW);
      digitalWrite(IN_PIN, LOW);

      float capacitance = -(float)t / R_PULLUP / log(1.0 - (float)val / (float)MAX_ADC_VALUE);

      if (capacitance > 1000.0) {
        DigiKeyboard.print(capacitance / 1000.0);
        DigiKeyboard.println(" uF");
      } else {
        DigiKeyboard.print(capacitance);
        DigiKeyboard.println(" nF");
      }
      DigiKeyboard.println(val); // usually ~ 520 (because we wait until digVal == 1?)
      DigiKeyboard.println(t); // depends on C: ~ 26000 for 1 µF, ~ 2600 for 100 nF, ~ 250000 for 10 µF
  }

  digitalWrite(1, 1);
  delay(10);
  while (micros() % 1000 != 0);
  digitalWrite(1, 0);

}

The reason this doesn't work is that PB5 is pulled high (as it's used as -RESET pin on the board). The code can be rewritten to use only one ADC pin though.


Measuring voltage on an analog pin - What do I need to know about amperage? I'd like to measure the voltage at a test point on a stepper motor driver chip with an arduino. The voltage at this point controls the amperages to the phase coils and is adjusted to trim the driver.

I have a common ground with the driver already, I'd like to wire the drivers v-ref point to an analog input to drive an LCD showing the output amp number so I can adjust the driver.

The issue I am worried about is that with the hardware I have to test with a properly trimmed driver is pushing 0.84A.

Is this safe to do without killing the arduino board?

Yes. The only thing you need to be concerned about is the voltage. It needs to be less than the Arduino Vcc.

The voltage sense circuit (analog inputs) typically have a high impedance and should draw a negligible current from the circuit being sensed. I didn't have much luck finding the actual spec for any of the AVR chips, but I did find this answer to the question on Electronics.StackExchange – where they say "hard to tell, the specs are incomplete, but 10 KΩ seems like a reasonable guesstimate/assumption" (I paraphrase). The reasoning is interesting and worth a read.


How to change ArduinoOTA upload timeout? I'm using ESP8266WiFiMulti, ESP8266WebServer and ArduinoOTA to communicate with my device and perform over-the-air-updates. Everything was working perfectly until I moved the ESP8266 further from the WiFi router. The OTA upload slowed down, which caused upload timeouts after 5 seconds. It fails at a different point each time, usually between 30% and 60%.
How do I increase the OTA timeout to 30 seconds?
Here is the setup code, let me know if you need more:
void startWiFi() {
    ESP8266WiFiMulti wifiMulti;
    wifiMulti.addAP(ssid, password);
    wifiMulti.run();
}

void startOTA() {
    ArduinoOTA.setHostname(_hostname);
    ArduinoOTA.setPassword(_password);

    ArduinoOTA.onStart([]() {
        Serial.println("Start OTA");
    });
    ArduinoOTA.onEnd([]() {
        Serial.println("\nEnd OTA");
    });
    ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
        Serial.printf("OTA Progress: %u%%\r", (progress / (total / 100)));
    });
    ArduinoOTA.onError([](ota_error_t error) {
        Serial.printf("Error[%u]: ", error);
        if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
        else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
        else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
        else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
        else if (error == OTA_END_ERROR) Serial.println("End Failed");
    });
    ArduinoOTA.begin();
}

The only timeout I can find is in the espota.py script itself. That is riddled with such lines as:
sock.settimeout(10)

You would need to scour that program and change them all.
However
ArduinoOTA uses UDP for communication. Because of that it is unreliable (yes, that's a technical term). It doesn't have any form of retransmit / retry, so if a packet is lost it's lost for good. No amount of increasing of timeouts will make that packet reappear.
So increasing your timeouts most likely will just make it wait longer before failing.
You should consider switching to a more reliable update system which uses TCP instead of UDP - such as downloading an update from a website using ESP8266httpUpdate.
Update:
ArduinoOTA uses a combination of both UDP (to initialise and authenticate the connection) and TCP (to make a "back channel" connection back to your computer) to download the actual binary.
The same still applies: you will need to alter the espota.py program to change its timeouts (sock2 is the back-channel object), but there is also one line in ArduinoOTA.cpp that will need to be altered to increase timeouts.  Line 294:
int waited = 1000;

This is not strictly the number of milliseconds to wait for incoming data, but it's not far off - it's a 1 millisecond delay in a loop while looking for incoming data.  Increasing that will allow more time for the ESP8266 to wait for data to arrive.
But of course, with an unstable WiFi connection YMMV...


Uploading bootloader on ATmega328P SMT package using Arduino Uno I have been trying to upload bootloader on ATmega328P SMT package on a custom PCB using Arduino Uno as ISP, I was quite successful.

I have Googled a lot and have tried numerous ways, sometimes I was able to successfully upload the bootloader, but I am not able to upload the sketch am getting "avr sync error".

What kind of bootloader should I use for this particular package?
How should I upload the sketches into the chip?

I've had success with bootloader of the Arduino IDE.
I used to have some trouble uploading sketches, but I solved them by doing this:

If the atmega is already soldered in a pcb and you have a pull up resistor, or something else connected to the reset pin, disconnect it. reset pin must be free.
Connect the tx, rx and rst pins of your atmega to your arduino.
Press the Upload button in the Arduino IDE and see the leds tx,rx in your arduino, just after the first blink, press the reset button, after that both of the leds should start blinking and in the end your code should be uploaded.


avrdude: Error: butterfly programmer uses avr_write_page() but does not provide a cmd() method When trying to flash my sketch, I see many errors such as:

 ***failed;
 ***failed;
 ***failed;
avrdude: Error: butterfly programmer uses avr_write_page() but does not
provide a cmd() method.
 *** page 127 (addresses 0x7400 - 0x747f) failed to write

And also:

avrdude: error: programmer did not respond to command: set addr

How can I successfully flash my sketch?

After much frustration in trying things, I came across this forum post which advised:

sudo systemctl stop ModemManager.service

If this works, disable the service from starting next boot:

sudo systemctl disable ModemManager.service

It seems like setting ENV{ID_MM_DEVICE_IGNORE}="1" in a udev rule is insufficient.


2 buttons, 1 servo, turn when pressed only I have a code problem. I need to turn a servo clockwise or counter clockwise using 2 microswitches.

The problem is that my code is fine on startup, but when i press the button the servo continues to spin.

How do i make this so it only spins while the buttons are pressed and turn off when they are not pressed?

#include <Servo.h>

Servo myservo; // create servo object to control a servo

// CONSTANTS

// PINS
const int crServo = 12; // sets pin 12 as servo
const int buttonPinCW = 2; // sets pin 2 as button; CW => clockwise => FOCUS FAR
const int buttonPinCC = 3; // sets pin 3 as button; CC => counterclockwise => FOCUS NEAR

// SERVO PROPERTIES
const int crSpeedDefault = 0; // is the stay still position, motor should not turn
const int crSpeedCW = 110; // turns the motor full speed clockwise
const int crSpeedCC = 70; // turns the motor full speed counter-clockwise

// SET BUTTON STATES
int buttonStateCW = 0; //sets button 1 as off
int buttonStateCC = 0; // sets button 2 as off

void setup()
{
  myservo.attach(crServo); // attaches the servo on pin 12 to the servo object
  pinMode (crServo, OUTPUT);
  pinMode (buttonPinCW, INPUT); // sets button as input
  pinMode (buttonPinCC, INPUT); // sets button as input
  myservo.write(crSpeedDefault); // default servo to crSpeedDefault
}

void loop()
{
  crServo = digitalRead(crSpeedDefault);
  buttonStateCW = digitalRead(buttonPinCW);
  buttonStateCC = digitalRead(buttonPinCC);
  // clockwise rotation
  if (buttonStateCW == HIGH) {
    myservo.write(crSpeedCW);
    // counterclockwise rotation
  }
  if (buttonStateCC == HIGH) {
    myservo.write(crSpeedCC);
  }
}

If you want the logic "if none of the two buttons are pressed, stop the servo immediately", then you'd express this in your loop as a if expression where you check if both buttons read LOW:

void loop()
{
  buttonStateCW = digitalRead(buttonPinCW);
  buttonStateCC = digitalRead(buttonPinCC);
  // clockwise rotation
  if (buttonStateCW == HIGH) {
    myservo.write(crSpeedCW);
    // counterclockwise rotation
  }
  if (buttonStateCC == HIGH) {
    myservo.write(crSpeedCC);
  }

  //Are both buttons not pressed?
  if(buttonStateCC == LOW && buttonStateCW == LOW) {
    //Stop the servo.
    myservo.write(0);
  }
}

This assumes your buttons are with pull-down resistors to GND on one side and with +5V on the other side, as detailed in the Arduino tutorial. In short this means that an unpressed button reads as 0 and a pressed on reads as 1 (HIGH). This is unusual because we usually use the internal pullup resistors via the INPUT_PULLUP pinMode parameter with a switched logic (1 = unpressed, 0 = pressed).

I've also removed the line crServo = digitalRead(crSpeedDefault); because that doesn't make sense in my opinion, as I've detailed in my comment.


Scroll one line of text while another line is static on a SSD1306 OLED I have an SSD1306 OLED that I have connected to a Wemos D1 Mini. It works like a charm, but I was wondering if it was possible to have two lines of code, where one line is static, and the other one scrolls? No example on the web as far as I have tried to find.

I just found the answer on the following site: https://lastminuteengineers.com/oled-display-arduino-tutorial/

Basically, the method startscroll* on the display takes some arguments.
By passing the proper start page and stope page you can scroll parts of the screen.

Refer to OLED Memory Map for explanation of the pages on the screen. There are eight pages in the display from 0 to 7, so we can scroll a certain part of the screen by passing specific page numbers as parameters.

In this example, we pass both the parameters as 0x00. This will scoll the first page only (first 8 rows) of the display:

// Scroll part of the screen
display.setCursor(0,0);
display.setTextSize(1);
display.println("Scroll");
display.println("some part");
display.println("of the screen.");
display.display();
display.startscrollright(0x00, 0x00);

Source: https://lastminuteengineers.com/oled-display-arduino-tutorial/


Why is this returning the wrong answer? Why does this print output -3? xpos can be any value.

void loop() {
xPos = analogRead(xPin);
yPos = analogRead(yPin);
pwm = xPos*(255/1023);
Serial.println(pwm);

}

The problem is that (255/1023) is being treated as an integer calculation, meaning the result gets truncated to 0. You can make the compiler promote it to a floating-point calculation by explicitly making at least one of the values floating-point. For example:

pwm = xPos*(255.0f/1023.0f);


Reduce current consumption on ATtiny85 I am trying to reduce current consumption on my project. Right now it is using ~1.28mAh, it should be possible to get it much lower (I am using AA batteries as the power source).

The ATtiny85 has its fuses set to run at 1MHZ, with BOD disabled.

I am using this board to mount the CPU. I desoldered the power LED and the regulator, feeding power directly from the batteries to the 5V input.

Nothing was connected to any other pins while measuring, just 5V and GND. The code was running in debug mode, so every 8 seconds it flashed a debug LED. I don't know for how much this could account.

Full code:

#include <avr/sleep.h>
#include <avr/power.h>
#include <avr/wdt.h>
#include <avr/interrupt.h>

#define DEBUG (true)
#define INT_PIN (0)
#define OUT_PIN (2)
#define LED_PIN (1)

/***************************************************
 *  Name:        ISR(WDT_vect)
 *
 *  Returns:     Nothing.
 *
 *  Parameters:  None.
 *
 *  Description: Watchdog Interrupt Service. This
 *               is executed when watchdog timed out.
 *
 ***************************************************/
EMPTY_INTERRUPT(WDT_vect);
EMPTY_INTERRUPT(PCINT0_vect);

/***************************************************
 *  Name:        enterSleep
 *
 *  Returns:     Nothing.
 *
 *  Parameters:  None.
 *
 *  Description: Enters the arduino into sleep mode.
 *
 ***************************************************/
void enterSleep() {
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  sleep_enable();
  sleep_cpu();
  sleep_disable(); /* First thing to do is disable sleep. */

  #if DEBUG
    digitalWrite(LED_PIN, HIGH);
    for (uint16_t dbg = 0; dbg < 65535; dbg++);
    digitalWrite(LED_PIN, LOW);
  #endif
}

/***************************************************
 *  Name:        setup
 *
 *  Returns:     Nothing.
 *
 *  Parameters:  None.
 *
 *  Description: Setup for the serial comms and the
 *                Watch dog timeout.
 *
 ***************************************************/
void setup() {
  pinMode(INT_PIN,INPUT);
  pinMode(OUT_PIN,OUTPUT);
  pinMode(LED_PIN,OUTPUT);
  ADCSRA &= ~_BV(ADEN); // ADC off
  power_all_disable();
}

/***************************************************
 *  Name:        enterSleep
 *
 *  Returns:     Nothing.
 *
 *  Parameters:  None.
 *
 *  Description: Main application loop.
 *
 ***************************************************/
void loop() {
  digitalWrite(OUT_PIN, LOW);
  digitalWrite(LED_PIN, LOW);
  /*** Setup the WDT ***/
  wdt_reset();
  /* In order to change WDE or the prescaler, we need to
   * set WDCE (This will allow updates for 4 clock cycles).
   * WDTCR on ATTINY85 / WDTCSR on ATMEGA
   */
  WDTCR |= (1<<WDCE) | (1<<WDE);
  /* set new watchdog timeout prescaler value */
  WDTCR = 1<<WDP0 | 1<<WDP3; /* 8.0 seconds */
  /* Enable the WD interrupt (note no reset). */
  WDTCR |= _BV(WDIE);
  // sleep for 8 seconds x 43200 = 96 hours = 4 days
  for (uint16_t i = 0; i < 43200; i++)
    enterSleep();
  wdt_reset();
  wdt_disable();
  GIMSK |= _BV(PCIE); // Enable Pin Change Interrupts
  PCMSK |= _BV(PCINT0); // Use PB0 as interrupt pin
  enterSleep();

  #if DEBUG
    digitalWrite(LED_PIN, HIGH);
  #else
    digitalWrite(OUT_PIN, HIGH);
  #endif
  enterSleep();
  PCMSK &= ~_BV(PCINT0); // Turn off PB0 as interrupt pin
}

Today I measured again without the development board. Just the CPU, same setup otherwise (original code, using the FTDI cable as power source) and I got a reading of about 6-8µA. I guess that answers it! Thanks everyone for your help!


ESP8266 Flash - Maximize SPIFFS size the board i use has 1MB Flash Size. My program however downloads 512K+ of data for processing.

Arduino Options i see are:

Ideally i would like to use 1MB of SPIFFS, is this even possible?

I don't use OTA, and compile with:

To minimise the footprint of the main sketch.

Thanks in advance.

No.

Even if you don't use OTA, your program is stored in flash. If you have 1MB of flash, there's no way you can use all 1MB for SPIFFS; that would leave no space for your program.

Here's a page showing how flash is divided up in an Arduino environment.

Even if you eliminate space for OTA images and the EEPROM, the Arduino environment will still reserve space for the sketch itself and for its wifi config and possibly a little more data.

You can never use 100% of the flash storage for SPIFFS.


Wirelessly communicate between two Arduinos without router I want to "connect" two Arduinos, without using wires. The range is ~0.2 miles (300 meters). Using Google, I saw too many options.

The idea is to build something like a beacon, so the bandwidth can be small. I want to send 32 or 64 bits/second of data (32 bits for the application + 32 bits for checksum if the module does not guarantee consistency of data).
The communication between Arduinos is bi-directional, and I'm looking for something cheaper than 50 US dollars per module.

Can I use a serial WiFi module for this, without using a router? Do you recommend a 2.4GHz module? Or a RF module?

I can highly recommend these cheap little 433Mhz radios.  You can get them on amazon, ebay, etc. and they work pretty well for me. Your distances are a bit longer than my situation but I have to go through several walls.


Reading a tachogenerator I'm trying to read a tachogenerator from a washing machine. It outputs an alternating current, with multiple periods per revolution. The voltage for my test case (constant rpm) reads 5.5V. I attached the tachogenerator to Digital 2 and GND and ran this sketch, just to see if a change is detected:

int ledPin = 13;
volatile int state = LOW;

void setup() {
  pinMode(ledPin, OUTPUT);
  attachInterrupt(0, blink, RISING);
}

void loop() {
  digitalWrite(ledPin, state);
  delay(500);
}

void blink() {
  if (state == LOW) state != state;
}

Unfortunately, the LED does not light when I start the motor. When I measure the voltage while it is connected to the Arduino, it shows only about 0.7V, which would explain why the LED is not reacting. But why is this?

There's an obvious code problem in your blink() function:

state != state;

The above statement will never modify your state variable. The != operator in C/C++ does not perform an assignment (unlike operators such as += and -=). It's a comparison operator which just tests for inequality. You presumably meant to do this:

state = !state;

That may not fix your problem entirely though. You might find that the interrupt doesn't get reliably triggered anyway because it's not designed to handle AC. I'd recommend using an external comparator circuit to generate a clean digital signal, such as a Schmitt trigger.


Creating and Arduino synthesizer without the tone library I am thinking about trying to make an Arduino synthesizer using the true analog output on the Due. However I would like to be able to play multiple notes at the same time on a single buzzer. Is this possible and how would I do it?

You just have to add the waveforms. For example, if you want to play
pure tones (the simplest and most boring timbre), you generate a sine
wave for each of them and add them together:

struct Note {
    float frequency;
    float phase;
    bool is_active;
} notes[MAX_NOTES];

void output_sample()
{
    static uint32_t previous_time;
    uint32_t now = micros();
    uint32_t elapsed_time = now - previous_time;
    previous_time = now;
    float output = 0;
    for (int i = 0; i < MAX_NOTES; i++) {
        Note *note = &notes[i];
        if (note->is_active) {
            output += cos(note->phase);
            note->phase += 2*M_PI*note->frequency*1e-6*elapsed_time;
            if (note->phase >= 2*M_PI) {
                note->phase -= 2*M_PI;
            }
        }
    }
    analogWrite(DAC_PIN, 2048 + round(output * (2047.0 / MAX_NOTES)));
}

The function output_sample() should be called as frequently as
possible. You can change the notes array any time to add, remove or
change notes.

There is some room for optimization here, like:

storing 2*M_PI*note->frequency*1e-6 as the “frequency” in order to
save some calculations
using a wave table instead of the cos() function (I don't know how
good is the Due at transcendental math)
replacing elapsed_time by a constant if you can manage to output the
samples at a fixed rate.

Edit: I wrote “You can change the notes array any time to add,
remove or change notes.” Here is how to start or stop a note, i.e. to
add or remove it from the list of active notes:

// Start a note. Returns an index to be used with stop_note(), or -1 if
// we couldn't start the note because we are already outputting the
// maximum number of simultaneous notes.
int start_note(float frequency)
{
    int i;  // index of the note in the notes[] array

    // Find a free slot in the array.
    for (i = 0; i < MAX_NOTES; i++)
        if (!notes[i].is_active) break;  // found

    // Couldn't find a free slot?
    if (i == MAX_NOTES) return -1;

    // Setup the note parameters.
    notes[i].frequency = frequency;
    notes[i].phase = 0;
    notes[i].is_active = true;
    return i;
}

// Stop the note with the given index.
void stop_note(int index)
{
    if (index >=0 && index < MAX_NOTES)
        notes[index].is_active = false;
}


Lighted geofenced dog collar project help needed I have a project that I would like to make for Christmas and while I have never worked with Arduino before I am hoping people here can point me in the right direction.

I currently have two dogs that like to go out at night a lot. Currently I clip a small LED to their collars when they go out so I can see where they are.

I would like to automate this process by setting up an Arduino system to turn the dog collar lights on and off based on some type of geofencing (either connecting/disconnecting from wifi or bluetooth etc).

I was thinking I would do the following:

Get the smallest Arduino with Wifi.
Write a program that triggers a relay for onConnect? and onDisconnect? events.
Buy a lighted dog collar like this, sew the Arduino into it and hook the relay into the circuit.

What would be really helpful from the group is to know what to buy, and any reference projects that might be helpful on my way. I am a software engineer so I would prefer to stay away from as much custom hardware as possible and get the smallest setup possible for the project pre-made so I can just focus on software.

I am hoping to spend less than $25 per device, but I would pay more for smaller devices.

Thanks all!

I would suggest the following hardware for your project.

https://store.arduino.cc/arduino-mkr1000

It has an integrated wifi module. If a wifi chip is attached to chip manually it will likely loose contact or sometimes be broken during movement.

Here are some tutorials to get you started:

https://www.hackster.io/charifmahmoudi/arduino-mkr1000-getting-started-08bb4a
https://www.pubnub.com/blog/2016-08-23-remotely-configure-your-arduino-mkr1000/
http://platformio.org/lib/show/299/WiFi101

Hope this helps.


Controlling a servo motor with a touch sensor I want to modify my code to move a servo motor only for the duration of time that the sensor is touched and stop moving immediately when the sensor is no longer touched. The code I have moves the sensor from 0 to 90 and back.  That motion is completed even when you remove your finger. I want it to be such that if you remove your finger before the servo reaches 90 degrees the servo stops.  And the servo starts up again toward 90 when touch resumes. This is the code I currently have:

//when signal output is high the sensor is being pressed

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
int pos = 0;    // variable to store the servo position
int sensor=11; //initialises component to arduino digital pins
led=13;

void setup() {
        myservo.attach(9);
        pinMode(led,OUTPUT);
        pinMode(sensor,INPUT);
        Serial.begin(9600);
}

void loop() {

        int value=digitalRead(sensor);
        if(value == HIGH){
                digitalWrite(led, HIGH);
                for (pos = 0; pos <= 90; pos += 1) {
                        myservo.write(pos);              // tell servo to go to position in
                        variable 'pos'
                                delay(15);                       // waits 15ms for the servo to reach the
                        position
                }
                for (pos = 90; pos >= 0; pos -= 1) { // goes from 90 degrees to 0 degrees
                        myservo.write(pos);              // tell servo to go to position in
                        variable 'pos'
                                delay(15);
                }
                Serial.println("TOUCHED ");
        }else{
                digitalWrite(led, LOW);

                Serial.println("NOT TOUCHED ");
                delay(500);
        }
}

To solve your problem, you need to take a tiny step into real time programming.  Most Arduino programs deal with one issue or action at a time.  Your simple twist to interrupt and action "i want it to be such that if you remove your finger before the servo reaches 90 degrees that's where the servo stops" requires you to continuously monitor your input (touch switch) while changing your output (next servo position).

You can go about this 2 ways.  You can use interrupts to inform you when the state of the touch switch changes. This is challenging.  Many find it difficult to conceive of what might happen if their program were to be interrupted at any and all possible points in its execution.  A mistake here can lead to unexpected results.

Or you could take turns polling the state of the touch switch then making a small adjustment in the position of the servo.  When the state of the touch switch changes from active to not-active, exit the loop you are using to change the servo position.


MQTT Arduino add quality of service I'm making a project with MQTT Arduino, but on publish messages i read that it's not possible to publish with qos 1 and 2? It is true? If is not, how can i put qos on publish messages?

What MQTT client are you using?

Paraphrased from the MQTT spec  http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718099

  The MQTT protocol provides three qualities of service for delivering
  messages between clients and servers: "at most once", QOS0; "at least
  once" QOS1; and "exactly once" QOS2. For QOS 1&2: The message must be
  stored locally at the publisher, until the publisher receives
  confirmation that the message has been delivered to the receiver.
  However, for QOS0 there is no storage requirement.

The problem with the Arduino is that there is no large quantity of storage available. If the client is disconnected from the broker while using a QOS of 1 or 2 the client must store the messages until a connection is reestablished and the message transfers are acknowledged. On an Arduino there is no guarantee all the messages can be saved. Consider a sensor node collecting 16-bits (int value) every second. Then supposed the broker goes down over the weekend and a repair person isn’t paid to work on the weekend. That’s two days’ worth of data or 172800 readings or about 1/3 MB (without overhead). The Arduino does not have that much storage.


Ultimate GPS Logger Shield : Soft Serial Sketch Error Im using a OSEPP Uno R3 Plus to connect with a Ultimate GPS Logger Shield. I am currently working through the Adafruit Ultimate GPS Logger Shield pdf. When connecting in Soft Serial Mode and loading a parsing sketch. In the com window my values are showing but unreadable. I have included an image. Any help is appreciated.

jfpoilpret > My apologies for not including enough information and details. But your comments did lead to me resolving my issue. I did not change my baud rate to match the baud rate of the source code and the script is working now. Appreciated.


Arduino delay inside of an Interrupt Using the delay function inside of an ISR is frowned upon when programming in an Arduino. The general response to solve this desire is to design the program to delay in a more cleanly way outside of the interrupt.

My question is simply why. Why does putting a delay() inside of an ISR cause wonky behavior with the Arduino. Whats going on under the hood?

Why is putting a delay() inside of an ISR cause wonky behavior with the Arduino. Whats going on under the hood?

The first problem is that delay() is a busy loop monitoring millis(). The value that millis() returns will not change inside an ISR as interrupts are turned off inside an ISR; this is why ISRs must be as short and fast as possible, or they will interfere with other interupts

So if you call delay() within an ISR your poor AVR is now deadlocked! It is waiting for something to happen that can now never happen.

A second problem is that if your ISR takes too long, you can miss other interrupts; millis() and micros() can miss ticks and become inaccurate!


Arduino not connecting, but running the code I wrote last My Arduino was working fine one day except it wasn't getting enough power, so I grabbed a 12v power supply, and when I plugged it in nothing happened. So I checked the 2 things behind the port that say:
47
25v
VT

with a test light, and somehow the power jumped through it I guess and after that it won't connect but it's still running the last written code. Plz help.

Well you are very unclear about what exactly happened.  I find the statement "somehow power jumped" to be very questionable.  Almost certainly you accidentally touched something with your "probe" and shorted a higher-voltage signal, like your 12V power, to something that cannot tolerate that voltage.
There are many things on the board that fit this from the USB interface chip to the AVR chip itself.  Chances are quite good that you destroyed an input at least.
If you have an Arduino Uno with a socketed AVR chip, you can get a replacement with the bootloader pre-programmed.  Search your favorite search engine for one of these.
Otherwise it's time to buy a new one.  Sorry!


Can I change VCC pin to 3.3V on a 5V Arduino Pro Micro? I'm using a 5V Arduino Pro Micro (schematic).

For my project, I'm using the VCC pin to output power to an external device.  I need VCC to output 3.3V to the external device.  Can I open jumper SJ1 to reduce the voltage of the VCC pin without affecting the operation of the other parts of the unit?

No. If you change the voltage to 3,3 Volt you also have to change the crystal to 8MHz and reprogram the ATmega32u4 to meet the new frequency.


Using I2C to keep track of position of slaves I am trying to flesh out my ideas for an electronics project and this question seems to be the main hangup. Is it possible, in the I2C protocol, to figure out the order in which the slaves are chained to the host? For example if I have 5 arduinos strung together by their serial and clock lines I want the master to be able to see that Arduino 1 is in position 1, Arduino 2 is in position 2... And so on. But if I switch Arduino 1 and 2 I want the master to know that Arduino 1 is in position 2 and Arduino 2 is in position 1.

I assume this isn't possible because all of the arduinos are connected to the same data and clock. So does anyone have any other protocols or algorithms in mind where I could do this. I was thinking I could have one Arduino talk to it's neighbors somehow and waterfall data down the line until it gets to it's destination. But I'm curious to see what y'all come up with.

This is indeed not possible.  I2C was meant for short on-the-same-board communications and though it's sometimes also extended to near-board communications, it still has no facility for position sensing.  Each slave  simply listens for an address and then responds to commands sent for that address.

Slaves can "stretch the clock" to slow down things, but cannot otherwise make themselves known so long as they are not mastering the bus.  In any case, even if bus mastering is assigned round-robin, only presence can be determined, not the position in any chain.


Why are my sensors not working (the reaction time is so slow)? //testing the light sensor;
int sensor=A0; // setting as input is by default;
int sensorval;
int pin=13;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(pin,OUTPUT);
  pinMode(sensor,INPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  sensorval=analogRead(sensor);
  Serial.println(sensorval);
  if(sensorval>900)
    digitalWrite(pin,HIGH);
  else  digitalWrite(pin,LOW);
    delay(1000);
}

I am using a photocell, a temperature sensor and a potentiometer with an Arduino Uno and it always gives me 1023 0 1023 0 1023 0 1023 ....... All my wires are connected properly and I tried all this stuff online and they are working correctly.

Have you tried with a different trimmer?

I dont seem to be able to find any issue with your code or your schematic, so can you please cross verify that the trimmer is not spoilt.

Can you also check if, when A0 is left floating (nothing connected) it give a random value.


Is an atmega 2560 board compatible with the Adafruit Trellis? I want to build a custom midi controller for my computer, and yes, Adafruit has a mini Untz project. For my purposes, I need more analog inputs than the Leonardo, and the only other option I can find is the atmega 2560. Can i use that?

MIDI comes in many different arrangements.

The two most important ones for you are "MIDI Over USB" and "Traditional Serial MIDI".

The former encapsulates MIDI messages and sends them over USB to the computer. This is what you normally get when you plug in a USB-based MIDI instrument, or a USB to MIDI adapter cable.

The latter is a simple serial port running at a specific baud rate. It's generally opto-isolated as well.

On the Leonardo you can do either of those methods (you haven't mentioned which you use), but on the ATMega2560 you can only do the latter (that is, connect the board to a USB to MIDI adaptor cable).  However the Arduino Mega2560 (Note: this is a board, what you talk about is a bare chip) has a USB interface chip that can be re-programmed to look like MIDI.  That will bridge between the "traditional serial MIDI" to the "MIDI over USB". However doing so may impare your ability to program the board.

Another option is to use some PC-based Serial-To-MIDI bridge software which reads normal Serial data as provided by the Arduino and converts it into MIDI signals within your computer.

A third option is to step away from Arduino and choose a board that has both a native USB interface (with MIDI support in software) and more analog inputs.  A board such as one of the Teensy 3.x range would probably suit you well.


Arduino diy wireless Is it possible to do simple wireless on an Arduino, digital, or analog (SDR)? I would like to hook one pin to an antenna (or piece of wire) and generate signals with simple modulations (analog or digital).

here there's a nice tutorial on how to obtain it.

Basically it sets the registers so that a pin outputs a PWM signal at 800 kHz and then modulates that signal in code by just switching the pin and off (pinMode set to INPUT or OUTPUT). If you plug a cable (20 cm and on) to pin 8, and tune your radio to 800Khz you'll hear some noise going on and off.

If you read down the forum you'll see people suggesting how to actually send tones, by putting a very small delay (delay(1)) between the on/off of the pin.

In this link they guys have ogn further and they even implemented a morse code library.

Now I am trying to figure out a way to do the same for a receiver.


Alternative IDE for compiling and running arduino code? I am not super experienced with c++ and I know that the syntax for C++ and the code written/compiled by the arduino IDE are slightly different.

I would like to be able to write code, compile it the same way the arduino IDE does, and run it, without uploading it to a board.

I dont need to test any code that interacts with any hardware. I simply want to be able to test basic syntax to make sure my concepts work before integrating with the full program.

I have written a few Arduino programs and I think the most complicated thing I've used were pointer functions, but I'd like to be able to test out code without needing to upload to a board for every change, while relying on Serial.print.

I have found alternatives that help with debugging and although that is helpful, I'd like to avoid the need to upload to a board every time I want to test changes for basic concepts

You can use any C++ IDE you like, best when bundled with a compiler, for example Code::Blocks. Assuming you're using Windows: A combination of a decent editor like Notepad++ and some good compiler chain like MinGW will do, too. If you absolutely have to you could also use MS Visual Studio, I don't bother.

Then create standard console programs with this main():

void setup();
void loop();

int main()
{
    setup();
    for (;;)
    {
        loop();
    }
}

And append your hardware-less Arduino code.


Arduino Clone - A request for the USB device descriptor failed I was working with my arduino clone and that was working well till last night.
I was trying to add l298p motor shield and after a few times of testing without any achievement, my PC suddenly did not recognize the arduino.
The device status in device manager is :

Windows has stopped this device because it has reported problems. (Code 43)
A request for the USB device descriptor failed.

What should I do now??
My OS is windows 8.1

Solution for semi-bricked Pro Micro/mini-Leonardo clones:

The OP's question is ambiguous to as the exact Arduino device in question. My answer applies to the "Pro Micro" or "mini-Leonardo" since these Clones usually use the default Leonardo boot loader, not the modified Sparkfun version.

Note the the Pro Micro doesn't use an external serial to USB chip at all. So the "CH340T USB" argument doesn't apply here. The USB is directly wired to the ATMEGA chip in this case as it has built-in USB 2.0 support.

I've made two projects with these: I gutted an old keypad replaced with a Pro Micro Clone and turned it into a extended keyboard so I could get F13 to F24 keys plus some others, then a custom game foot controller (to 'Q' and 'E' lean in FPS shooters).

Problem, I went to update my Foot controller sketch and after over a year later I forgot my Arduino IDE settings. This time I must have used the wrong setting like "Sparkfun Pro Micro" 3.3.v 8Mhz when your clone is probably like mine a 5v 16Mhz model.
When I uploaded the sketch it failed and apparently corrupted the program Flash header or something.
The original code was still running (on pedal press my LED lit up) but the device now showed up as "..missing USB device descriptor.." type message in the Windows device manager.

Fear not, it's probably recoverable like it was for me.
First of all realize you DON'T set in the Arduino IDE the board to "Spark Fun Pro Micro", simply set it to the default "Arduino Leonardo".
That's the right board setting for these clones. The Sparkfun bootloader IS different, as it says on their site. If you uploaded their bootloader then it might work but that's an experiment for another time.

Now you will need to add a reset button to the right hand side of your board (with the micro USB plug pointing up). The pins are next to each other and are clearly labeled.
I found a mini-switch just right to fit into the header pins from my parts box. In a pinch you can probably solder two small insulated stripped wires as a makeshift switch, but it might make the following step harder which is timing related.

If you plug your Clone Micro back in, notice if you press the switch the Clone Micro will show back up as a Arduino Leonardo on a COM port for about 8 seconds, then fall back to the bad USB ID thing again.

Now in your Arduino IDE create a NEW sketch. Which will create a minimal program that you'll need to restore your Clone back to working order.
Hit the reset switch again and quickly in your IDE preset the "port" to the COM port that shows up. Don't worry it will remember it after the device falls back again.

Now comes the hard part. Unlike a real Sparkfun Micro you can't double tap the reset button for extra time, you only get the 8 seconds period.
In the IDE click the "Upload" button, wait about a second, then hit your reset button.
If all goes well, you will see the typical flashing programming LED success lights and you will have restored your Clone Micro! This might take a few tries depending on your timing.
The thing is to press your reset button slightly after you click the Upload button (or CTRL-U) else you will miss the time frame of the special bootloader reset phase.

Basically this is the directions given here, with a little more details:
https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide#troubleshooting-and-faq

The OP got some opinionated and pretty toxic responses for an open-source hardware device. Some common sense notes on the morality and ethics of buying Chinese clone devices:

First of all, at least this is not nearly as bad a situation of the Chinese fake chips, arguably the real scourge of the Electronics parts world.

Without spending too much time on the legal ramifications and not being a lawyer, it looks like most of the Sparkfun stuff is CC licensed. Although doubtful the license if for their original or modified software/firmware.

From the Arduino site:
"Arduino is an open-source hardware and software company". So the clones are apparently not illegal to buy in the USA (if this is the country of contention).

The reason a lot of people buy the clones is you can buy around three or more of them for the same price of just one Sparkfun Micro.
I've been an electronic hobbyist since the late 70's and part of the equation for me is getting a few extras because there is always that chance I'll fry something despite double if not triple checking my wiring.
I can make a project plus have some spares for the next time.

I wouldn't use it in anything mission critical, but so far the Clone has been working fine for me as a hobbyist.

These things being said, I'm a big fan of Sparkfun. They are a relatively small USA company that makes fun innovative products with helpful Youtube "how too" videos, etc. I'm all for supporting them.


How is a local variable address retrieved/returned inside the CPU of Arduino? How is the address of a local variable retrieved in Arduino's ATMEGA328 micro-controller?

Lets say somewhere inside the main we have lines as:

int x = 5; //a variable declared and value of 5 stored in SRAM ??
int  *p; // a pointer is declared
p = &x; // p holds the address of the variable x

What happens above is &x retrieves the address of the variable x.

But how does this happen in a lower level?
Which function retrieves the address of a variable and how does it do it?
How does that function know the address of the variable x?
I'm wondering what happens step by step after the instruction comes to the instruction register.

edit: Another question for int x = 5; is 5 stored at CPU register or SRAM?
.

Just as an experiment, I tried the following:

void bar(int *);

void foo()
{
    int x = 5;
    int *p;
    p = &x;
    bar(p);
}

And here is what gcc translated that into (comments mine):

__SP_H__ = 0x3e
__SP_L__ = 0x3d
__tmp_reg__ = 0
foo:
    push r28            ; save r28
    push r29            ; save r29
    rcall .             ; make room on the stack
    in   r28, __SP_L__  ; copy SP into r29:r28 = Y: LSB...
    in   r29, __SP_H__  ; ... and MSB
    ldi  r24, lo8(5)    ; store x in a register: LSB...
    ldi  r25, 0         ; ... and MSB
    std  Y+2, r25       ; copy x into the stack: MSB
    std  Y+1, r24       ; ... and LSB
    movw r24, r28       ; r25:r24 = Y
    adiw r24, 1         ; r25:r24 = Y+1 = &x
    call bar            ; call bar(&x);
    pop  __tmp_reg__    ; release the two bytes...
    pop  __tmp_reg__    ; ... of stack space
    pop  r29            ; restore r29
    pop  r28            ; restore r28
    ret                 ; return

Expanded comments:

The instruction rcall is normally used to call another function. Here
it's calling the following instruction, so it doesn't affect the program
flow. It's only a trick: as rcall saves the return address into the
stack, it makes the stack grow by two bytes, and is used here as an
optimized way of reserving to bytes of stack space for storing x.

Next you see the stack pointer being copied into the r29:r28 register
pair, also known as “Y pointer”. The stack pointer is a CPU register
holding the address of the top of the stack, namely of the first free
slot. As the stack grows towards the bottom of the RAM, at this point
it looks like this:

address | SP = Y | Y+1 | Y+2  | Y+3 | Y+4 | Y+5  |  Y+6  |...
--------------------------------------------------------------
data    | (free) | room for x |  saved Y  | return addr. | ...

Next you see the value of x being placed first in a register pair
(r25:r24), then on the stack at the addresses Y+1 and Y+2.

The instruction mowv copies a register pair, so now you have a copy of
the stack pointer in the pair r25:r24. The instruction adiw adds an
immediate value (here, 1) to a register pair, so that now r25:r24 holds
the address of x. Finally, the function bar() is called: per the
calling convention, the argument is to be passed in the r25:r24 pair.

A few final remarks:

I passed the pointer to another function just to make gcc believe that
I am actually using that pointer, otherwise it would optimize out
the whole code into a function that does noting but return.
You don't need to create a pointer variable to hold the address of
x: calling just bar(&x) compiles into the very same assembly.
Most local variables are assigned to CPU registers. Only because I am
using the address of x did this variable get stored in the stack.
The compiler output is very sensitive to the surrounding code, the
compiler version, the optimization options, and so on. So you should
consider all this as only an example.
If you do not completely understand what each instruction is doing,
you should now take a look at the AVR Instruction Set Manual


ESP32 servo runs continuous I have ESP32 connected to TZT servo SG90.
This is the code
#include <ESP32Servo.h>
#define TURN_TIME 175

Servo myservo;  // create servo object to control a servo
// 16 servo objects can be created on the ESP32

int pos = 0;    // variable to store the servo position
// Recommended PWM GPIO pins on the ESP32 include 2,4,12-19,21-23,25-27,32-33
#define servoPin  17
#define MOTOR_1_PIN 22

void setup() {
  pinMode(servoPin, OUTPUT);
  Serial.begin(9600);
    // Allow allocation of all timers
    ESP32PWM::allocateTimer(0);
    ESP32PWM::allocateTimer(1);
    ESP32PWM::allocateTimer(2);
    ESP32PWM::allocateTimer(3);
    myservo.setPeriodHertz(50);    // standard 50 hz servo
    // using default min/max of 1000us and 2000us
    // different servos may require different min/max settings
    // for an accurate 0 to 180 sweep
}

void loop() {

  myservo.attach(servoPin, 700, 2500); // attaches the servo on pin 18 to the servo object
  myservo.write(0);
  delay(TURN_TIME);
  for(int i =0; i<180; i++)
  {
    myservo.write(i);
    delay(TURN_TIME);
  }
  delay(3000);
  for(int i =180; i>0; i--)
  {
    myservo.write(i);
    delay(TURN_TIME);
  }
  myservo.detach();
  delay(3000);

}

My servo starts rotating one way and reverse for few degrees, then after 5 seconds the servo starts rotating at one way forever..
I had no problems with arduino and nodemcu board. What should I change in the code?
EDIT: I have connected the servo with battery, they have common ground.
The pin on esp32 that I am using is G17. "#define servoPin 17" in the code

I used other servo library and it worked.. Then i changed the pulse width with this line of code.
The default is 1000-2000. But it rotates only 95 degrees. When it's pushed to around ~2850us the servo rotates up to 181-185 degrees.
servo1.attach(servoPin,CHANNEL_NOT_ATTACHED, 0,180,544,2840/);
#include <Servo_ESP32.h>

static const int servoPin = 16; //printed G14 on the board
int delayTime = 20;
Servo_ESP32 servo1;

int angle =0;
int angleStep = 5;

int angleMin =0;
int angleMax = 180;
#define CHANNEL_NOT_ATTACHED -1
void setup() {
    Serial.begin(115200);
    servo1.attach(servoPin,CHANNEL_NOT_ATTACHED, 0,180,544,2840/);

}

void loop() {
    for(int angle = 0; angle <= angleMax; angle +=angleStep) {
        servo1.write(angle);
        Serial.println(angle);
        delay(delayTime);
    }

    for(int angle = 180; angle >= angleMin; angle -=angleStep) {
        servo1.write(angle);
        Serial.println(angle);
        delay(delayTime);
    }
}


Can't understand this codes process void loop()
    {
    if ( Serial.available() > 0 )
      {
    static char input[inputLength];

    static uint16_t i;

    char c = Serial.read();

    if ( c != '\n')
      input[i++] = c;

    else
    {
      input[i] = '\0';
      i = 0;

      uint16_t array[80];
      uint16_t j = 0;

      if ( !strncmp(input, "SEND", 4) )
      {
        char* p = input + 4;

        while ( (p = strchr(p, ' ')) != NULL )
          array[j++] = strtol(p, &p, 16);

        ir_start(array);
        Serial.println("WURKS");
      }
    }
  }
}

Hello I can't seem to figure out what this code is doing. I know the main goal but I can't figure out the proccess. If someone could please make the code dumber for me I would appreciate it :). Full code is here since its hard to copy code: https://anonfiles.com/z6ldWff0pf/no_lib_ino

It's easier to follow if you indent it properly. I'll do that, and add comments as I go:
void loop() {
    if ( Serial.available() > 0 ) { // If there is something in the serial RX buffer

        static char input[inputLength]; // Create a working string to store data in
        static uint16_t i; // This is the current index in that working string

        char c = Serial.read(); // Read the next character from serial

        if ( c != '\n') // If it's not a "line feed" character...
            input[i++] = c; // then store it in the input string and increment i

        else { // Otherwise...

            input[i] = '\0'; // Terminate the string with a NULL to make it valid C
            i = 0; // Reset the index to 0 ready for next time

            uint16_t array[80]; // Create an 80-int array (temporary)
            uint16_t j = 0; // And an index variable

            if ( !strncmp(input, "SEND", 4) ) { // If the string starts with SEND
                char* p = input + 4; // create a "pointer" to the string that starts 4 characters in

                while ( (p = strchr(p, ' ')) != NULL ) // While there is a space somewhere in the string
                    array[j++] = strtol(p, &p, 16); // convert the first portion to a number, store it in the array, and advance the pointer to the next space.

                ir_start(array); // Send the array through IR
                Serial.println("WURKS"); // Tell us it worked
            }
        }
    }
}

So you see it receives data through serial and stores it, byte by byte, in input until it receives \n at which point it looks to see if it starts with SEND, then effectively "cuts off" the SEND by only considering everything after the SEND. Then it slices the remainder of the string up by looking for the next space each time and convert each portion to an integer which it stores in an array.
It then sends that array.


Open video file if sensor reaches certain threshold value I am an ABSOLUTE beginner at Arduino and my first project I've proposed to my teacher is as follows: an Mq-2 smoke sensor will sense smoke and if the level of smoke reaches a certain value (only because I want the smoke to accumulate for aesthetics purposes) then a video file in whatever directory opens and plays. It seemed plausible at first, but as I search for pertinent info., I am faced with content and hobbyists whose instructions and "knowledge" are way out of my depth. Can anyone help me with this? If anyone knows a good website/tutorial videos/documents/books that a beginner like me should take to improve his programming and physical computing(?) skills, please let me know!

What I'm thinking is that you could make a conditional statement. Below is a little a bit of pseudo code on how to possibly open said video from an SD card because there's no way Arduino would be able to store a video on it's own, let alone play good quality videos:

int dangerLevel = 500 (or however the shield reads the smoke level)

int smokeDetectorPin = A0

setup:

smokeDetected = analogRead(smokeDetectorPin)

loop:

if smokeDetected >= dangerLevel:

open video from SD card directory or computer.

So in order to get a "video" from the SD card, you should check this website. Like I mentioned before, this is really primitive and it's probably not what you're looking for.

I found something very interest about the Arduino that I never knew you could do before and using composite display from a TV. Interesting and you can find that info here.

And lastly, to get a video from your computer or laptop, there's really no easy way. However, I did find two solutions that might be able to do this. First of all, and this may sound ironic since we're on an Arduino Stackexchange, you could use a Raspberry Pi (and this is the easily solution I can think of) though I believe your instructor prefers if you use the Arduino instead. Second, and this took me forever to find on the internet, you could use a third party software called "Gobetwino" and you can check out what that does here. I saw on YouTube video of a quick little demonstration of what it does. When the button is pressed, the video is played. That's conditional and you can do the same thing but for the smoke detector.


How to expand an Arduino when using a TFT display shield? I am really new to this Arduino stuff. I can't figure out one of my problems on my own.

I am using this 2.4 TFT display shield on an Arduino Uno. It works fine so far: I have coded a little sketch for it that displays a start button and after tapping that it shows random colors.

Now I would like to connect a circuit with jumper cables that are used as sensors. When I touch one of the jumper cables the light connected will turn on.

The problem I have now is that this specific circuit is using an other Arduino because my first Arduino is already 'full' because the TFT shield is taking up all pins.

How can I resolve my problem? Is it possible to Stack Arduinos? Is it possible to connect those Arduinos somehow? Thanks in advance!

As I can read your link, the shield is using D2-D8 and A0-A3, leaving some pins unused. So some Arduino pins are still free to use, just the shield is in the way to get connected there.

So there are some possible ways:

brutally solder some wires to the shield unused pins from front side and use that wires to connect where you want (sensors, breadboard, universal PCB, ...)
brutally solder some wires to arduino bottom on unused pins, then continue as mentioned
create intermediate shield (there are many, which allow you connect to arduinou on bottom and stack antother shield on top, draw your wires from there (and maybe even put some circuities on the middle shield, if you want
(something like this https://www.aliexpress.com/item/UNO-Prototype-DIY-shield-kit-for-Arduino-UNO-Universal-Extend-Board-UM-UNO/32555004112.html or any "arduino universal shield"

https://www.indiegogo.com/projects/ardushield-most-universal-shield-for-arduino-ever#/ works excelently across arduinos and other shields/breadboards ...

or anything along this lines ... http://shieldlist.org/sunhayato/universal

use pins D10-D13 as they are connected also to ISP header https://www.arduino.cc/en/Tutorial/ArduinoISP and could be connected from there. As they are part of SPI interface
https://www.arduino.cc/en/Reference/SPI that could be good coise too (if you manage ChipSelect somehow.

As for other part of question -
It is possible to connect more arduinos, there are so much different ways, that it is hard to write here all - choose one, that would suit you best. (anyway you would need some access to some pins anyway )


Would an Arduino Uno be suitable for a simple time-based locking circuit? Background: I'm looking to start on my first real electronics project and I have an Arduino Uno I bought a while back. I've only done a few of the starter Arduino tutorials and that was a while back as well. Starting from very little electronics knowledge, I'm trying to get a bit of advice on how to tackle my first project.
TL;DR: I have an Arduino Uno but very little experience with it or electronics.

Project: I want an object that locks, I want the duration of the time it stays locked for to increase by ~1-3% every time it locks. I want to put my nicotine products in there to gradually pull myself off nicotine. I have designed a rough 3D model of the box, which I can 3D print so now I'm looking at the electronics.
TL;DR: A box which stays locked for longer, every time it locks.

Electronics: A microcontroller/Arduino/Pi to increase the locking duration; a locking circuit and some form of power supply.

My 2 questions are

Would the Arduino Uno be suited to this type of project?
What sort of components should I be looking for for the locking circuit and power supply (I'm thinking some sort of solenoid actuator and a battery pack)?

It is a great occasion to use the Arduino!

There are many tutorials for the Arduino out there, so thats a good place to start. This forum is a good place to ask any Arduino related question if you need to do so.

The following contains MY OPINION

In my opinion, an Arduino Nano would be great for this project. It is really user friendly and can pretty much accomplish many things. A Pro Mini would be better, but seeing sa you're a beginner, stick with the Nano.

A good long lasting batteRY would be a simple USB power bank. It outputs 5V and has a lot of juice. For a locking circuit, a simple servo would work IF THE THINGS THAT IS IN THAT "SAFE" ISN'T 1M $$. A servo does a decent job as a lock.

Good luck!


Arduino with HC-05 Bluetooth Module | No data will be transmitted I've got an Arduino Uno (Elegoo R3) and a Hc-05 bluetooth module. First of all i want to send data with an android app (Bluetooth terminal) to the Arduino and turn pin 13 (LED) on.
My Arduino code:
#include <SoftwareSerial.h>

int state = 0;

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

  pinMode(13, OUTPUT);
}

void loop() {
  if (Serial.available() > 0) {
    state = Serial.read();

    if (state == '1') {
      Serial.println("Turned on LED");

      digitalWrite(13, HIGH);
    }

    if (state == '0') {
      Serial.println("Turned off LED");

      digitalWrite(13, LOW);
    }
  }
}

The RX and TX pins I have hooked up with the HC-05 but if I connect my smartphone with the HC-05 and type in a 1 or a 0 nothing happens. If I type a 1 or a 0 in my serial monitor on my computer (hooked up via usb to my arduino) it turns the LED on/off. The RX and TX lights also flashes one time. The bluetooth terminal app recognises all what was sent via serial monitor on pc and displays it in the app. But if I type something in the app, it won't flip the LED or show me some "Turned off LED" or "Turned on LED".
I also tried different apps from the PlayStore but all of them didn't work.
Does someone has an idea how I could fix this? Thank you for your answers.
EDIT: A drawing how my Arduino is connected to my HC-05 https://imgur.com/a/FtUz5So

The TX signal coming from either the Arduino or HC-05 should be
connected to the RX of the other as I understand it, because both are
labeled from the perspective of their respective chips

Like @timemage already said, I connected TX with TX and RX with RX but this is wrong. The solution was to plug TX (Arduino) with RX (HC-05) and RX (Arduino) with TX (HC-05).
Thank you for your help. :)


analogRead() inside a loop always returns 0 I wrote Arduino code to receive analog input from different voltage dividers connected to four pins (A0 to A4) and analog input from a temperature sensor (LM35) to A5. analogRead inside the for loop always returns zero whereas analogRead outside the for loop returns correct values.

What has to be changed to get correct values?

int time=0,y=0;
float volt;
String str;
int countParallel=0;
float voltage[]={0,0,0,0};
float temperature=0;
int sensors_pin[]={A1,A2,A3,A4,A5};
String x="";

// the setup rouontine runs once when you press reset;
void setup() {
  pinMode(2,OUTPUT);
  pinMode(3,OUTPUT);
  pinMode(4,OUTPUT);
  pinMode(5,OUTPUT);
  pinMode(6,OUTPUT);
  pinMode(7,OUTPUT);
  Serial.begin(9600);
  Serial.setTimeout(50);
}

// the loop routine runs over and over again forever;
void loop() {
  Serial.println(analogRead(A5)*500/1023);
  delay(1000);
  while (Serial.available() > 0) {
    int inChar = Serial.read();
    if (isDigit(inChar)) {
      x += (char)inChar;
    }
  }
  // Parallel Disharging
  //  Serial.println(x);
  if(x.toInt()==1) {
    digitalWrite(13,HIGH);
    if(countParallel<1) {
      digitalWrite(6, HIGH);
      digitalWrite(7, HIGH);
      countParallel++;
    }
   for(int i=1,x=14;i<=5;i++,x++) {
    if(i<4) {
      Serial.println(analogRead(x)*(5/1023));
      delay(100);
    } else if(i==5) {
      Serial.println(analogRead(x) * p(500/1023));
      delay(100);
    }
    if(volt<2.8){
     digitalWrite(i+1,HIGH);
   } else if(temperature>40) {
     digitalWrite(2,HIGH);
     digitalWrite(3,HIGH);
     digitalWrite(4,HIGH);
     digitalWrite(5,HIGH);
    }
  }
}

// Series Discharge
if(x.toInt()==2){
    for(int i=A0;i<=A4;i++){
      if(i<A4) {
        voltage[i] = analogRead(sensors_pin[i]) * (5/1023);
        Serial.println(10);
        delay(100);
      } else if(i==A4) {
        temperature = analogRead(sensors_pin[i])*(500/1023);
        Serial.println(9);
        delay(100);
      }
      if(volt<2.8) {
        digitalWrite(i, HIGH);
        delay(100);
      } else if(temperature>40) {
        digitalWrite(2,HIGH);
        digitalWrite(3,HIGH);
        digitalWrite(4,HIGH);
        digitalWrite(5,HIGH);
      }
     }
  }
}

voltage[i]=analogRead(sensors_pin[i])*(5/1023)

Is equivalent to

voltage[i]= analogRead(sensors_pin[i])*0
          = 0;

You are using an integer division, not a floating point divsion. 5 / 1023 evaluates to 0, 5.0f / 1023 evalues to 0.00488... You have repeated this error throughout your lower loop code, which is why you're only getting 0.

In your outer loop you printed it as

Serial.println(analogRead(A5)*500/1023);

Which will first multiply by 500, then divide by 1023, which works. But since you put the above expression in parenthesis, it was first evaluated.


Arduino NANO hardware SPI not working I have an Arduino NANO clone and a 2.4" ILI9341 TFT display.  The VCC and LCD pins of the display are connected to the 5V pin of the board.  The GND to the GND.  All the logic pins are connected to voltage dividers (2k2 and 4k3 resistors), their connections checked and delivering 3.3V when 5V is supplied to them.

If I understand the source correctly, if I specify all the pins to the constructor, then I use software SPI, but if I don't, then I use hardware SPI.

Now, if I use the software SPI, everything is working fine, I can get the info, I can draw, etc.  However if I use the hardware SPI then it is not giving me anything.

#include <Adafruit_GFX.h>
#include <Adafruit_ILI9341.h>

// Adafruit_ILI9341 tft = Adafruit_ILI9341(10, 9);              // NOT WORKING!
Adafruit_ILI9341 tft = Adafruit_ILI9341(10, 9, 11, 13, 8, 12);  // WORKING!

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

    Serial.println("ILI9341 Test!");

    tft.begin();

    // read diagnostics (optional but can help debug problems)
    uint8_t x = tft.readcommand8(ILI9341_RDMODE);
    Serial.print("Display Power Mode: 0x"); Serial.println(x, HEX);
    x = tft.readcommand8(ILI9341_RDMADCTL);
    Serial.print("MADCTL Mode: 0x"); Serial.println(x, HEX);
    x = tft.readcommand8(ILI9341_RDPIXFMT);
    Serial.print("Pixel Format: 0x"); Serial.println(x, HEX);
    x = tft.readcommand8(ILI9341_RDIMGFMT);
    Serial.print("Image Format: 0x"); Serial.println(x, HEX);
    x = tft.readcommand8(ILI9341_RDSELFDIAG);
    Serial.print("Self Diagnostic: 0x"); Serial.println(x, HEX);
}

void
loop()
{
    // pass
}

However, what really makes me totally confused is when I use the SD card reader with the SD Library alone (the SD card reader is on the ILI9341 board), then that is working fine as well (as if the hardware SPI would be working, unless the SD Library is switching to software SPI magically).  Anyway, the following is the working code:

#include <SD.h>
#include <SPI.h>

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

    Serial.println("ILI9341 Test!");

    if (!SD.begin(7))
    {
        Serial.println("Cannot initialise SD card");
        while (true);
    }

    File file;

    if ((file = SD.open("file.txt", FILE_WRITE)))
    {
        Serial.print("Writing to file...");
        file.println("Hello, World!");
        file.close();
        Serial.println(" DONE");
    }
    else
        Serial.println("Cannot open file for writing");

    if ((file = SD.open("file.txt")))
    {
        Serial.println("Opening file...");
        while (file.available())
            Serial.write(file.read());
        file.close();
        Serial.println("DONE");
    }
    else
        Serial.println("Cannot open file for reading");
}

void
loop()
{
    // pass
}

So what exactly is going on here?  Am I doing something obviously wrong?  Or is the board's hardware SPI not working?  Or is there a problem with the Adafruit library?

Extra info:

I'm using the arduino-cli to upload sketches the following ways:

# To compile:
arduino-cli                                     \
    compile                                     \
    --fqbn arduino:avr:nano:cpu=atmega328old    \
    --warnings all                              \
    MyArduinoSketch;

# To upload
sudo arduino-cli                                \
     upload                                     \
     --verify                                   \
     --verbose                                  \
     --port /dev/ttyUSB0                        \
     --fqbn arduino:avr:nano:cpu=atmega328old   \
     MyArduinoSketch;

I installed the mentioned libraries via arduino-cli.

Use constructor Adafruit_ILI9341(10, 9, 8); to make the reset that works with software SPI.

To SD card as second device on the bus:

Every SPI device on SPI bus must be controlled by slave select pin. If a device is connected to the bus and the SS pin is left floating the device disturbs the bus.

The empty SD card adapter is not a device on the bus, only the inserted card is a device. If it is on the bus the corresponding SS pin must be set HIGH. If you use the SD libray SD.begin(SD_SS_PIN), the library initializes the pin. If you don't use the library in the sketch (because it takes much memory), remove the SD card or set the SS pin to OUTPUT and HIGH.


Rc switch library display received values only one times using serial monitor I use Rc switch library to transmit and receive data. It works fine.
The part that sends the data is as follows :
#include <Arduino.h>
#include <RCSwitch.h>

RCSwitch transmitter = RCSwitch();

void setup()
{
    Serial.begin(9600);
    transmitter.enableTransmit(10);
}

void loop()
{
    /* Send data in binary */

    // Go right
    transmitter.send("010101010101010100000011");
    delay(1000);

    // Go left
    transmitter.send("010101010101010100001100");
    delay(1000);
}

And the receiving part is like this:
#include <RCSwitch.h>

RCSwitch receiver = RCSwitch();
int rightLED = 4;
int leftLED = 7;
unsigned long receivedValue;
unsigned long goRight = 5592323;
unsigned long goLeft = 5592332;

void setup()
{
    Serial.begin(9600);
    receiver.enableReceive(0); // Receiver on interrupt 0
    pinMode(rightLED, OUTPUT);
    pinMode(leftLED, OUTPUT);
}

void moveRight()
{
    Serial.println("I'm going right");
}

void moveLeft()
{
    Serial.println("I'm going left");
}

void loop()
{
    if (receiver.available())
    {
        receivedValue = receiver.getReceivedValue();
        if (receivedValue == goRight)
        {
            moveRight();
        }
        if (receivedValue == goLeft)
        {
            moveLeft();
        }
        receiver.resetAvailable();
    }
}

The problem is, when I open a serial monitor and look the output of the received values moveRight and moveLeft functions are called multiple times.
I'm going right
I'm going right
I'm going right
I'm going right
I'm going left
I'm going left
I'm going left
I'm going left
I'm going right
I'm going right
I'm going right
I'm going right

What kind of change should I do in the receiver part so that moveRight and moveLeft functions are called only once.
I'm going right
I'm going left
I'm going right

You can save the previous received value, and only print if it is different from what you just received.
Something like this:
// near the top
const int rightLED = 4;
const int leftLED = 7;
const unsigned long goRight = 5592323;
const unsigned long goLeft = 5592332;

// to hold the state
unsigned long previousValue = 0;

// ...

// loop code
void loop()
{
  if (receiver.available())
  {
    unsigned long receivedValue = receiver.getReceivedValue();
    if (receivedValue != previousValue) {
      // something changed
      if (receivedValue == goRight)
      {
        moveRight();
      }
      if (receivedValue == goLeft)
      {
        moveLeft();
      }
      // remember the current value
      previousValue = receivedValue;
    }
    receiver.resetAvailable();
  }
}


Using VS1838B with Arduino I just bought VS1838B IR module (from here) and I’m trying to make it work. Below you can find the circuit to see how I have connected the 1838B IR receiver:

My Code (Here) :
#include <IRremote.h>

int RECV_PIN = 2;
IRrecv irrecv(RECV_PIN);
decode_results results;
#define CH1 0xFFA25D
#define CH 0xFF629D
#define CH2 0xFFE21D
...
#define BUTON8 0xFF4AB5
#define BUTON9 0xFF52AD

void setup()

{

 Serial.begin(9600);

 irrecv.enableIRIn();

}

void loop() {

 if (irrecv.decode(&results))
  {

 if (results.value == CH1)

 {

 Serial.println("CH-");
 }

 if (results.value == CH)

 {

 Serial.println("CH");

 }

 if (results.value == CH2)

 {

 Serial.println("CH+");

 }

 ...

 if (results.value == BUTON8)

 {

 Serial.println("BUTON8");

 }
if (results.value == BUTON9)

 {

 Serial.println("BUTON9");

 }
 irrecv.resume();

 }

}

But I'm not getting any output from Serial Monitor.
Can you help me for debugging it?

Looking further here

http://forum.arduino.cc/index.php/topic,188236.0.h...

I found the following

"Removing
the files - libraries\RobotIRremote\IRremoteTools.cpp and
libraries\RobotIRremote\IRremoteTools.h solved the problem. They are
example files which somehow are getting included. You can move those two
files to some other location as backup."

I went to my libraries
file and did this and can confirm that the example given above then
compiles fine without downloading a new library. Its an Arduino
libraries problem .

Either way will work

answer from here and worked for me

i use this code:

#include <IRremote.h>
int input_pin = 10; //set D10 as input signal pin
IRrecv irrecv(input_pin);
decode_results signals;
void setup()
{
    Serial.begin(9600);
    irrecv.enableIRIn(); // enable input from IR receiver
}
void loop() {
if (irrecv.decode(&signals)) {
        Serial.println(signals.value, HEX);
        irrecv.resume(); // get the next signal
    }
}


Arduino Due vs Mega 2560 What can an Arduino Due do that a Mega 2560 can't? What can a Mega 2560 do that a Due can't? I've heard the Due is 3.3V so it can't work with most shields.

The 'R3' version boards and shields are compatible with 3.3V and 5V. For example the Ethernet Shield V1 version 'R3' can be used with the Due. The new Arduino Ethernet Shield 2 is also compatible with the Due.
Many older shield are not compatible with the Due, but do you really need to use an old shield ?

Most sensors are 3.3V, and also a SD memory card is 3.3V. That is a lot easer with the Arduino Due which runs at 3.3V.

The Arduino Mega 2560 board is the only board with 10k pullup resistors at SDA and SCL, therefor it has a 5V I2C bus. When a 3.3V sensor with I2C is used, you need a I2C level shifter. When a 3.3V with SPI is used, you need more hardware.

The Arduino Mega pins can drive more than 20mA, it can be used to drive 10 leds with 20mA simultaneously, the Arduino Due can't do that.

My suggestion is to use an Arduino Uno for all kind of testing. It's always good to have one lying around. Start with an Arduino Uno if you want to learn programming and have fun with leds and buttons.

The Arduino Zero or MKRzero or M0 have a M0+ processor at 3.3V and they can be used for all kind of nice projects. When you already know a little about programming and electronics, this is a very good choice.

The Arduino Due has more processing power then the M0+.

The Arduino Mega 2560 is still used, because there are many libraries and shields that are compatible with the Arduino Mega 2560.


Arduino Uno - combined LCD and keypad interfacing problem I have a problem with the Arduino Uno.

I need to use a 4x3 keypad and 16x2 LCD together with an Arduino Uno. As 4x3 keypad requires 7 pins, I have defined pins 2, 3, 4, 5, 6, 7 and 8 to it. A 16x2 LCD requires 6 pins but only 5 pins remain (9, 10, 11, 12 and 13). Pins 0 and 1 are used for serial.

Please suggest a probable solution.

You could use a shift register to read the switches as outlined by the excellent tutorial Parallel to Serial Shifting-In with a CD4021BE. Quoting the summary:

  Sometimes you'll end up needing more digital input than the 13 pins on
  your Arduino board can readily handle. Using a parallel to serial
  shift register allows you collect information from 8 or more switches
  while only using 3 of the pins on your Arduino.

So you would only use 3 pins to read the seven switches, which would leave you with 9 pins to play with, for the LCD.

In addition, you could use a similar method for the LCD, using a shift-out register, and use just 3 pins for the 6 inputs of the LCD. A tutorial for that is Alphanumeric LCD with Shift Register on Arduino – part 1, using the AlphaLCD library or 3-Wire Serial LCD using a Shift Register, which has no library, but provides code.

This would leave you with 6 pins free (out of the total 12 pins, if you exclude pins 0 and 1 for serial), after both the switches and LCD are wired up.

Of course, this solution requires you to purchase one or two shift (in and/or out) registers.

The Arduino IDE may come with a built-in library that use shift registers, but I am not sure about that. Maybe someone can confirm, or refute, this?

I hope that this helps.


NodeMCU does not connect to wifi I'm trying to connect my nodeMCU to my WiFi network but it keeps printing ........ which means is not connecting to the network. Here is my code used to connect to WiFi. Any reason why it isn't connecting to WiFi network?.

#include <ESP8266WiFi.h>

        // Replace these with your WiFi network settings
        const char* ssid = "******"; //replace this with your WiFi network name
        const char* password = "******"; //replace this with your WiFi network password

        void setup()
        {
          delay(1000);
          Serial.begin(57600);

          WiFi.begin(ssid, password);

          Serial.println();
          Serial.print("Connecting");
          while (WiFi.status() != WL_CONNECTED)
          {
            delay(500);
            Serial.print(".");
          }

          Serial.println("success!");
          Serial.print("IP Address is: ");
          Serial.println(WiFi.localIP());
        }

        void loop() {
        }

If your WiFi network doesn't have DHCP, then you must set the IP addresses

example:

  IPAddress ip(192, 168, 1, 8);
  IPAddress gw(192, 168, 1, 1);
  IPAddress sn(255, 255, 255, 0);
  WiFi.config(ip, gw, sn, gw);

gw is gateway. the last parmeter is dns server's IP. sn is subnet mask.


Windows stops recognizing Arduinos I've just got my first Arduino Pro Mini and a USB to TTL chip. When I try to upload the program I get the message The uploader process failed followed by

avrdude: ser_open(): can't open device "\\.\COM6": Access is denied.

and a bunch of lines like

avrdude: ser_drain(): read error: The device does not recognize the command.
avrdude: ser_send(): write error: sorry no info avail
avrdude: ser_recv(): read error: The device does not recognize the command.
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x48
avrdude: ser_send(): write error: sorry no info avail

with 10 attempts after which nothing comes from avrdude and I can't upload nor get Arduino's visible in port choice menu all the time until the Windows 7 boots again. I can upload to my Arduino Uno with no problems before I try the ttl chip. TTL chip also shows up in the port menu before trying to upload, with correct name next to the port number. I installed drivers I found on a official site that sells the chip that looks just the same as mine, before I did that it wouldn't show up in the port choice menu at all. Is there any way to reset whatever it is that is preventing me from uploading to Arduinos so I don't have to restart my computer every time it happens? I managed to upload one program to the Arduino Pro and it's working fine but after a couple of hours, when I tried again, it didn't work. Maybe it would be of some use to say that I left my pc on sleep with the TTL chip plugged in and powered by the usb. My guess is that this chip is defective and was near it's life end when I uploaded so now it's just confusing the driver to the point where Windows decides to block the driver for the session.

After a couple of hours I figured out what was happening so I will write all my analysis here for anyone having some of my problems.

First, a list of my components:

-USB TTL ship, used to upload programs to Arduino Pro. The one on the picture on instructables dot com /id/Usb-to-SerialTTL-adapter/, and used that driver.

-Arduino Pro. Chinese copy, red board just like Sparkfun's. 328p chip @ 5V = 16mhz.

-A board very similar to this one. It has a chip with FT232 written on it, also FTDI in bold letters.

The big USB TTL pcb I was using has 5 output pins: 3v3, 5v, TX, RX, GND. Turns out this is not enough to program Arduino Pro as you need one more pin. If you don't connect this pin, avrdude just gets stuck after opening the COM port and waits indefinitely/until you kill the process. To even be able to see this USB TTL chip in Windows, you need to download a driver from the website(first link) and my guess is that the driver is buggy since it won't exit the process when it encounters this type of error, further leading to suspicious/dangerous behaviour which results in Windows completely shutting down all COM ports until next restart.

To get this pin(it's called DTR/GRN), I borrowed the other chip(3rd) and I connected it regarding to this scheme:

I also had to download a different driver for it, I don't remember where I downloaded it from but it's called CDM21226 driver, when you install it it says FTDI driver installed.

Now my uploading was getting stuck no more, however after the first successful upload to my Arduino Pro the upload process would get stuck in the part where it is burning the program, if you turn verbose option in Arduino IDE on, you can see something like Writing: [#######              ].

It turns out this driver was faulty too, as I uninstalled it and when I installed it with the very same setup as before it worked seamlessly ever since. It also took me some time how to uninstall a Windows driver without using Device Manager because it wouldn't show up there - no device attached to it.

To do that open Command Prompt as admin and type pnputil.exe -e to get a list of all drivers. Among them will be one called FTDI and that's the guy, in my case he was called oem51.inf. To delete him, type pnputil.exe -d oem51.inf, or add -f before -d to force deletion - in my case it kept saying device is busy so it required this drastic measure. Change 51 to the number you have above your ftdi driver. After this just install the driver again and everything should be fine, even without reboot.

Phew...
So much work to get a simple program burned to Arduino Pro. Hope you have less trouble with it than I did.


Controlling amplifier using remote control jack Many older amplifiers support wired remote control through connector jacks or ports. My 10-year old Marantz also supports this function, using a simple RCA connector.

Originally these were used with external IR receivers when the unit was not kept in plain sight.

I wonder if there is a way to control the amplifier using an Arduino, which probably means by generating the required signal over the connector instead of receiving it from an IR receiver. Any pointer to a similar project is appreciated as well.

According to this thread on remotecentral the signal on the RCA connector is just the inverted signal that the IR-LED receives. So if you load an RC5 library and invert the output (0=1 and 1=0), you should be able to send codes to that connector with an arduino. Or even better, use an ESP8266 and control it over wifi ;)
The RC5 codes and their functions are in this  nice excel sheet or use this information if you want to send raw hex


Digital Potentiometer and Motor Speed Controller I'm trying to get a Chinese 20A DC Motor Speed Controller working with a MCP42100 Digital Potentiometer. The analogue potentiometer supplied was 100kOhm. I have programmed my arduino with the following code:

#define DATAOUT     11
#define DATAIN      12       //not used
#define SPICLOCK    13
#define SLAVESELECT 10
#define NOTEON      9
int potValue = 255;
float potInputValue;

void SPIInitialize()
{
  byte clr;
  pinMode(DATAOUT, OUTPUT);
  pinMode(DATAIN, INPUT);
  pinMode(SPICLOCK, OUTPUT);
  pinMode(SLAVESELECT, OUTPUT);

  digitalWrite(SLAVESELECT, HIGH); //disable device

  SPCR = (1 << SPE) | (1 << MSTR);
  clr = SPSR;
  clr = SPDR;
  delay(10);
}

char SPITransfer(volatile char data)
{
  SPDR = data;                    // Start the transmission
  while (!(SPSR & (1 << SPIF)))   // Wait the end of the transmission
  {
  };
  return SPDR;                    // return the received byte
}

//--- MCP42100 code

byte SetPot(int address, int value)
{
  // Slave Select set low to allow commands
  digitalWrite(SLAVESELECT, LOW);

  // 2 byte command
  SPITransfer(0x10 + address);   // 0x10 = 'set pot' command
  SPITransfer(value);            // Value to set pot

  // Release chip, signal end transfer
  digitalWrite(SLAVESELECT, HIGH);
}

//--- Application code

void setup()
{
  SPIInitialize();          // Initialize the SPI interface

  Serial.begin(9600);
  delay(25);
  Serial.println("Type a resistance between 0-100 kOhms above.");
}

void loop()
{
  if (Serial.available() > 0) {
    // read the incoming byte:
    potInputValue = Serial.parseInt();
    float potValue = (potInputValue / 100.0) * 255;
    Serial.print("Value: ");
    Serial.print(potValue);
    Serial.print(", Resistance: ");
    Serial.print(potInputValue);
    Serial.println(" kOhms");
    SetPot(1, potValue);
  }

}

Here is a picture of my setup:

Currently at a resistance of 0 kOhms the motor runs at full speed, as it should do and this is how it reacts with the analogue potentiometer. At a resistance of 100 kOhms, the motor (in this case a computer fan) still has enough juice to spin, until I stop it with my finger, but then it doesn't spin without a little push. With the analogue potentiometer, at 100 kOhms the motor received no juice to spin.

Here is a link to the speed controller: http://www.ebay.co.uk/itm/301366805277?_trksid=p2060353.m2749.l2649&ssPageName=STRK%3AMEBIDX%3AIT

The speed controller appears to use a 555 timer.

What am I doing wrong with the digital potentiometer to make it so it doesn't behave the same way as the analogue potentiometer?

The MCP42100 does not appear to be an appropriate digital pot for this application.

Without a schematic of the motor controller it is hard to tell, but a good guess would be that the digital pot is seeing voltages higher than the supply voltage you are feeding it, and higher than the maximum supply voltage of the digital pot (5.5V; 7.0V abs max). I don't see a voltage regulator on the motor controller board, nor would one be necessary for a low-end design. Probably just a PWM using a 555, as you say.

To make this work you probably need a different type of digital pot - one that can accept logic level inputs and has a higher supply voltage (12V + some margin). You also typically actually have to feed it the higher supply voltage (and be careful that nothing shorts and ruins the micro board).

Otherwise the input protection networks on the digital pot conducts more current than you would expect.


Connect ESP-01 to USB Uart for programming my ESP-01 chip I bought an "USB Uart", but it looks different to all the ones in all tutorials. I don't know how to connect the uart to the esp.
The uart i bought has following pins: 3V3, DTR, RXI, TX0, GND, +5V. The ESP01 has the known layout (http://www.esp8266.com/wiki/doku.php?id=esp8266-module-family#esp-01).

Once connected: Do I need an external power source, or do i just connect the usb uart to my computer?

Many thanks

Just to give an anwser for users struggling with the same problem I will sum up what helped me.

To connect the UART to the ESP the Beginner's Guide to the ESP8266 from @tttapa was very helpful. Another helpful link was this one:
https://www.allaboutcircuits.com/projects/flashing-the-ESP-01-firmware-to-SDK-v2.0.0-is-easier-now/

So in my case I just needed the GND, 3V3, RXI and TX0 pins from my UART.

I needed no external powersupply for the flashing process and some simple examples.


Do I need a full Arduino board hardwired to a sensor to send data via Wi-Fi? Basically I want to wire a Wheatstone bridge style load-cell into a moving trolley and transmit the data to a remote workstation so I can get real-time feedback about the loading conditions.

Do I need to have a full board riding on the trolley that is wired in between the Wi-Fi transmitter and the bridge amplifier or is there a way that the current variations from the bridge can be read directly by the Wi-Fi transmitter and relayed to the remote in some translatable format?

The trolley design is extremely streamlined and it would be a bummer to have to add more than minimal electronics to make this happen...

There are small packages out there with built in WiFi.  Node MCU is one of them, however its analog to digital conversion isn't up to the task of measuring bridges.  If you go that route you'll need to add a ADC to the Node MCU which will increase the total package size.


I²C only works when I short-circuit my Arduino I'm trying to connect an Arduino Nano with a Raspberry Pi 3 via I²C.

This is the small test-program I found and used for I²C.

#include <Arduino.h>
#include <Wire.h>

void setup() {
  Wire.begin(4);                // join i2c bus with address #8
  Wire.onReceive(receiveEvent); // register event
  Serial.begin(9600);           // start serial for output
}

void loop() {
  delay(100);
}

// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany) {
  while (1 < Wire.available()) { // loop through all but the last
    char c = Wire.read(); // receive byte as a character
    Serial.print(c);         // print the character
  }
  int x = Wire.read();    // receive byte as an integer
  Serial.println(x);         // print the integer
}

After compiling and uploading, I ssh-ed into my Pi and executed sudo i2cdetect -y 1 which prints an empty I²C table.

Here are images of how I connected the two devices, as far as I know the connection itself is okay. I also tested the cables with a multimeter.

Now the strange thing is, when I short-circuit my Arduino for a brief moment between GND and VIN I²C works, but Serial via USB with my PC stops working. Also the chip gets very hot and stays hot even though it isn't short-circuited anymore.

Any ideas what I'm doing wrong? I don't think the Arduinos are broken, since I tested it with 2 different ones. (while testing I accidentally short-circuited one and it worked)

EDIT: I tested I²C between the two Arduinos and it works flawlessly, but still doesn't want to work with my Pi. :(

Any ideas what I'm doing wrong?

Apart from deliberately shorting +5V to ground? Sheesh!

Get, or make, a level-shifter. You can't pump 5V from the Nano to the Pi and expect things to work. Example schematic:

In this example the low voltage (3.3V) side is marked LV, and the high voltage (5V) side is marked HV.

  You can use a level shifter with I²C but you don't need one. The Pi has pullup to 3.3V. Provided there are no other pullup it works. I routinely do this.

The important phrase there is "Provided there are no other pullup".

Wire.begin() enables the pull-ups. So make sure that on the Nano side you disable them again:

  Wire.begin (4);
  // disable internal pullups for twi.
  digitalWrite(SDA, LOW);
  digitalWrite(SCL, LOW);


Are the Arduino Micro, Mini, etc plug'n play? Also, what about the micro/nano/mini arduinos? Are they easily plug'n'play like the uno?
(This is an edit from another of my questions)

The ones that have a USB connector are plug-and-play with a USB host. The ones that don't need a USB-to-UART bridge.


Sharing serial Rx to read a push button on ESP8266-01 I'd like to know if it's possible, and if so how to use the serial Rx pin in a shared way to read a push button?

I've seen people using it in sort of a dedicated way but my idea is to use it dynamically. Which means it would stay as a standard Rx pin, with a push button sharing it. So the question is, what would happen if the push button was pressed? Would it be possible to detect it from the Rx stream?

I have experimented with my NodeMCU (ESP8266-12F, but the core chip is the same ESP8266EX).

First, the theory: UART is a asynchronous serial protocol. It has a configuration which consits of the baud rate (bits per second), parity bit (enabled or not) and number of stop bits (between 1-2). A common configuration is "9600N1", meaning 9600 bits per second, no parity bit, 1 stop bit.

If you want to trasmit the bitstring 0101 0101 with no parity, 1 stop bit, the RX line voltage will be:

RX line idles in high state (for us: 3.3V). Transmission is started by the start bit, which means that the line is pulled LOW. Then, the bits are transmitted LSB to MSB, followed by parity (if enable) and the stop bits.

I wrote the sketch

#include <Arduino.h>

void setup() {
    //use 300 Baud, lol
    Serial.begin(300);
}

void loop() {
    if(Serial.available()) {
        char readChar = (char) Serial.read();
        Serial.println("Read char: " + String(readChar) + " hex " + String((int)readChar, HEX));
    }
}

When transmitting a normal "A" (binary: 0100 0001) over serial, it looks like this in a logic analyzer:

When I connected a pulled-up button the RX line and press, the signal goes as

As one can see, the analyzer sees the pushing down of the button as a start bit, but the timing is way of. The line is pulled back to high much later. The time slot for the stop bit (which must be 1) was missed, so the logic analyzer displays "FRAMING ERROR". But the UART circuit inside the ESP8266 doesn't seem to care. It reads this as the transmission of a byte of the value "0x00".

Serial output: Read char:  hex 0

So, in response to the question "what would happen the push button was pressed?" we can say: At this speed of 300 baud (lowest possible setting), the UART received a bogus transmission but still reads it as an incomming 0x00 byte. However, depending on the bouncing of the signal due to the button presses, other received byte values might well be possible. You could be able to de-bounce the button to make the signal more stable, timing wise.

Anyway, you should not make a push button act as a crude UART transmitter if it isn't the absolute last possible solution. Depending on your application, you might be able to use the solution from this question and switch the function of the TXD0 and RXD0 to GPIO (more info). If you know exactly when to expect a button push, switch the pins to GPIO mode before and poll the status of the button (or install an interrupt).

However, as a bottom line: If you have no idea when the button will be pushed, then you will be fundamentally unable to distinguish the cause of the RX line falling low at the time the transition happens. It could be the transmission of some actual data (maybe also the zero-byte), but it could have also been the button.

A I²C GPIO port expander like the MCP23017 (link) would make much more sense, especially if you already have an I2C bus. There are also SPI devices available for this.


Reading port register and print I am playing with port registers directly to improve speed on a Arduino micro. I have no problem writing them, like

PORTF &= B11101111

However, when I try to read and print it, things get funny and I hope to know why.

Observation 0:

byte dat = PORTF;
Serial.print(dat,BIN);

produces a single 0, where I am expecting 8 0's as for a byte. And, even when I check that a digitalRead correctly gets a 1 from PF5 or A2,

Observation 1:

byte dat = PORTF;
Serial.print(dat,BIN);
Serial.print(dat,BIN);

produces a compiler error like

...cores\arduino\Print.cpp: In function 'println.constprop':
...cores\arduino\Print.cpp:143:1: internal compiler error: Segmentation fault
}
^

The function Serial.print() and it's siblings cuts all leading zeros. So 0b00001111 get's displayed as 1111 and 0b00000000 as 0. So you actually get what you expect. It's just printing different.

Also, when reading PORTF, you actually read the output state of the pins, as you have set it before. If you want to read the real input level of the pins, you should read PINF instead.

Though I don't know, where that segmentation fault came from.


How to check whether my arduino-mega ADC is sampling correctly? I have a code which samples the given input signals with sampling rate 256hz. I plotted the graph of FFT and was able to see the peaks at the expected frequencies.But I would like to know whether my ADC is sampling correctly or not?Is there a way to do it?`

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

const unsigned long READ_PERIOD = 3906;  // 3906 us: 256 Hz
void loop() {
    static unsigned long lastRead;
    if (micros() - lastRead >= READ_PERIOD) {
        lastRead += READ_PERIOD;
        int val_a0 = analogRead(A0);
        int val_a1 = analogRead(A3);
        int val_a2 = analogRead(A5);
        int val_a3 = analogRead(A7);
       Serial.print(val_a0);
       Serial.print("  ");
       Serial.print(val_a1);
       Serial.print("  ");
      Serial.print(val_a2);
      Serial.print("  ");
        Serial.println(val_a3);
    }
}

In this case the baud rate will be real bottleneck. You have to send from 110 to 230 bits per reading (1 start bit, 8bits data, 1 stop bit)*(3*2 spaces + 4-16 number characters + 1 line feed).

That means best case (all numbers are less than 10) 349 readings per second. And worst case is 166 readings per second (all readings are more than 999).

So it's about 10% probability to be sampled correctly.

You can check if the next time (with misleading name lastReading) is less than current time. That means you are already too slow.


Can an ATtiny print results to a console? I'm trying to port some Arduino code that I wrote for the Arduino Mega to an ATtiny and I'm having trouble figuring out how to do output. Here is what I have:

char foo;
#include <SoftwareSerial.h>
const int rx=3;
const int tx=4;

SoftwareSerial mySerial(rx,tx);

void setup()
{
mySerial.begin(9600);
}

void loop() {
 if (mySerial.available()) {
   char data = mySerial.read();
   mySerial.write(data);
 }

 mySerial.println("hello");
}

To my understanding this should print "hello" to the console over and over again but for some reason it uploads successfully but then it doesn't do anything.

Here is the programmer that I am using to connect my ATtiny to my computer: https://learn.sparkfun.com/tutorials/tiny-avr-programmer-hookup-guide/programming-in-arduino

You don't have any output because you don't have a serial adapter connected to the device. The programmer you have is only for programming and does not support a UART serial connection.