Multiple servos noise I'm building  an application that uses 20 servo motors, and i control then with an Arduino Mega. The servos are having some instability, to the point where they make small random swings. Im powering then from a 7.4V LiPo battery and I drop the voltage to around 6V with 2 series diodes. I've made some research and found 4 things that may help stabilize the servos.

Put a 1000uF eletrolitic capacitor between the battery VCC and GND pins.
Put a 470uF eletrolitic capacitor between each servo VCC and GND pins.
Put a 100nF ceramic capacitor between each servo SIGNAL and GND pins.
Put a 10k pull-up resistor on each servo SIGNAL pin.

My question is, how to make the right decision here. It is better for the project if I take all this designs into account, or I shouldn't be making some combination of this, or one in particular?

You can use the old software serial library from mikal heart. that one does not die interupts. You can do a google search on it.

here is a forum topic about it:
http://forum.arduino.cc/index.php?topic=82596.0


Constantly read analog in in SWITCH/CASE setup I'm writing a program with three different cases. Case one an LED is off, in another it is on and in the last case the brightness is controlled by a potentiometer. Each case works as I press the button. The issue I am having is with the third case. The potentiometer is read only once and the LED is set accordingly. I would like the LED to be adjusted continuously until the button is pushed again and the case is switched to off. I used the Serial.print to see the valves read from the potentiometer. I verified its only read once on each cycle through the different cases. I also changed from a SWITCH/CASE to If statements and it only reads the potentiometer once.

CODE HAS BEEN UPDATED

//-------------------------------------------------------
// BUTTON AND POT - TEST
// KNOWN ISSUE - POT ONLY TAKES ON READING
// vonderasche
// 7/28/2016
//-------------------------------------------------------

const int BUTTON_PIN = 9;
const int LED_PIN = 3;
const unsigned long DEBOUNCE_TIME = 50;

int val = 0;
int pot = 0;

int state = 0;

void setup()
{
    pinMode(BUTTON_PIN, INPUT_PULLUP);
    pinMode(LED_PIN, OUTPUT);
    Serial.begin(9600);
}

bool button_press()
{
    static bool last_state;
    static unsigned long last_state_change;
    unsigned long now = millis();

    if (now - last_state_change < DEBOUNCE_TIME)
        return false;

    bool state = digitalRead(BUTTON_PIN);
    if (state != last_state) last_state_change = now;
    bool press = last_state && !state;
    last_state = state;
    return press;
}

void loop()
{

    unsigned long now = millis();
    static enum { OFF, ON, POT } state;

    if (button_press()) switch (state) {
    case OFF:
        analogWrite(LED_PIN, 255);
        state = ON;
        Serial.println(state);
        break;
    case ON:
        analogWrite(LED_PIN, 0);
        state = POT;
        Serial.println(state);
        break;
    case POT:
        Serial.println(state);
        int Mode = button_press();
        while (val < 1023) {
            val = (analogRead(pot) / 4);
            analogWrite(LED_PIN, val);
            Serial.println(val);
            state = OFF;
            break;
        }
    }
}

The problem is that it will only go through the POT case once, if you want it to repeatedly read the potentiometer, and then change the LED brightness, you would have to put the case in a loop.

So, you might do something like this:

case POT:
int Mode = digitalRead(BUTTONPIN);
while(Mode == LOW) {
    val = (analogRead(pot) / 4);
        analogWrite(LED_PIN, val);
        Serial.println(val);
        state = OFF;
        break;
        Mode = digitalRead(BUTTONPIN);
    }
}

If you want to use the debounce, do something like this:

static enum { OFF, ON, POT } state;
unsigned long now = millis();
int x = 0;

while (x == 0) {
    switch (state) {
    case OFF:
        analogWrite(LED_PIN, 255);
        if (button_press()) {
        state = ON;
        }
        break;
    case ON:
        analogWrite(LED_PIN, 0);
        if (button_press()) {
        state = POT;
        }
        break;
    case POT:
        val = (analogRead(pot) / 4);
        analogWrite(LED_PIN, val);
        Serial.println(val);
        if (button_press()) {
        state = OFF;
        }
        break;
    }
}

This should work. What it's doing is basically just going through this while loop over and over and over again, and whenever the button is pressed, THEN it will switch state, but otherwise, it'l just do the same state again and again. This way the potentiometer will work AND the debounce.


Grouping multiple pins to one variable I'm new to all of this, but it's there a way to group a cluster of pins to one variable? I don't necessarily want the grouped pounds to be sequential.

Only if you drop to low-level access, and only if the pins are on the same port.

#define pinset 0x55

 ...

PORTC |= pinset;
delay(1000);
PORTC &= ~pinset;


Data not updated in real time In my recent project, working with JSON and Arduino. Till now, I am getting proper JSON data and add this one into Arduino data. But here I face one problem. My data are not updated in real time.

For example, my JSON string is:

{"TPS_Json":"0.40"}

And below is my Arduino code:

#include<LiquidCrystal.h>
#include <ArduinoJson.h>

LiquidCrystal lcd(12, 11, 7, 6, 5, 4);

String response = "";
bool begin = false, finished;

//------------------------------ Variable ---------------------------------//

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

  lcd.begin(16, 2);
}

void loop()
{
  //----------------------------TPS----------------------------//

  float TPS = analogRead(A0) * (5.0 / 1023.0);

  //-----------------------JASON DATA--------------------------//

  StaticJsonBuffer<100> jsonBuffer;

  while (finished == false)
  {
    if (Serial.available())
    {
      const char in = Serial.read();
      if (in == '{')
      {
        response = "";  // Blank the string
        begin = true;
      }
      if (begin)
      {
        response += (in); // Only write if within the {}
      }
      if (in == '}')
      {
        begin = false;   // Prevent any chars between } and { leaking through.
        break;
      }
    }
    delay(1);
  }

  JsonObject& root = jsonBuffer.parseObject(response);

  float TPS_Json = root["TPS_Json"];

  float TPS_Final = TPS + TPS_Json;

  lcd.setCursor(0, 0);
  lcd.print("      ");
  lcd.setCursor(0, 0);
  lcd.print(TPS);
  lcd.setCursor(8, 0);
  lcd.print("      ");
  lcd.setCursor(8, 0);
  lcd.print(TPS_Json);
  lcd.setCursor(0, 1);
  lcd.print("      ");
  lcd.setCursor(0, 1);
  lcd.print(TPS_Final);
}

So, now I add TPS_Json with TPS. Where TPS_Json is JSON data and TPS is an analog value from A0. And TPS_Final is the addition of TPS_Json and TPS. I displayed all this on LCD.

Suppose, TPS_Json = 0.40, TPS = 2.40... So addition is 2.80 means TPS_Final = 2.80...
And this all data displayed on LCD successfully.

But when I changed my analog value means TPS value then it is not updated and I'm not getting the correct result.

Suppose, I change the value of TPS means makes it 3.00 from 2.40 than my TPS_Final must be 3.40.But nothing updated. It updated when I send JSON data again. I don't know why this happens. I want to change it in real time means When I changed TPS then TPS_Final must be changed in real time.

The reasons it's not updating is because your code is sitting in the loop while (finished == false) {...} waiting for more json to arrive.

Try replacing the while loop with something along these lines:

  while ((finished == false) || Serial.available()) {
   if (Serial.available()) {
    const char in = Serial.read();
    if (in == '{')  {
        response = "";  // Blank the string
        begin = true;
        finished = false;
    }
    if (begin)
        response += (in); // Only write if within the {}
    if (in == '}') {
        begin = false;   // Prevent any chars between } and { leaking through.
        finished = true;
    }
   }
  }

and change the initial variable declarations at the start of the code to set finished to false:

// personally I always put each variables on a separate lines when setting initial values.
bool begin = false;
bool finished = false;

This will block until it's received at least 1 json string. After that it will check if there is new data on the serial port, if there is it will block until it's received the whole string, it there isn't any data waiting it will exit.

Oh and your response string is currently including the { } characters at the start and end, this contradicts your comments which imply that it doesn't.


How to upgrade Arduino UnoR3 clock A little background:

I need to generate a 40KHz frequency as accurately as possible.

(One of my other posts is here:
Stable frequency generation)

My code is solid- I'm using an Uno R3 and generating the most accurate frequency I can at this point. The only way to get a more accurate frequency is to upgrade the ceramic resonator to a crystal oscillator.

So, my over-arching question is: How do I actually upgrade the ceramic resonator to a crystal oscillator?

Things I'm considering are:

Is it worth it to actually upgrade my Uno R3 - and is it even possible? Is there a clone that drives the ATMega328p with a crystal oscillator that I could use instead? Is there simply just a better model for this application?

It's really easy to take an ATmega328 chip and wire it up on it's own.  There are even instructions on the Arduino site on how to do it.  Take a look at http://www.arduino.cc/en/Main/Standalone .

You could even pull the 328 out of the Uno, add the crystal and a few caps and then program it with the Uno board.  I've done this a few times myself and it worked just fine for my needs.


Arduino MEGA2560 Standalone I had an Arduino UNO (ATmega168) standalone working, but I need more pins, and I decided to use the ATmega2560, I was searching for some schematics, and none of them shown an ATmega2560 standalone, only the full Arduino, with the FTDI, power transformers... etc integrated. So taking parts from those designs, I made this, but I don't know if it's enough or I need Something more:

Note: VCC2 is connected to 5V.

You need more decoupling capacitors - one per VCC and AVCC pin, plus a larger (10µF) for the whole chip.

You need a pullup resistor (and maybe button) on RESET.


What are some fun things you can do using the ICSP header? I bought 10 Arduino Nanos for a project, each with all of their headers soldered in place.  Each was going to go into a tiny space, so I found myself needing do desolder the ICSP headers.

This led to a bit of a moral conundrum.  What would I lose by removing these useful looking headers.  They cover quite a lot of space on the nano, so they must be important right?  Am I going to regret removing these things when I finally realize how useful they are (I thought to myself.)

In the end, I did remove the ICSP headers, but the event got my thoughts going.  What is this header all about?  Why is it there?  What can I do with it?  I began to search for things that I could do with the ICSP header, but engaging results were not forthcoming ( except for this project:  https://www.arduino.cc/en/Hacking/ParallelProgrammer )

Anyway, I was more interesting in things that flash, move, jump, sing, and such, so are there any interesting things that can be done with the ICSP header?

You can use every single last byte of flash on the device.
Since you're performing low-level programming of the device you get the entire chip to play on, without having to worry about bootloaders and such.

You can debug (breakpoint, single-step, watch, disassemble, etc.) the code on the chip using software on your computer.
Admittedly the devices you'd need in order to do so are more expensive than a simple ISP programmer and it only works with specific pieces of software, but it can be done.


Wiring and Connecting WS2801 to NodeMCU ESP8266 After hours of searching for a solution and try many ways of wiring, I must asking here for Help:

I'm using a ESP8266 (ESP-12E) with a WS2801 - 4 Wire LED Strip and using this Pinout-Diagram to connect WS2801 wires to NodeMCU.

https://alexbloggt.com/wp-content/uploads/2015/10/nodemcu_pinout_700.png

Here is my Wiring:

LED     ESP
====   =====
5V --> Vin
GND --> GND
CK --> GPIO2 (D4)
SI --> GPIO3 (RX)

I have found this sample Program which should turn on and off all LEDs one after each other for 100ms. But it happens nothing after compiling and uploading it to NodeMCU board using Arduino IDE. Any help is highly appreciated.

//This program was taken from the FirstLight.ino supplies with the FastLED library
// It has been modified for use with a NodeMCU for use in a tutorial by NQMakerSupplies.com.au
// Hosted at theMakers.org.
//
// Special thanks to the people behind FastLED.io and all the contributors :)

#define FASTLED_ESP8266_NODEMCU_PIN_ORDER   // map output pins to what they are called on the NodeMCU
#include "FastLED.h"

///////////////////////////////////////////////////////////////////////////////////////////
//
// Move a white dot along the strip of leds.  This program simply shows how to configure the leds,
// and then how to turn a single pixel white and then off, moving down the line of pixels.
//

// How many leds are in the strip?
#define NUM_LEDS 10

// Data pin that led data will be written out over
#define DATA_PIN 3

// Clock pin only needed for SPI based chipsets when not using hardware SPI
#define CLOCK_PIN 2

// This is an array of leds.  One item for each led in your strip.
CRGB leds[NUM_LEDS];

// This function sets up the ledsand tells the controller about them
void setup() {
    // sanity check delay - allows reprogramming if accidently blowing power w/leds
   delay(2000);
   FastLED.addLeds<WS2801, DATA_PIN, CLOCK_PIN, RGB>(leds, NUM_LEDS);
}

// This function runs over and over, and is where you do the magic to light
// your leds.
void loop() {
   // Move a single white led
   for(int whiteLed = 0; whiteLed < NUM_LEDS; whiteLed = whiteLed + 1) {
      // Turn our current led on to white, then show the leds
      leds[whiteLed] = CRGB::White;
      // Show the leds (only one of which is set to white, from above)
      FastLED.show();
      // Wait a little bit
      delay(100);
      // Turn our current led back to black for the next loop around
      leds[whiteLed] = CRGB::Black;
   }
}

Changing the first line from

 #define FASTLED_ESP8266_NODEMCU_PIN_ORDER

to

 #define FASTLED_ESP8266_RAW_PIN_ORDER

has solved the Problem.


Powering Motor doesnt work from Digital Pin, but works on 5V power I am building a little car project, and I have come across an issue that has made me go mental.
I have a single motor (3V-5V), that on direct 3.3V & 5V output works fine. However, when I connect this to a digital port, it for some reason doesn't power. Of course, I first thought it was not supplying correct power, so I got myself a voltage meter and tried that. 3.3V outputs, well 3.3V, all fine. The digital port outputs 4-5V (when it is coded to). So here is my question: Why aren't my motors powering/turning?

Power is made up of two values, not one. Besides the voltage there is the current (P=VI), and it's the current you are lacking.

A motor needs a large amount of current to start turning (called the stall current) and a digital I/O pin can only supply a relatively small amount (absolute maximum 40mA, recommended maximum 25mA). The power pins though can supply many hundreds of mA.

You should never try and power a motor directly from an I/O pin since you risk damaging the I/O pin.  Instead you should use the I/O pin to control an NPN transistor or N-channel FET, which is then used to switch the power (actually the ground connection) to the motor from one of the power pins.

Here is a good tutorial: http://www.circuitstoday.com/pwm-generation-and-control-using-arduino


Can I run a loop in setup() Are loops not allowed in setup()? The following doesn't print anything inside the for loop to the serial terminal

Code:

void setup() {
  Serial.begin(9600);
  Serial.println("Ping");
  for (int i = 0; i >= 10; i++) {
    Serial.println(i);
    Serial.println("Pong");
  }
}

void loop() {

}

Output:

Ping

In principle yes, you can use a loop in setup() however this specific code

for (int i = 0; i >= 10; i++) {
  Serial.println(i);
  Serial.println("Pong");
}

will result in the body of the loop never executing, as the loop test i >= 10 is initially false.

You probably meant i <= 10

Generally speaking, it would be poor program structure to use a loop in setup() in place of one in loop(), however if you need a loop to apply similar operations to a range of things, or to briefly busy wait on a condition as part of setting up operation, that kind of thing could be appropriate.


Avoid the 10 attempts of Avrdude when programmer is not responding Sometime I update my sketch in the Arduino environment, and when I click on the transfer arrow but forget to plug my arduino (I'm using the UART in my project so every time I need to plug/unplug some wires) it's a drama, avrdude throw this for at least 2 minutes :

  avrdude: stk500_recv(): programmer is not responding
  avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x32

It's a real pain because I can't stop avrdude when this happens.
Is there a way to configure the Arduino environment to disable it?

Unfortunately, MAX_SYNC_ATTEMPTS is a constant in the source code, and one which appears several times.

avrdude is an open source project, so customizing and building it should be relatively straightforward.  Since it is a numeric rather than string value, and is checked in several places, simply modifying the binary is likely to be tricky.

One can of course manually kill the process, though it is annoying to have to.

Another approach could be to write a wrapper which might potentially do some sanity checking first (does any other process have the port open?) and then would launch avrdude as its child, passing through all the arguments.  By monitoring the output before passing it on, it should be possible to detect this message and terminate the avrdude instance automatically.


Can't able to detect Square wave from 74HC14 In my recent project, I want square wave which length vary according our timing. And this square wave is take reference as a another square wave.

For that, I made Square wave with help of Arduino.

Here, it's code.

int kPinSqrOut = 13;

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

void loop()
{
  digitalWrite(kPinSqrOut, HIGH);
  delay(1000);
  digitalWrite(kPinSqrOut, LOW);
  delay(2000);

}

This is just simple HIGH and LOW one pin of arduino and we get Square wave.

Oscilloscope output :

Now based on this, I'm getting Square wave which length can be able to vary.

Here, it's code.

const uint8_t button_pin = 2;
const uint8_t kPin = 3;

void setup()
{
   pinMode(button_pin, INPUT_PULLUP);
   pinMode(kPin, OUTPUT);
   Serial.begin(9600);
}

void loop()
{
   static int last_button_state = LOW;
   static unsigned int push_count;
   static unsigned long last_press_time;
   int button_state = digitalRead(button_pin);
   unsigned long now = millis();

  // Record when the button is pressed.
  if(last_button_state == LOW && button_state == HIGH)
  {
    push_count++;
    last_press_time = now;

    digitalWrite(kPin, HIGH);
    delay(20);
    digitalWrite(kPin, LOW);
  }

  // Report when the button is released.
  if(last_button_state == HIGH && button_state == LOW)
  {
    unsigned long push_duration = now - last_press_time;
    if (push_duration < 10)   // discard bounce
    {
        push_count--;
    }
    else
    {
       Serial.print(F("pushes: "));
       Serial.print(push_count);
       Serial.print(F(", duration: "));
       Serial.print(push_duration);
       Serial.println(F(" ms"));
    }
  }

  last_button_state = button_state;
}

And Serial Monitor output :

pushes: 1,    duration: 1001
pushes: 2,    duration: 1000
pushes: 3,    duration: 1001
pushes: 4,    duration: 1002
pushes: 5,    duration: 1001

ve
So, basically what I'm try to do. One Arduino generate Square wave and another Arduino take this Square wave as Input and calculate it's length and also generate another Square wave based on first one.

Here, I just detect HIGH state of Square wave and according that generate another Square wave which length vary.

Oscilloscope output :

Ideally, all this things work fine. Now, when I apply this things in real implement then not working.

Here, it my square wave(upper one) from 74HC14. But not getting another square wave based on that.

So, give me some suggestion.

The only issue in your code is due to the delay in the pin control. You can solve it this way:

void loop()
{
    static int last_button_state = LOW;
    static unsigned int push_count;
    static unsigned long last_press_time;
    static bool kPinPressed = false;
    int button_state = digitalRead(button_pin);
    unsigned long now = millis();

    // Record when the button is pressed.
    if(last_button_state == LOW && button_state == HIGH)
    {
        push_count++;
        last_press_time = now;

        digitalWrite(kPin, HIGH);
        kPinPressed = true;
    }

    if ((kPinPressed) && ((now - last_press_time) >= 20))
    {
        digitalWrite(kPin, LOW);
        kPinPressed = false;
    }

    ...
}

So you turn on the output, then after 20ms you turn it off.

There are just a couple of things not clear for me. What is the last picture? What are the yellow and pink traces? Why is it not behaving correctly? What are the readings on the serial interface?

And most important... What is the time scale? Is it really 10ms/div?


How can one reset Arduino Nano from NodeMCU? If one connects the RESET pin on an Arduino Nano to a digital pin on a NodeMCU, will the NodeMCU be able to reset the Nano by setting said pin to LOW?

Yes, you can reset a 5 V Arduino with esp8266. I did it many times. The esp8266 doesn't have a problem with pull-up level current at 5 V.

On my picture io 0 of the esp-12F is wired to reset pin of Nano. The esp-12F runs WiFiLink firmware which can OTA upload sketch to ATmega328p and of course before flashing it must reset the ATmega.


Can I connect a DS3231 and an MPU6050? Can I connect a DS3231 and an MPU6050 by an Arduino Mega 2560? I have connect it:

MPU 6050               Arduino Mega 2560
SDA           =        SDA
SCL           =        SCL
GND           =        GND
VCC           =        5V

And I have connected DS3231 to SDA and SCL beside AREF pin:

DS3231               Arduino Mega 2560
SDA           =        SDA
SCL           =        SCL
GND           =        GND
VCC           =        5V

The problem is when I connect both of them MPU6050 prints nan, after opening the DS3231 pin from the arduino, MPU6050 prints the correct angles.
Can someone please help me?

Code:

#include "MPU6050.h"
#include "Wire.h"
#include <DS3231.h>
MPU6050 accelgyro;
int16_t ax, ay, az, gx, gy, gz;

DS3231 rtc(SDA, SCL);

double timeStep, time, timePrev;
double arx, ary, arz, grx, gry, grz, gsx, gsy, gsz, rx, ry, rz;

int i;
double gyroScale = 131;

void setup() {
  Wire.begin();
  accelgyro.initialize();
  Serial.begin(9600);
  rtc.begin();
}

void loop() {
  timePrev = time;
  time = millis();
  timeStep = (time - timePrev) / 1000;
  accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
  gsx = gx/gyroScale;   gsy = gy/gyroScale;   gsz = gz/gyroScale;
  arx = (180/3.141592) * atan(ax / sqrt(square(ay) + square(az)));
  ary = (180/3.141592) * atan(ay / sqrt(square(ax) + square(az)));
  arz = (180/3.141592) * atan(sqrt(square(ay) + square(ax)) / az);
  if (i == 1) {
    grx = arx;
    gry = ary;
    grz = arz;
  }
  else{
    grx = grx + (timeStep * gsx);
    gry = gry + (timeStep * gsy);
    grz = grz + (timeStep * gsz);
  }
  rx = (0.1 * arx) + (0.9 * grx);
  ry = (0.1 * ary) + (0.9 * gry);
  rz = (0.1 * arz) + (0.9 * grz);
  Serial.print("X axis == ");
  Serial.println(arx);
  Serial.print("Y axis == ");
  Serial.println(ary);
  Serial.print("Z axis == ");
  Serial.println(arz);
  Serial.println(rtc.getTimeStr());
  i = i + 1;
  delay(1000);
}

The DS3231 library you are using works (for some bizarre reason) exclusively with its own internal bit-bang implementation of I2C. This cannot be used on the same pins as the hardware Wire library which the MPU6050 uses.

Either move the DS3231 to a different pair of pins, or find a better DS3231 library that uses the Wire library for communication.


Not getting pure color while using the FastLED with WS2812b I am working with the LED strip WS2812b and FastLED library, currently I have only 3 LEDs connected in such a way that the first 2 receive a color (say green) and the last one receives another one (say blue).

The problem is that by putting the color (blue) on the last LED, the other two (currently only in green) also take a portion of blue, preventing it from being a pure (green) color. It happens with any combination of color.

I leave the piece of my code referring to the LED strip:

#include "FastLED.h"
#define NUM_LEDS 3
#define DATA_PIN 2

//Variables declaration...
....

void setup() {
  FastLED.addLeds<WS2812B, DATA_PIN, RGB>(leds, NUM_LEDS);
.....

  }

void loop() {
  ReadMySerial();       //This function take data from serial port and set the color for the leds
  FastLED.setBrightness(brigth);

  for (int pinNo = 0; pinNo <= 2; pinNo++){
    leds[pinNo].setRGB(green_inactive,red_inactive,blue_inactive);
    FastLED.show();
      if (digitalRead(pinNo+3) == HIGH){
        leds[pinNo].setRGB(green_reactive,red_reactive,blue_reactive);
           FastLED.show();
            }
        }

  }

I already change the pin for where I put the signal for the LED strip, I try to change the type of LED strip

FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS)
FastLED.addLeds<WS2812, DATA_PIN, RGB>(leds, NUM_LEDS)
FastLED.addLeds<WS2812, DATA_PIN, COLOR_ORDER>(leds, NUM_LEDS)

without any success...

Can anyone point me in the rigth direction?

Edit: actually, the first LED of the strip is flashing, not in the way of the Blinking example, but I can see a little flashing.

I can see what the problem is, I put FastLED.show(); where it should not, that's also why I saw the flash ... fix it and here's the result:

void loop() {
  ReadMySerial();       //This function take data from serial port and set the color for the leds
  FastLED.setBrightness(brigth);

  for (int pinNo = 0; pinNo <= 2; pinNo++){
    leds[pinNo].setRGB(green_inactive,red_inactive,blue_inactive);
    FastLED.show();
    if (digitalRead(pinNo+3) == HIGH){
      leds[pinNo].setRGB(green_reactive,red_reactive,blue_reactive);
    }
  }

  FastLED.show(); //NOW IS IN THE RIGHT POSITION
}


How to program Arduino manually via STK500? I am trying to program an Arduino Nano (with an ATmega328P) from an ESP32 that is attached to its UART and the reset pin. I have to do this via the ESP, because the Arduino is supposed to run on its own, detached from a PC (where I could use an existing programmer for it). But its program should be changable, hence, it is attached to the ESP, which is accessible from a web server via Wifi, so that the Arduino can be reprogrammed on request. I almost got the whole setup figured out: The server is running, files can be sent to the ESP, and the ESP can talk with the Arduino Bootloader. The only problem is that I cannot get the Arduino to execute new programs.
The whole procedure goes like this: The server communicates with the ESP, sends the HEX file of the Arduino sketch (which is successfully verified by a checksum, so this part is working properly). Then, the ESP pulls the reset pin of the Arduino and waits for a while before it attempts to talk to its bootloader. Then, it basically does the same sequence of STK500 commands as avrdude.
I really just copied the commands from the avrdude log after executing
avrdude -c arduino -vvvvv -p m328p -b 57600 -P /dev/ttyUSB0 -U flash:w:sketch.hex:i

and skipping query commands like which firmware version it uses etc. So, basically: enter programming mode, erase chip, re-enter programming mode, write the hex file to flash, starting from address 0, moving in steps of 128 bytes (using 1's to pad the last message to the full size of 128 bytes). Then afterwards reading back the file from the Arduino and veryfing that all bytes match (which they do!) and leaving the programming mode (which is the very last thing that happens in the avrdude log). Afterwards, I trigger the reset. I am using exactly the same type of file which I gave to avrdude, and all the responses of the Arduino bootloader exactly match the values from the avrdude log.
But whereas the Arduino just starts executing the sketch after this procedure when using avrdude, in my own implementation it just blinks its LED in a regular interval (when the test sketch should make it blink short, long, short, long etc.). I don't get what's going wrong here. I thought that the blinking might represent an error code, but I couldn't find any documentation about that. I feel like I've searched the whole Internet (including arduino stackexchange), and I even looked at the avrdude source code to check if there's something else done after the last STK500 command, that is not listed in its log. I feel (hope) that I'm very close to having it work and this whole thing just needs like a one-line fix, but I don't know what else to try anymore and would greatly appreciate a second opinion from someone more experienced.

Okay, by comparing the data packets my implementation sends with those from the avrdude log for the same sketch, I finally found the cause of trouble. I was sending the hex file byte-by-byte exactly as it is read from storage. But of course, the metadata needs to be skipped (i.e. the addresses at the beginning of each line, the magic bytes at the end of each line, and the newline). I added this simple fix, and now it works fine.
EDIT: Here is the preprocessing code from my Python3 script:
import codecs

program = b''
for line in open('sketch.hex', 'rb'):
    program += codecs.decode(line[9:-4], 'hex')


Using multiple timers and avoiding conflicts I would like to use three timers in CTC mode to launch three Interrupt Service Routines at different frequencies.

In this application I need to use the servo library, millis() and micros() functions.

Timer3 (Working)

Thanks to this question, Timer3 has been set up in the following way:

  cli();          // disable global interrupts
  TCCR3A = 0;     // set entire TCCR3A register to 0
  TCCR3B = 0;     // same for TCCR3B

  // set compare match register to desired timer count:  @~744 Hz
  OCR3A = 20;
  // turn on CTC mode:
  TCCR3B |= (1 << WGM32);
  // Set CS10 and CS12 bits for 1024 prescaler:
  TCCR3B |= (1 << CS30) | (1 << CS32);
  // enable timer compare interrupt:
  TIMSK3 |= (1 << OCIE3B);
  // enable global interrupts:
  sei();

  ISR(TIMER3_COMPB_vect)
  {
     cont++;
  }

Timer4
I've tried with this configuration:

cli();          // disable global interrupts
TCCR4A = 0;     // set entire TCCR3A register to 0
TCCR4B = 0;     // same for TCCR3B

// set compare match register to desired timer count: @ ~744 Hz
OCR4A = 20;
// turn on CTC mode:
TCCR4B |= (1 << WGM42);
// Set CS10 and CS12 bits for 1024 prescaler:
TCCR4B |= (1 << CS40) | (1 << CS42);
// enable timer compare interrupt:
TIMSK4 |= (1 << OCIE4B);
//TIMSK4 |= (1 << OCIE4A); same issue
// enable global interrupts:
sei();

ISR(TIMER4_COMPB_vect) //TIMER4_COMPA_vect same issue
{
  cont++;
}

But the compiler returns an error caused by the servo library conflict:

  Servo\Servo.cpp.o: In function '__vector_42': C:\Program Files
  (x86)\Arduino\libraries\Servo/Servo.cpp:117: multiple definition of
  '__vector_42' Timer4B_800Hz.cpp.o:C:\Program Files
  (x86)\Arduino/Timer4B_800Hz.ino:49: first defined here c:/program
  files
  (x86)/arduino/hardware/tools/avr/bin/../lib/gcc/avr/4.3.2/../../../../avr/bin/ld.exe:
  Disabling relaxation: it will not work with multiple definitions

As Gerben suggested in a comment in this question:

  They are just hogging all timers. I guess you have to alter the
  library slightly by removing the #define _useTimer3 line, or try
  putting a #undef _useTimer3 right after the include. –  Gerben

I would avoid changing the servo library since motors play a critcal role in the application.

Timer 5 Same issue

Which timers and output compare registers can I use to set up the three ISR correctly?

The problem is the Servo library. This library is claiming all the timers, so you can't use them yourself. What I do to fix this is edit the Servo.h (or ServoTimers.h) file.

#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
//#define _useTimer5
#define _useTimer1
#define _useTimer3
//#define _useTimer4
//typedef enum { _timer5, _timer1, _timer3, _timer4, _Nbr_16timers }   timer16_Sequence_t;
typedef enum { _timer1, _timer3, _Nbr_16timers } timer16_Sequence_t;

This will remove the 2 timers (4 and 5) for the Mega boards, but you can still attach 24 servo's. If you need more, you should edit this file again.


How do I run multiple vibration motors from an Arduino Mini with PWM? I'm building a project for my Physical Computing class that involves 4 vibration motors for varied haptic feedback based on serial input via analogRead. I have each coming out of their own pin and assigned to conditionals.

I'm wondering:

how do i control the PWM of each individual motor?
assuming I need an external power source for the motors, do I need to have a diode and transistor in between each motor and the ground?

Thanks in advance - I'm still learning but definitely looking forward to taking Part II next semester!

You can control motor PWM by using AnalogWrite() feature. Arduino Mini is equipped with 6 PWM pin, so you can use 1 PWM pin for each of you motor. Check here about more information on AnalogWrite, and here about Arduino Mini
This is the circuit if you want to use external power source. Normally, I use 1k ohm resistor, I'm sure there are someone out there that knows the exact formula.

simulate this circuit – Schematic created using CircuitLab


trying to use millis() I'm learning how to use the millis() function. Instead of having it in the main body of the program I wanted to place it in a function so I can change the time interval with which an led will flash. I modified the code blinkWithoutDelay. My code is below. The output I get is an LED that is always on. I did print the output of the ledState to the serial monitor. Its changing from on to off repeatedly. So I think the led is really flickering too fast to see. I took a screenshot from the serial monitor. The output is below.

const int LED2 = 2;
int ledState2 = LOW;

void timeCheck(int interval)
{
    unsigned long cMillis = millis();
    unsigned long pMillis;

    if (cMillis - pMillis > interval)
    {
        pMillis = cMillis;

        if (ledState2 == LOW)
        {
            ledState2 = HIGH;
        }
        else
        {
            ledState2 = LOW;
        }
        digitalWrite(LED2, ledState2);
        Serial.println(ledState2);
    }
}

void setup()
{
    Serial.begin(9600);
    pinMode(LED2, OUTPUT);
}

void loop()
{
    unsigned long flashtime = 1000;
    timeCheck(flashtime);
}

The problem here is that the variables you declare in your function are not static. The rest of the code works as expected.
Where you declare the variables at the beginning of your function is correct. There is only one variable in question though as it is the cause of the error you are seeing.
What you need to do is change the variable
unsigned long pMillis;

to
static unsigned long pMillis = 0;

By not having the pMillis as a static variable, each time the function is called the value of pMillis is undefined, which means it is unpredictable whether  (cMillis - pMillis > interval) will be true or false. But with the static declaration the Arduino knows to keep the previous value for the next time you call the function.
An excerpt from Wikipedia:

In computer programming, a static variable is a variable that has been allocated statically—whose lifetime or "extent" extends across the entire run of the program....
A static local variable is different from a local variable. It is initialized only once no matter how many times that function in which it resides is called.


Can I use an arduino as a ground short? I have a little personal project involving an Arduino Uno and an amp board from Sure Electronics. The amp has contacts for a mute function that involves shorting the contact to ground. I would like to control this muting with the Arduino which I was planning to do with a relay. However I think I might be complicating things and I thought it might be possible to do it directly with the pins.

Can I use the Arduino to directly short a circuit to ground? Or would I need something more complicated to be safe?

Depends on the voltage that is on that mute pin. If it's below 5 volt, you could use the arduino pin. You can measure the voltage using a multimeter.

If it's more than 5v you can use a NPN transistor and resistor combination.

Current isn't a problem with these kinds of "settings" pins, as there is just a pull-up resistor that by default (unconnected) sets the pin to HIGH. By connecting the pin to ground you set the pin to LOW.


Need to "Extend" a Arduino Digital Signal Here's the scenario:
We have 1 arduino uno accepting DMX and converting that to a signal that is being sent out digitally (PIN 3). The digital signal then goes to several IR LED senders that control 3,200 IR, color-changing candles. I've recently added some more senders, and now some of the senders are not working (even some that were working before). I assume this is because the digital signal has been weakened due to me splitting it so many times.

I'd like to add another arduino to control half of the IR senders. I obviously already have a cable running to every device, but I know of a perfect place to "interject" the new arduino. Is this possible? Can the second arduino essentially "repeat" or decode and re-encode the digital signal? If so, what pins am I looking at and will I need any special code?

Thanks for the help!

The scenario you are referring to - connecting one output to many devices - is called the fan-out. Yes, a GPIO pin has a limited amount of drive which limits the number of devices in the fan-out.

There are two problems that are caused by excess fan-out:

Excess current draw from resistive loads
Excess capacitance from logic loads

The former is evident when you have too many LEDs connected directly to an output (with resistors, of course). The combined current draw of the LEDs exceeds the current the IO pin can provide and either damage the pin or the LEDs go dimmer than would be desired.

The latter is more evident when working with communication signals. The excess capacitance imposed by each gate attached to the output causes a low-pass filter effect which can filter out high-frequency signals or corrupt the waveforms by removing higher frequency components and "curving off" the nice clean square waves.

In normal logic systems it's common to use line drivers or buffers to allow the connection of more devices to a single signal. Devices such as the 74HC244, which is 8 buffers in one chip, are commonly employed. You can connect the inputs of all 8 buffers to one Arduino output, and each output from the buffer mirrors the input exactly and can connect to more devices than an Arduino can (each output has an extra 10mA steady-state drive capacity than the Arduino).

And yes, you can even connect the output of one buffer to the inputs of other buffers to give even more capacity.

simulate this circuit – Schematic created using CircuitLab


Make action happen after time is passed using interrupts I am trying to create a code which prints to the LCD a message once a certain time is passed.

#include <Time.h>
#include <TimeLib.h>
#include <Adafruit_RGBLCDShield.h>
#include <utility/Adafruit_MCP23017.h>
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

void setup() {
  lcd.begin(16, 2);
  setTime(02, 10,00, 14, 03, 2016);

  //pinMode(13, OUTPUT);
  pinMode(2, INPUT);
  digitalWrite(2, LOW);
  attachInterrupt(0, blink, CHANGE);
}

void loop() {
  lcd.setCursor(0, 1);
  char time_out[16];
  sprintf(time_out, "%02u:%02u:%02u",hour(),minute(),second());//use %x to get hex
  lcd.print(time_out);

  int totalSeconds = (hour() * 3600) + (minute() * 60) + second();
  lcd.print(totalSeconds);
  if(totalSeconds > 7806) {
    digitalWrite(2, HIGH);
  }
}

void blink() {
  lcd.print("time passed");
}

The setup uses the Time lib to set a date. It also  sets pin 2 as an INPUT and sets it it LOW. The attachInterrupt checks if pin 2 (0), changes, then function blink should execute.

In the loop, I am creating a string that prints out the time and displaying it to the LCD. I am also converting the time to seconds, so that I can easily compare two times. After 6 seconds (the timer starts at 7800), I am changing the value of pin 2 to HIGH.

This should indicate a change in its state and should and trigger blink, but it does not. Can anyone spot the mistake I made? Thanks in advance.

Since I don't have enough reputations to comment on your question I am going to drop my two cents here.

Since your question is a little bit vague, I am going to suppose that you don't want any external interrupts thus, you don't need to use the attachInterrupt function. I am going to suppose that there is no need to use timers' interrupts as well.

Have a look at the following code:

#include <Time.h>
#include <TimeLib.h>
#include <Adafruit_RGBLCDShield.h>
#include <utility/Adafruit_MCP23017.h>
Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();

void setup() {
  lcd.begin(16, 2);
  setTime(02, 10,00, 14, 03, 2016);
}

void loop() {
  char time_out[16];
  lcd.setCursor(0, 1);
  sprintf(time_out, "%02u:%02u:%02u",hour(),minute(),second());//use %x to get hex
  lcd.print(time_out);

  int totalSeconds = (hour() * 3600) + (minute() * 60) + second();
  lcd.print(totalSeconds);
  if(totalSeconds > 7806) {
    blink();
  }
}

void blink() {
  lcd.print("time passed");
}

You should know the following:

Commands inside void loop() is going to be executed for ever again and again. Especially lcd.print(time_out);. You had better refresh the LCD every 1 second.

After 6 seconds blink() is going to be executed many times (maybe forever) since it is inside the loop and if(totalSeconds > 7806) is going to be always true.

If you have any question let me know in the comment section.


Unreliable function of transistor, pump and ESP32 I have a 12 VDC pump, 8.5A, connected to a MOSFET transistor PSMN5R6-100PS,127.
The connection from the transistor to transformer, pump and a ESP32:
1    Gate   --> port to ESP32
2    Drain  --> (-) pump
3    Source --> Gnd ESP32, (-) transformer
(+) transformer to (+) pump
This is, as I understand it, how it ought to work. But with this configuration it doesn't...
But changing 3    Source --> (-) transformer, removing the Gnd connection to the ESP32, then it works. It, however, seems to be some kind of leakage in terms of current because the pump has a "clucking" sound, not fully activating, just making a sound. Sometimes it doesn't work at all, where a reset makes it work again. Any ideas how I can fix it reliably?

As can be seen from the datasheet for the PSNB5R6 (Fig 7) at 3.3V the MOSFET is barely even beginning to switch on.
You need to select a more suitable MOSFET that switches on fully at a voltage well below 3.3V, such as the STP40NF04L.


Displaying when Button has been pressed for LED and returning 1 I've just started using Arduino and I'm having trouble getting my code right.

Here is the task I need to do.

"Create a button read function
  Hint: the function header should be int checkbutton ( void )
in the loop function, add code such that if the button has been pressed (i.e. the checkbutton function
returns 1), a message is sent to the serial monitor with your username."

There are no errors in the code but nothing happens in the serial monitor when I press the LED button and it does not return 0 when i don't press the LED button.
Any sort of help would be appreciated!

Thanks!

int Button = 15; //LED and output are on the same pin

int last = 0;

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

int button() {
  pinMode(Button, INPUT);

  int current = digitalRead(Button);

  if (current and not last) {
    delay(5);

    pinMode(Button, OUTPUT);

    Serial.print("Hey");
    return 1;
  }

  else {
    pinMode(Button, OUTPUT);

    current == last;

    return 0;
  }
}

void loop() {
  if (button >=0)
  {
    button();
  }

  else
  {
    ;
  }
}

In your button() function, the line

if (current and not last) {

is less common syntax. The more common equivalent is:

if (current && !last) {

(see https://stackoverflow.com/questions/2376448/the-written-versions-of-the-logical-operators)

This line:

current == last;

Has no effect and is incorrect. This ( “==“ ) is not an assignment but a comparison and does not do what you want it to do.

I also think you have this the wrong way around. You want to save the “last” button state to compare it with the current button state when you call button() the next time. So you would need to set “last” to the current button state, like this:

last = current;

The next time you call button(), “last” contains the previous button state, so your comparison to the current button state will work.

And I think your button detection code would work better if you set last = current each time you call button(), whether a button has been pressed or not. Otherwise your code would repeatedly keep printing “Hey” until you stop pushing the button (unless that’s what you want). Like so:

int button() {
  pinMode(Button, INPUT);

  int current = digitalRead(Button);

  if (current &&  !last) {
    ...
    ...

    Serial.print("Hey");
    last = current; // Insert here
    return 1;
  }

  else {
    pinMode(Button, OUTPUT);
    ...

(This has not been tested but should give you a general idea).


Reprogram Atmega 16u2 on Arduino Mega with Arduino IDE? I had an Arduino mega 2560, suddenly Arduino didn't recognize my computer and I thought the problem is about Atmega 16u2 and I decided to copy hex file from another Arduino Atmega 16u2 and paste to damaged Arduino but it didn't work.
in fact, in our laboratory, we don't have any Linux and other software to reset or reprogram Atmega 16u2 on the other hand I know several methods to solve the problem but I need to know can I use the Arduino IDE to reset Atmega 16u2 without other software.
thanks a lot.

Yes, you can recover the firmware in 16u2 only with Arduino IDE installed. In subfolder hardware/arduino/avr/firmwares/atmegaxxu2/ of the IDE installation folder is the hex file of the firmware Arduino-COMBINED-dfu-usbserial-atmega16u2-Mega2560-Rev3.hex. The README.txt file in that folder has sample command line to upload the firmware with avrdude.


Why am I getting "expected primary-expression before '.' token"? I know this is a common question but the truth is every code is different. Sometimes it's hard to apply the concept to your code, it does not work. So please help me. What is wrong with this code? I got it from GitHub. I'm trying to compile it first before I can do a little modification, it sends temp and humidity data to ThingSpeak cloud servers.

#include <DHT.h>  // Including library for dht
#include <ESP8266WiFi.h>

String api_key = "YOUR API KEY"; // Enter your Write API key from ThingSpeak
const char *ssid = "YOUR WIFI SSID"; // replace with your wifi ssid and wpa2 key
const char *pass = "YOUR WIFI PASSWORD";
const char* server = "api.thingspeak.com";

#define DHTPIN 1 // pin where the dht11 is connected
DHT dht;

WiFiClient client;

void setup() {
  Serial.begin(115200);
  delay(10);
  pinMode(2, OUTPUT);
  digitalWrite(2, 0);
  Serial.println("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, pass);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
}

void loop() {
  int chk = DHT.read(DHTPIN);
  float hum = DHT.humidity;
  float temp = DHT.temperature;
  if (isnan(hum) || isnan(temp)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }
  if (client.connect(server, 80)) {
    // "184.106.153.149" or api.thingspeak.com
    String data_to_send = api_key;
    data_to_send += "&field1=";
    data_to_send += hum;
    data_to_send += "&field2=";
    data_to_send += temp;
    data_to_send += "\r\n\r\n";
    client.print("POST /update HTTP/1.1\n");
    client.print("Host: api.thingspeak.com\n");
    client.print("Connection: close\n");
    client.print("X-THINGSPEAKAPIKEY: " + api_key + "\n");
    client.print("Content-Type: application/x-www-form-
    urlencoded\n");
    client.print("Content-Length: ");
    client.print(data_to_send.length());
    client.print("\n\n");
    client.print(data_to_send);
    delay(1000);
    Serial.print("Temperature: ");
    Serial.print(temp);
    Serial.print(" degrees Celcius, Humidity: ");
    Serial.print(hum);
    Serial.println("%. Send to Thingspeak.");
  }
  client.stop();
  Serial.println("Waiting...");
  // ThingSpeak needs minimum 15 sec delay between updates, I've set it to 30 seconds
  delay(10000);
}

When I compile I get this error,

  Arduino: 1.8.10 (Windows 10), Board: "NodeMCU 1.0 (ESP-12E
  Module), 80 MHz, Flash,
  Legacy (new can return nullptr), All SSL ciphers (most
  compatible),
 4MB (FS:2MB OTA:~1019KB), 2, v2 Lower Memory, Disabled, None, Only Sketch, 115200"

    C:\Users\Agent 96\Desktop\thingspeak\thingspeak.ino: In function 'void loop()':

   thingspeak:37:20: error: expected primary-expression before '.' token

  int chk = DHT.read(DHTPIN);

                ^

  thingspeak:38:22: error: expected primary-expression before '.' token

  float hum = DHT.humidity;

                  ^

  thingspeak:39:23: error: expected primary-expression before '.' token

  float temp = DHT.temperature;

                   ^

  Multiple libraries were found for "DHT.h"
  Used: C:\Users\Agent
  Not used: C:\Users\Agent
  Multiple libraries were found for "ESP8266WiFi.h"
  Used: C:\Users\Agent
  exit status 1
  expected primary-expression before '.' token

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

Please help, I'm kind of a beginner.

Change three lines right after loop() to these:

  int chk = dht.read(DHTPIN);
  float hum = dht.humidity;
  float temp = dht.temperature;

Change 'DHT' into lower case letters. DHT is the class and dht is the object of the DHT class.

Also you have multiple copy of these libraries: DHT.h and Esp8266WiFi.h. Check your cuurent directory where your Arduino code is and also Documents->Arduino->Libraries directory. These libraries should be in the  Documents->Arduino->Libraries directory.


Serial communication and Arduino program in C When I flash this simple code (using Arduino-Makefile):

#include <avr/io.h>
#include <util/delay.h>
#include <Arduino.h>

void init_io(void) {

    // open serial port
    Serial.begin(9600);
    while (!Serial);
    Serial.println("Comm-link online");

}//END: init_io

int main(void) {

    init_io();

    while (1) {

        // send data only when you receive data:
        if (Serial.available() > 0) {

            // read the incoming byte:
            int incomingByte = Serial.read();

            // say what you got:
            Serial.print("I received: ");
            Serial.println(incomingByte, DEC);

        } else {

            //  Serial.println("No serial ");

        }

    }//END: loop

    return 0;
}//END: main

I only see first two chars printed in the serial output:

  ~$> Co

The input also does not work as intended - tested on two independent microcontrolers, Mega and Uno. I'm not sure what's the cause of this behaviour. Here's the Makefile:

BOARD_TAG    = uno # megaADK uno
MONITOR_PORT  = /dev/ttyACM0
ARDUINO_LIBS =

include $(ARDMK_DIR)/Arduino.mk

It's definitely not a hardware problem, I've used serial i/o before in other projects.

When using the Arduino core library, you normally do not write a
main() function. Instead, you write setup() and loop() and rely on
libcore's provided main() for calling them.

If you nevertheless want to provide your own main(), then you should
call init(); (with no arguments) before you try to use the library.
Adding this single call makes your program work on my Uno.

However, since it does not seem to be officially documented, this trick
may not be safe against upgrades in the core library. Writing setup()
and loop() should be more future-proof.


Johnny-five driving LCD Matrix or call Arduino library from Johnny-five I would like to know if it's possible to drive an LED Matrix like this one with johnny-five.
If not, how can i call Arduino library/code from johnny-five.

If I Write method on sketch into the Arduino, can I call them from J5 REPL?

After research, it can't be done, as J5 use firmata to drive the Arduino, the only way is to write a library to use with.


Reading and interpreting Serial information I am trying to use a Raspberry Pi to control a ESC and for that I am sending the instructions for the ESC using serial. My problem is that when i send the instructions i can not interoperate them, and by interoperate I mean check what the first letter is and then remove it and make the Arduino output a PWM signal. My problem is when I use the serial monitor to send an instruction it firstly comes up on several lines, and when I try and look at the first letter of the string the if statement thinks it is true for all inputs of "FirstLetter" my function to get the serial input it

String readSerial()
{
  char SerialInput;
  String Data = "";
  if (Serial.available())
  {
    SerialInput = Serial.read();
    Data.concat(SerialInput);
    //Serial.println(Data);
  }
  return Data;
}

the function that should interoperate  the information from readSerial() is

void DecodeInput()
{
  String input = readSerial();
  if (input != "")
  {
    char FirstLetter = input.charAt(1);
    if (FirstLetter = 'U')
    {
      Serial.println("Hello World");
      //input.setCharAt[0, '');
      //SetPower('U', Power);
    }

Two things immediately jump out at me:

char FirstLetter = input.charAt(1);

charAt(1) is the second letter, not the first - the first is charAt(0).

if (FirstLetter = 'U')

That is saying "If I have been successful in assigning the value 'U' to FirstLetter then..." - "=" is assignment, you need "==" for comparison.

Also your readSerial() function is complete junk.  It's not doing anything at all like you think it is.  You should read this to better understand Arduino serial reading: http://hacking.majenko.co.uk/reading-serial-on-the-arduino


Why is delay(1000) breaking my serial communication? I have the following sketch...

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
}

void loop() {
  if(Serial.available() > 0){
    Serial.println("Hello world from Ardunio!");
  }
}

This works great with my client code...

import SerialPort from 'serialport';
const port = new SerialPort('/dev/ttyACM0', {
  baudRate: 115200,
  autoOpen: false
})

port.open(function (err) {
  if (err) {
    return console.log('Error opening port: ', err.message)
  }

  // Because there's no callback to write, write errors will be emitted on the port:
  console.log("port opened");
  port.on('readable', function () {
    console.log('Data:', port.read())
  })
})

Now I want to slow it down so I change the sketch to...

void loop() {
  if(Serial.available() > 0){
    Serial.println("Hello world from Ardunio!");
  }
  delay(10000);
}

I would expect this to delay each message by 10 seconds, however, it seems to never rerun so I do not get any messages. What am I missing? Why would delay break the loop?

NEVER use delay() in a loop - its a bad habit you get used to and then you return later on with complex code asking why nothing is happening or your webserver is dead for 10 seconds every time you receive a request.

So instead of

void loop() {
  if(Serial.available() > 0){
    Serial.println("Hello world from Ardunio!");
  }
  delay(10000);
 }

you would do

unsigned long timerStart = 0;
unsigned long myTimer = 10000;

setup(){....}

 void loop() {
  if(Serial.available() > 0 ){
     if(millis() - timerStart > myTimer){      // non blocking
       Serial.println("Hello world from Ardunio!");
       timerStart = millis(); // reset timer
     }
   }
 }

What your code does at the moment is enter the IF clause if exactly in this millis the buffer is filled, then wait for ten seconds ignoring whatever you do. Next chance tohit and so on. Delay() is blocking processing => not a good thing todo in communication scenarios,


Arduino Mini Pro not working with my Neopixel project my project involves 9 Neopixel LEDs. I have tested my code with my Arduino Uno board successfully. I'm using a mix of breadboard, jumper wires, and solder to connect everything. Powering the strip of 9 LEDs with 4 AA NiMh rechargable batteries, showing 5.2v on the meter. I've put a capacitor (1000mF 25v) in the circuit, right at the power source.

But when I upload the same code to my Mini (5v/16MHz) and swap it in in place of the Uno, I get nothing. No matter how much I jiggle wires or provide a good ground (which helped me get good results from my Uno). Every now and then by messing with wires, or as a few minutes go by, the first few lights might light up, but not in the right colors and no animation.

Just to test the Mini board I uploaded the sample program "blink" and the mini runs that one properly. So I'm certain my code is getting on there. My program is definitely bigger and involves some quick changes (I'm making an "ebbing" glow of supernatural eyes). Connecting the Mini to the Neopixel strip I soldered a wire with a female jumper onto the board, and my strip of lights has a wire soldered on with a male jumper. As a side note, it takes a little physical handling to get the project to work with the Uno (like pressing a little bit on the data wire in it's plug on the Uno or using a jumper wire in the breadboard clamped in a metal measuring tool and my hand to ground out the circuit). So maybe I'm just experiencing some of the shortcomings of the Mini, but I was under the impression that it would do just about anything the Uno could do. Especially in terms of just providing a data line for the LEDs.

I'm new to Neopixel. This is my first project in fact. So it is entirely possible I'm doing something wrong or there's something I just missed completely, or maybe my luck just sucks and I have some piece of faulty hardware... No idea.

Any suggestions would be most appreciated!

As I was playing around today I found a solution. Powering the board through the FTDI adapter, which in turn was being powered by a USB juicepack charger, wasn't supplying enough juice and/or ground. It was enough for the Uno to work, so that's what was confusing me. I soldered in a 9V battery and clamped down on the pins with a wrench to ground it out. That made the board happy and it kicked into gear and lit my project up perfectly. It's pretty ghetto but it works! Yeah! :D


Arduino Leonardo clone voltage question I'm planning my first Arduino project which involves a MPU-6050 accelerometer(3.3V) and a RGB led(5V). I've found this Arduino Clone but i'm not sure if it has 3.3V and 5V outputs that I can use. The pins do exist on the original Leonardo board but i'm not sure if the clone contains them as well.

That has a 5V pin (Vcc) but no 3.3V. Also the 5V pin can't provide more than a few hundred mA.

Better specifications are here: https://www.sparkfun.com/products/12640


How can I use Python from a sketch? I'd like to be able to use Python from a sketch. According to the Arduino playground, one can use PySerial from a computer to talk with an Arduino via Python.

It looks like from that page you can also use various API's to use Python with an Arduino from a computer. However, I'd like to know if you can execute Python directly from a sketch. It would be nice because then you could execute Python directly from a sketch, and not all of it would have to be written in Python.

If this is not possible, is there an easy way to execute Python on an Arduino? Looking at the various API's it was hard to determine exactly what they did, and if you could execute a .py script from a computer or from anything on the Arduino.

It looks like from that page you can also use various API's to execute
  Python directly on the Arduino.

I don't see that, at all. All those links show you how to communicate with the Arduino over serial using Python on the host side.

You'd need a python interpreter to be able to run python on the Arduino. There is the Python On A Chip project and it seems like they have support for the Mega.

  2010/09/01 (1bdb8d31f27b) New platform: Arduino Mega.

Some more info from the PyMite page:

  any device in the AtMega family which meets these requirements: 20KiB
  Flash and 4K RAM, will run today

I doubt you'll find anything that'll let you mix Arduino and Python code in the same sketch.


How to trigger NodeMCU sketch from Arduino Leonardo Micro Pro? So this is probably a very simple question. I have my NodeMCU set up and working where it connects to wifi and sends a push notification. Currently it does that automatically when connected to power.

What I want to do is connect it to my Leonardo Micro so that at a part in the Leonardo sketch it sends a signal to the NodeMCU to run the sketch to trigger the push notification. So simply, which ports should I connect and what code should I change.

Here is my working NodeMCU code.

    #include <ESP8266WiFi.h>

// Wifi Settings
const char* ssid = "MySSID";
const char* password = "MyPassword";
// Pushover settings
char pushoversite[] = "api.pushover.net";
char apitoken[] = "MyAPIToken";
char userkey [] = "MyUserKey";
int length;
WiFiClient client;
void setup() {
  Serial.begin(9600);
  delay(10);

  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

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

  // Print the IP address
  Serial.print(WiFi.localIP());

}

void loop()
{
 pushover("OMG, Yes it works!!!");
 delay(60000);
}

byte pushover(char *pushovermessage)
{
 String message = pushovermessage;

 length = 81 + message.length();

if(client.connect(pushoversite,80))
 {
   client.println("POST /1/messages.json HTTP/1.1");
   client.println("Host: api.pushover.net");
   client.println("Connection: close\r\nContent-Type: application/x-www-form-urlencoded");
   client.print("Content-Length: ");
   client.print(length);
   client.println("\r\n");;
   client.print("token=");
   client.print(apitoken);
   client.print("&user=");
   client.print(userkey);
   client.print("&message=");
   client.print(message);
   while(client.connected())
   {
     while(client.available())
     {
       char ch = client.read();
       Serial.write(ch);
     }
   }
   client.stop();
 }
}

And my Leonardo code

#include <Keyboard.h>
#include <Mouse.h>
char returnKey = KEY_RETURN;
char tabKey = KEY_TAB;
void setup() {
  Keyboard.begin();
  Mouse.begin();

  delay(4000); //Testing Delay
// Language Select Screen
  Keyboard.write(returnKey);
  delay(30000);
// Welcome Screen
  Mouse.click(MOUSE_LEFT);
  delay(100);
  Keyboard.write(tabKey);
  delay(100);
  Keyboard.write(tabKey);
  delay(100);
  Keyboard.write(' ');
  delay(2000);
// Select Keyboard
  Keyboard.write(tabKey);
  delay(100);
  Keyboard.write(tabKey);
  delay(100);
  Keyboard.write(tabKey);
  delay(100);
  Keyboard.write(' ');
  delay(2000);
  TELL NODEMCU TO SEND PUSH NOTIFICATION HERE
}

void loop() {
}

As a reminder the pinout on my boards are as follows.

Leonardo:

NodeMCU:

HW part:
It's like button, simply connect arduino micro pin to nodeMCU pin and GND of arduino to GND of nodeMCU.
It's also good idea to use two resistors as voltage divider because arduino micro works with 5V and ESP8266 (nodeMCU) with 3V3. 5V can destroy ESP8266 but this thing is still not really clear.
Resistor divider connect as in this link link about resistor divider for uart but instead of TX put arduino micro and instead of RX nodeMCU.
resistor divider schematic

Code part:
On the arduino micro part use:

In void setup():
pinMode(PIN, OUTPUT);

In your marked place:

digitalWrite(PIN, HIGH);
delay(100);   //short wait time
digitalWrite(PIN, LOW);

nodeMCU part:

In void setup():
pinMode(PIN, INPUT);

Remove everything from void loop() and put there this:

if(digitalRead(PIN) == 1) pushover("OMG, Yes it works!!!");

In both codes select the PIN according to your choice.


Midi controlled LED by USB I am trying to create something that will allow me to control an individually adressable LED strip using an electric piano using its midi output.

Some things to note:

The piano can output midi either via USB or via standard midi connectors.
I have an Arduino Uno and an Arduino Mega available
I'm using a WS2812B strip with +ve, ground and data cables

I don't believe there's a way to read midi from my piano direct to the arduinos without reflashing the USB controller. For this reason I'm connecting via USB to my mac.  On my mac I've written a program which reads the midi input and can understand it and send it on to somewhere else.

The arduino for the light strip I think I can program pretty easily but I have some questions:

If I need to power the LED strip, should I be powering it from the arduino power or giving it its own power source with common ground?
Is splitting it up into midi -> computer, computer -> arduino, arduino -> LED strip sensible? If not how should I be going about it?
Am I making life difficult by going the USB route for Midi or should I switch to midi connectors and connect direct to the arduino somehow?

I did some time ago something very similar, except not using USB, and on an STM32 (Arduino compatible STM32F103C8T6), but the principle is similar.

Regarding another MIDI test I did on an Arduino, I used the 47 Effects library and for the WS2813 (software-compatible with WS2812B) the FastLed library.

One MIDI port is easy to use (supported by 47 Effects), which uses the single UART of the Arduino UNO.

You have to write a small program to convert the MIDI notes to WS2812 LED data, which is not much more than filling in a structure. Mapping 61 or 88 notes to 30, 60 or 144 LED notes is not so easy, just clip the notes, or use some mapping factor.

You cannot use the Arduino for powering the LED strip, use a separate adapter for that. Only the line signal comes from the Arduino, and connect GNDs together.

The Arduino should be fast enough to both read MIDI, translate it to LED data (unless you make some very time consuming algorithm) and send the data.


Charlieplexing 30 LED sections with a max of 27 LEDs at the same time? So basically, I'm trying to make a digital wall clock and using digital numbers, I have 7 sections of LED's per number, 4 numbers and one section for the colon in between them. A total of 30 sections. The colon will toggle every second so the the most possible simultaneously glowing sections is 27. That's because of the time 08:08.
Is there any way to make this work with an arduino? Possibly by Charlieplexing the arduino into 30 sections, using 6 pins. Or is there something out there that has 30 pins!?

The problem of course with charlieplexing, is that you need it to become rapid pulses. I'm sure I'm going to need some help with this, and also with laying out a schematic.

To be clear, this is how the led sections are going to be laid out. I also know I'm going to need an npn transistor for every single one of them. the biggest section uses 20 LEDs.

Thanks!

I would consider 74HC595N's. These are shift registers, which can control 8 'outputs' using less pins on your Arduino.

These are very cheap (buy them per 10) and you can daisy chain 4 of them, having 32 outputs, using only 5 pins of your Arduino. This would fit perfectly with your 30 sections.

Each of the 30 outputs can be used to control a transistors to control one LED sections.

See for an example for using shift registers with the Arduino: ShiftOut

Also you might need this: ULN2803 darlington drivers for each output (4 total).


Arduino recognize specific sound? I'm wondering if Arduino is able to not just measure sound and work based on hearing a sound that is "loud enough", but if it is able to identify a specific sound (say the first few seconds of a song). Is this possible, and how would one go about doing so?

If identifying the first few seconds of a song isn't really feasible, is it at least possible to do so with a consistent (but particular) pitch (rather than a general loudness threshold)?

As stated in other answers, sound recognition is completely out of the
realm of what an Arduino can do, but recognizing a specific pitch is
possible.
However, contrary to previous answers, I would recommend against using
an FFT. The FFT is the right tool when you need to get all the
frequency components. It is, however, overkill when you want to look at
a single frequency. Given the low processing power at your disposal, I
suggest you try instead an homodyne detection scheme. An Arduino
Uno, or similar board, has enough resources to sample an input at
9.6 kHz, and extract in real time a specific frequency component.
See for example this homodyne detection program.


Arduino with multiple buttons - will power be an issue? I have a spare Arduino Uno lying around, which I figured I could attempt to turn into a game controller. First clear issue, that immediately popped up, was that there are not enough digital input pins on the board, but I think I can get around that by using analog pins with appropriate external resistors (is that actually a possibility?).

Another one, more severe, is that I'm not sure how I would need to go around wiring microswitch buttons with the board. Assuming they short the circuit when pushed (SPST), I could simply wire one contact to an input pin, set to INPUT_PULLUP mode, and connect the other to ground. However, since I know little about how such circuits work, I'm immediately in doubt about two things. Considering the board would be used as a controller, an external power source is out of question and I'd only want to rely on the USB power. Since I want to use plenty of buttons (up to fifteen), out of caution I'm worried that shorting this many input pins to the ground at once could overload the... regulator I think?

So my question is this: is it safe to use multiple, potentially simultaneously pressed, buttons connected to input pins on an Arduino Uno board, powered solely from a USB port? Additionally, just to be clear, is it normal to connect them all to a common ground on the board?

Yes, it is safe to connect multiple buttons to ground. The pull-up resistors have a fairly high value - about 10 kΩ and we know from Ohm's Law that

I = V / R = 5 V / 10k = 0.5 mA

per button. Your USB power is good for about 500 mA.

Welcome to StackExchange.


arduino PWM temperature inexpected results I am making a system which regulates the temperature of a plate.
using the PID library
I programed the system as followed:

/********************************************************
 * PID Basic Example
 * Reading analog input 0 to control analog PWM output 5
 ********************************************************/

#include <PID_v1.h>
#include "math.h"

int val, output2;
//Define Variables we'll be connecting to
double Setpoint, Input, Output;
//Specify the links and initial tuning parameters
PID myPID( &Input, &Output, &Setpoint,0,20,20, DIRECT);

void setup()
{
  //initialize the variables we're linked to
  Setpoint = 37; //temperature a reguler

  //turn the PID on
  pinMode(9, OUTPUT);
  myPID.SetOutputLimits(-100, 100);
  myPID.SetMode(AUTOMATIC);
  Serial.begin(57600);
  while (!Serial);
}

void loop()
{
  // phase haute
  //delay(100-output2);
  val = analogRead(1);
  float mv = ( val/1024.0)*5000;
  Input = mv/10;
  myPID.Compute();
  {   output2 = map(Output, -100, 100, 0, 200);
      Serial.print("output is :");
      Serial.println(output2);
      digitalWrite(9,HIGH);
      delay(output2);
      // phase basse
      digitalWrite(9,LOW);
  }
  //analogWrite(5,Output);
  //Serial.print("input temperature is :");
  //Serial.println(Input);
  // Serial.println(Output);
  // Serial.println(Input);

}

As you can see in the code the output result is between 0 and 100.
the temperature desired in the plate is 37 degre. and the actual temperature is 24 degre. consequently, the program supposes to set the value of the output to the max value to reach to 37 degre.
But the problem is my output is setting to different values as you can see here:

what can be the problem here ? thank you in advance

As Gerben said in a comment, you should add the value of Input to the serial print, to facilitate problem diagnosis.  As your question stands, one can only speculate about what the problem might be.  My speculation is that the system is unable to cope with parameters (Kp, Ki, Kd) = (0, 20, 20), ie, that it's unstable and unresponsive without proportional control.


Why can't I define the constant A0 (some pin) to something? What I'm doing wrong or why is it not working:

#define Uin A0;

void setup() {
}

void loop() {
  analogRead(Uin);
}

Results in a Error (expected ')' before ; token.

I thought #define just exists as a place holder.

Because you have a ; at the end of your #define.

#define Uin A0;
analogRead(Uin);

becomes:

analogRead(A0;);

The Arduino website mentions this in their reference. For more in-depth detail about the C pre-processor you can read the (rather large) manual here.


Trouble trying to turn a stepper while a button is pressed down So i'm currently coding a little device that rotates a step motor round one 8th of a full revolution every time a button is pushed. the motor is attached to a question reel with 8 questions on it, each one is viewable through a little window covering the reel after each button press. the thing im concerned about is that if even one of the question sections is slightly larger or smaller than the others, it will cause the question to become misaligned with the window after a certain number of run throughs.

in order to combat this I want to have a back up code that simply rotates the stepper while the button is held down. this will allow me to manually reset the reel to its proper positioning should the questions become misaligned. im not achieving this however, and was hoping someone may be able to detect where the issues are in my code?

#include <Stepper.h>

#define STEPS 2048

Stepper myStepper(STEPS, 8, 10, 9, 11);

const int  buttonPinBlue = 6;

void setup() {

  myStepper.setSpeed(5);
}

void stepp() {

 myStepper.step(1);

  pinMode(buttonPinBlue, INPUT);
}

void loop() {

 if (buttonPinBlue == HIGH) {

  Serial.print("pin is high");

   stepp();
  }

}

also just as a side note, the stepper runs fine using the 'define steps' value and the speed that I've set here, the issue appears to be that the button press is not being detected

You don't set the pin itself:

Change

if (buttonPinBlue == HIGH) {

to

if (digitalRead(buttonPinBlue) == HIGH) {

Also you don't have to set the pin every time, only one time is enough: in function setup should be the following line (and it can be removed from the function stepp:

pinMode(buttonPinBlue, INPUT);

Note that if you want to use a 'click' to move to the next item, you have to debounce the button; on the Arduino site check for button debouncing: https://www.arduino.cc/en/Tutorial/Debounce


Clone vs Counterfeit (Arduino) On this page on Arduino's website, it states

  "HUNDREDS OF COMPANIES AROUND THE WORLD ARE USING IT [Arduino Software] TO PROGRAM THEIR
  DEVICES, INCLUDING COMPATIBLES, CLONES, AND EVEN COUNTERFEIT."
  (Emphasis Added)

With open source electronics, what is the difference between a clone, and a counterfeit?

This is not gospel, but here is what those terms are generally used to indicate (as I understand it):

compatible: a dev board which is compatible with the Arduino IDE/toolchain. The Arduino UNO uses an ATmega328 MCU, while other platforms may use different MCUs i.e. there are multiple MCUs that are compatible with the Arduino IDE. It may or may not have the same form factor. Keep in mind that this term can also be used for shields, "Arduino-compatible" shields are add-on boards that are meant to mate with an Arduino. The Sparkfun RedBoard is an example.
clone: a dev board which has the same (or very similar) circuitry as an Arduino and the same physical board/layout. They are branded differently, but are, for all intents and purposes, exactly the same as a real Arduino. These boards are permitted under the open-source licensing of the Arduino design. An Freeduino might be an example.
counterfeit: a dev board which is identical to an original Arduino, and is branded and sold as an original Arduino. As I understand it, the open-source licensing does not permit this, however, this does not deter the flood of shops churning out counterfeit Arduinos. A search on eBay or Aliexpress will turn up loads of examples; note the Arduino guide to spotting counterfeits, in general, the silkscreen is blue and the quality of assembly is not quite as good.

The difference between "compatible" and "clone" is a bit blurry, but it's not really important. The main difference between counterfeit and non-counterfeit is that counterfeit Arduinos are boards that are not sold by Arduino but are branded as such.


Change the baud rate of HC-05 #include <SoftwareSerial.h>

SoftwareSerial BTSerial(10, 11); // RX | TX

void setup() {
  pinMode(9, OUTPUT);
  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
  digitalWrite(9, HIGH);
  Serial.begin(9600);
  Serial.println("Enter AT commands:");
  BTSerial.begin(38400);
  // HC-05 default speed in AT command more
}

void loop() {
  // Keep reading from HC-05 and send to Arduino Serial Monitor
  if (BTSerial.available())
    Serial.write(BTSerial.read());

  // Keep reading from Arduino Serial Monitor and send to HC-05
  if (Serial.available())
    BTSerial.write(Serial.read());
}

I have tried this code but I am not able to change the baud rate. Please suggest me a solution.

I played a lot with HC-05 and HC-06 until I understand the way they work. Now i've big Android App communicating with HC at 115200 bauds and sending and receving heavy data.

I hope these tips will help you and other guys and save you time:

1) the way the HC-05 and HC-06 detect end of AT command is different:

HC-05 (can be slave and master): each AT command must end by CRLF. So or you add CRLF in your Android code or you select the option "CRLF line ending" in your console.

HC-06 (only slave): need a "time" between AT Command. According to the data sheet if there is more than 1 sec, the HC consider this is the end. Even if your question is about the HC-05 I think it can be VERY interesting to understand the big problem which can happened with the "delay" between AT.
If you use a communication at 9600 bauds and type AT commands on serial monitor and echo both what HC reply and what you send, you will have such things: type AT+VERSION and see on serial monitor AT+OVKERSION  Why ? Because as the delay between each char is long, as soon as the HC had receive "AT" he thinks that's the command and start to reply "OK".
So with a HC-06 you must send the AT command in one "shoot" and then add a delay of 2 sec to be sure.

2) Problem of settings.
The HC save the speed you set as the name and the pin code. So trying to set the pin, name and speed in the setup funcion is not usefull as at each time the Arduino will reset, each time you'll try to set the data.
Also, factory setting of HC seems to be 9600 bauds.
So you have to create a small sketch, which you'll use only ONE time to set the HC. Like this:

Serial.begin(9600);
delay(2000);

// AT+NAMEXXX where XXX is the new name
Serial.print("AT+NAMEJOHNDOO");
delay(2000);

// AT+PINXXXX where XXXX new code (4 number)
Serial.print("AT+PIN1999");
delay(2000);

// AT+BAUDX where X from 1 to 8
// 1 -> 1200 Bauds
// 2 -> 2400 Bauds
// 3 -> 4800 Bauds
// 4 -> 9600 Bauds
// 5 -> 19200 Bauds
// 6 -> 38400 Bauds
// 7 -> 57600 Bauds
// 8 -> 115200 Bauds
Serial.print("AT+BAUD8");

This for HC-06. For HC-05 you must add CRLF and you don't need the delay.

Important: as, at the end of this sketch, the HC is now at 115200 bauds, you must havea serial.begin(115200) for comunicating with it. If you run this sketch two time, the second run will do nothing as the Arduino will try to comunicate at 9600 bauds with a HC listening at 115200.

3) Problem of speed.
On the Arduino, you can use the software serial lib only if you plan to send and receive at up to 19200 bauds. Some say it work at 38400 but I've had problems at this speed.
The best way it to avoid Software serial and use directly the basic RX and TX of the Arduino. Using that you can run at 115200 without any problem.

Even if this answer is a bit "outside the question" I hope this will help you working with the HC.


A question about including libraries I'm a beginner in creating my own libraries so the following might contain some stupid stuff.

Anyways, I'm using NRF24L01+ modules for wireless communication and I've been utilizing the magnificent RF24 library (https://github.com/TMRh20/RF24) to operate these modules using Arduino. I wanted to clean up my code and decided to write my own library that uses the R24 library. My own library would contain all the subroutines that handle TX and RX functions.

Problem is that the RF24 library is initialized using e.g.

/* Hardware configuration: Set up nRF24L01 radio on SPI bus plus pins 7 & 8 */
RF24 radio(7,8);

To begin using the NRF24L01+ one would the use the RF24 library like for example:

byte addresses[][6] = {"1Node","2Node"}; // Radio pipe addresses for the 2 nodes to communicate.
Serial.begin(57600);
printf_begin();
radio.begin();

radio.setPALevel(RF24_PA_HIGH);
radio.setCRCLength(RF24_CRC_16);

radio.setRetries(2,15);
radio.setChannel(RFChannel);
if(radioNumber){
radio.openWritingPipe(addresses[1]); // Both radios listen on the same pipes by default, but opposite addresses
radio.openReadingPipe(1,addresses[0]); // Open a reading pipe on address 0, pipe 1
}else{
radio.openWritingPipe(addresses[0]);
radio.openReadingPipe(1,addresses[1]);
}

if(radioNumber == 1){
radio.startListening(); // Start listening
}
radio.printDetails();

Well, now I would like to make a library that would allow me just to call setup to handle all of the above. My library would be called RadioComm so I would call in my main code:

RadioComm rComm();

setup() {
rComm.setup();
}

The problem is that how do I use the RF24 library and all its functions in my library? To initialize the RF24 library in my own library I would have to call somehow this

RF24 radio(7,8);

and use all the radio. commands. How do I tell my own library that everything starting with "radio." is related to RF24 library because right now I'm getting this:

RadioComm.cpp: In member function 'void RadioComm::setup()':
RadioComm.cpp:20:18: error: 'radio' was not declared in this scope
radio(pin1,pin2); // Set up nRF24L01 radio on SPI bus plus pins 9 & 10

Below are my .h .cpp and .ino files

Lib_test.ino

#include <RadioComm.h>
#include <RF24.h>
#include <SPI.h>

RadioComm rComm;

void setup() {

rComm.setup();

}

void loop() {

}

RadioComm.h

#ifndef RadioComm_h
#define RadioComm_h

#include "Arduino.h"
#include <RF24.h>

struct dataStruct{
unsigned long id;
float value1;
float value2;
float value3;
float value4;
};

class RadioComm
{

public:

RadioComm();
void setup(void);

private:
int pin1;
int pin2;

};

#endif

RadioComm.cpp

#include "Arduino.h"
#include "RadioComm.h"
#include <RF24.h>
#include "printf.h"

RadioComm::RadioComm(void)
{}

void RadioComm::setup()
{
byte addresses[][6] = {"1Node","2Node"}; // Radio pipe addresses for the 2 nodes to communicate.
radio(pin1,pin2); // Set up nRF24L01 radio on SPI bus plus pins 9 & 10
Serial.begin(57600);
printf_begin();
radio.begin();
radio.setPALevel(RF24_PA_HIGH);
radio.setCRCLength(RF24_CRC_16);

radio.setRetries(2,15);
radio.setChannel(RFChannel);
if(radioNumber){
radio.openWritingPipe(addresses[1]); // Both radios listen on the same pipes by default, but opposite addresses
radio.openReadingPipe(1,addresses[0]); // Open a reading pipe on address 0, pipe 1
}else{
radio.openWritingPipe(addresses[0]);
radio.openReadingPipe(1,addresses[1]);
}

if(radioNumber == 1){
radio.startListening(); // Start listening
}
radio.printDetails();
}

Any help is appreciated.

Thanks.

Firstly, to address your compilation error:

RadioComm rComm();

That is not a constructor, that is a function prototype. When you have no parameters to a constructor you must not include the brackets or it confuses the poor little compiler.

RadioComm rComm;

Now - to address your main question.  Well, there's many ways of doing it, but the way I always tackle this is to have your sketch define the RF24 object and pass it to the library for later use.

In the class definition, in the private section, add:

RF24 *radio;

Then change the constructor to have:

RadioComm(RF24 &r);

The constructor itself would then read:

RadioComm::RadioComm(RF24 &r) {
    radio = &r;
}

Now throughout your library, instead of working with radio.whatever you need to work with radio->whatever since you are now using a pointer to an object not the object itself.

Then in your sketch you need to adjust your constructor to be:

RF24 myRadio(7, 8);
RadioComm rComm(myRadio);

The beauty of this is it decouples the configuration of the RF24 class from the RadioComm class, so you can use the same library in a different situation on a different board with different pins without having to change the library - just change the RF24 constructor in your sketch.

It also gives you direct access to the RF24 class in your sketch so you can do any advanced manual tweaks outside the library should you wish to.


Arduino Fio: Battery/Solar Powered Weather Station I am trying to make a Solar Powered Weather Station. I'm using the Arduino Fio, with a BMP180 and a DHT22 as the sensors. There are sleep modes activated with the Fio and the Xbee. It seems like the battery capacity requirements, after measuring, around about 664 mAh per day.

The Fio has a built in LiPo charger (MCP73831/2). Is this 3.7V 2000mAh battery safe to plug into the Fio as its battery source? Here is the datasheet from the link just provided. I'm not an engineer and I want to make sure that this is a safe device.

Once determining the correct battery, I will like to pair it with a solar panel.

Thanks for the help

You have a LiPo charger module. It's meant to charge single LiPo cells. It is therefore, the intended safe use that you can connect any single LiPo cell to it. All single cell LiPo batteries are nominally 3.7V. The only real question might be -- does the charging circuit try to charge too fast?

A 2000mAh pouch LiPo can safely be charged at 1X the capacity. So a maximum current of 2000mA for an hour in this case. The battery management chip has a maximum charge current of 500mA, so there's no way it can reach over 2000mAh of current while charging.

The datasheet for the battery management chip shows a R_PROG resistor that basically sets the maximum charge current.  Section 5.1.2 shows the formula for charge current regulation at:

I_REG [mA] = 1000 [V] / R_PROG [kΩ]

The schematic for the Fio shows they have used a 2k ohm resistor.

Thus: I_REG [mA] = 1000 [V] / 2 [kΩ] = 500 [mA] (the maximum the chip can operate)


What means the ~ symbol in the code? I'm learning Arduino (school and from myself).

We have the following code:

temp = Wire.read();
temp = ~temp;
temp = temp - 1;

This code is made to read, then print positive and negative values from a temp sensor. If you need more parts of the code, let me know.

I don't understand what does the ~ symbol, can someone help me?

Thanks.

As always, ~ in C++ is bitwise negation.


error while loading libtinfo.so.5 - SOLVED I just installed the 1.6.7 version and want to upload it a sketch to Arduino UNO hardware. I get error message:

  /home/pali/Irataim/TarBalls/Arduino/arduino-1.6.7/hardware/tools/avr/bin/avrdude: error while loading shared libraries: libtinfo.so.5: cannot open shared object file: No such file or directory

I'm on Gentoo linux operating system.

How can I solve this problem?

By following this link:

https://forums.gentoo.org/viewtopic-p-7815500.html?sid=f67283068e3655b2f9e259a2097efef6
I just add tinfo USE flag to ncurses package, re-emerged it and can run Arduino IDE that I emerged from Gentoo repository.

Install libtinfo5, the terminfo library.

If that doesn't help, you can try to debug the problem yourself. First,
check which libtinfo avrdude is looking for:

ldd arduino-1.7.8-linux64/hardware/tools/avr/bin/avrdude_bin | grep libtinfo

On my Ubuntu, I get this:

libtinfo.so.5 => /lib/x86_64-linux-gnu/libtinfo.so.5 (0x00007fa74a888000)

Next, see where your libtinfo is installed:

find /lib /usr/lib -name 'libtinfo*'

On my system I get:

/lib/x86_64-linux-gnu/libtinfo.so.5
/lib/x86_64-linux-gnu/libtinfo.so.5.9

Do you have any discrepancy between the two?


How can I convert PID correction values to an PWM brushless command? Please I'm working on a quadcopter, and I have to made my own flight controller based on arduino uno.
First of all please how can I get a filtred angular velocity and linear acceleration from the MPU6050, is the following code give us the angular velocity in deg/sec and the linear velocity in m/s² ?

accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

and is this pid value in this following code is right ?

  accel_reading = ax;
  accel_corrected = accel_reading - accel_offset;
  accel_corrected = map(accel_corrected, -16800, 16800, -90, 90);
  accel_corrected = constrain(accel_corrected, -90, 90);
  accel_angle = (float)(accel_corrected * accel_scale);

  err = angle_setpoint - accel_angle  ;

  P = Kp * err ;
  I += (Ki * err) ;
  D = Kd * (err - errp);

  pid = P + I + D;

Thank you.

How can I convert PID correction values to an PWM brushless command?

you have to do that yourself. you have to figure out first how to correct a pid value directionally. for example, should you increase the duty cycle if pid is positive or negative?

after that, you will need to map the pid value to a range for your pwm dc.

basically, it is application / task specific, and you are in complete charge.


Different functions using 2 buttons I'm currently learning Arduino. So right now I'm trying to create an Arduino app that will use buttons, LEDs and RGB.

So I have 2 buttons, 8 LEDs and an RGB. The first button is the function switcher: when you press it the LED will light according to their function. The second button is the function activator so right now here's I want to do:

Function 1: Turn on/off RED light
Function 2: Increase RED light brightness by 5; if already at 255, reset at 0
Function 3: Turn on/off GREEN light
Function 4: Increase GREEN light brightness by 5; if already at 255, reset at 0
Function 5: Turn on/off BLUE light
Function 6: Increase BLUE light brightness by 5; if already at 255, reset at 0
Function 7: Turn on ALL lights, all brightness to 255
Function 8: Turn off ALL lights, all brightness to 0

I already started coding and I'm stuck at turning on and off the red light. Here's my code:

const int red = 5;

int b1, b2; //Buttons
int dir = 0;
int light = 11;
int func = 0;
boolean buttonValue = true;
boolean buttonState = true;

void setup() {
  pinMode(2, INPUT);
  pinMode(3, INPUT);
  pinMode(red, OUTPUT);
  for (int i = 11; i <= 18; i++) {
    pinMode(i, OUTPUT);
  }
}

void loop() {
  b1 = digitalRead(2);
  if (b1 == HIGH) {
    dir = 2;
    func++;
    if (func >= 8)
      func = 0;
    } else {
      dir = 0;
    }
    digitalWrite(light, LOW);
    if (dir == 2 && light < 18) {
      light++;
    }
    digitalWrite(light, HIGH);
    delay(200);
  }

void function(int pin) {
  b2 = digitalRead(3);
  switch (func) {
    case 1:
      if (b2 = true) {
        digitalWrite(5, HIGH);
      } else {
        digitalWrite(5, LOW);
      }
  }
}

I have to be honest after reading you description and looking at you code I have no idea how you arrived at the code you have arrived at.

For now lets try a much simpler bit of code, once that is working you can build on it.

#define PIN_BUTTON_1    2
#define PIN_LED_RED     5

void setup() {
    pinMode(PIN_BUTTON_1, INPUT);
    pinMode(PIN_LED_RED, OUTPUT);
}

void loop() {
    const int buttonState1 = digitalRead(PIN_BUTTON_1);
    digitalWrite(PIN_LED_RED, buttonState1);
    delay(200);
}

If that code doesn't work then there is something wrong electrically.

I think is the next step you were trying for:

#define PIN_BUTTON_1    2
#define PIN_LED_RED     5

int lastButtonState1 = LOW;
int functionNumber = 0;
int currentLedValue = 0;

void setup() {
    pinMode(PIN_BUTTON_1, INPUT);
    pinMode(PIN_LED_RED, OUTPUT);

}

void loop() {
    const int currentButtonState1 = digitalRead(PIN_BUTTON_1);
    if (lastButtonState1 != currentButtonState1)
    {   // If the button's state has changed
        if (currentButtonState1 == HIGH)
        {
            ++functionNumber;
        }
        lastButtonState1 = currentButtonState1;
    }
    DoFunction(functionNumber);
    delay(200);
}

void DoFunction(const int& function)
{
    switch (function)
    {
    case 1:
        if (currentLedValue > 0)
        {
            currentLedValue = LOW;
        }
        else
        {
            currentLedValue = HIGH;
        }
        digitalWrite(PIN_LED_RED, currentLedValue);
        break;
    case 2:
        currentLedValue = 128;
        analogWrite(PIN_LED_RED, currentLedValue)
        break;
    default:
    }
}


What is the real lifetime of EEPROM? ATMEL says the cell lifetime of an EEPROM cell is about 100,000 write cycle/ cell.
Is this actually how the EEPROM performs in the wild?

If I do not change the value of a cell, does this stress the lifetime? For example, if I write the value 0xFF to the same cell again and again, is this any different to writing 0x00, 0xFF, 0x00 etc.

As you state, the internal EEPROM has a lifetime of 100,000 write cycles. This isn't a guess - a very significant proportion of ATmega328 will reach this number with no issues. I have tested three processors before, and all reached 150,000 cycles with no issues.

It is important to note the failure mode of EEPROM. Most "EEPROM destroyer" projects repeatedly read/write until the data is not written at all. Before this point, the EEPROM will still be damaged. This would be manifested by data not being retained for a reasonable period. It is unwise to rely on anything more than 100,000 write cycles for this reason.

EEPROM is different to the RAM on an ATmega. Writing to it is not simple or quick, but it is wrapped up in a friendly Arduino library, hiding this complexity from the user.

The first level of indirection is the EEPROM library, which is trivially simple], just calling two other functions for read and write. This calls eeprom_write_byte, found here.

This function uses inline assembly, so might not be easily understood. There is a comment that is easily understood though:

  Set programming mode: erase and write

This hints to one of the complexities of dealing with EEPROM - to write to
it, you first need to erase it. This means that if you call EEPROM.write(), it will perform a write cycle regardless of the value you are writing.

This means that repeatedly writing 0xFF will likely have the same effect as writing 0xFF,0x00,0xFF,0x00 etc.

There are ways to work around this - you can try calling EEPROM.read() before EEPROM.write() to see if the value is already the same, but this takes additional time.

There are other techniques to avoid excessive EEPROM wear, but their use depends on your application.


EMI resets atmega on switching ON relay with inductive load like a 230v fan I am making an automation device. I am using an atmega8a to control 6 relays. The setup is standard, 220v load, 5v dc coil, flyback diode and an NPN transistor to trigger with atmega pin. The problem is when I turn ON the relay, there is 10-20 MHz noise on the DC side and the atmega restarts. Switching OFF relays doesn't create a problem. i am guessing this is happening because of EMI. Is there a way i can protect my atmega from this and not have it restart everytime I start a relay.
The SMPS is 5v 2A
I have star tracks from SMPS
Is there a way to solve this?
Update: Had to switch from atmega chip to arduino nano. That seems to be working fine.

This can also be a power shortage as there will be a drop when the relays turn on, depending on you psu it might not respond quick enough, so you get a brown out. I added a bit 4700uF cap on the psu power line to the arduino.