text:
Arithmetic mean for sensor
This is the code I am currently using, but I want to add an arithmetic
mean to it. My goal is: when the pin A0 reads 5 values, I get the average
on which the fan and led will depend to be turned on and off, instead of
5 separate measurements.
int tempPin = A0;
int fan = 3;
int led = 8;
int temp;
int tempreal;
int tempMin = 20;
int tempMax = 30;

void setup()
{
  Serial.begin(9600);
  pinMode(fan, OUTPUT);
  pinMode(led, OUTPUT);
  pinMode(tempPin, INPUT);
}

void loop()
{
  temp = analogRead(tempPin);
  tempreal = temp * 0.48828125;
  delay(1);
  if(tempreal > tempMax)
  {
    digitalWrite(fan,HIGH);
    digitalWrite(led,LOW);
    delay(1);
  }
  else if (tempreal < tempMin)
  {
    digitalWrite(fan,LOW);
    digitalWrite(led,HIGH);
    delay(1);
  }
  else if (tempreal >  tempMin && tempreal <  tempMax)
  {
    digitalWrite(fan,LOW);
    digitalWrite(led,LOW);
    delay(1);
  }
}

Edit by Edgar Bonet – The OP added in a comment to my answer:
“I tried [averaging consecutive readings]. It worked as you would expect
but it still does not solves my problem. My sensor is only getting right
values in the beginning of the scanning and then it varies. That is why
I wanted to make average value but it still does not work. Sadly I think
I wont be able to change sensor, but is there any other way to
camouflage this problem?”
Below is a screenshot showing both correct (✓) and incorrect (✗)
readings:

A fixed sampling window can be hard to manage, especially if you want the calculation to be recursive, for space and speed considerations.
You can achieve similar results via exponential smoothing.
Yn = (1−α) Yn−1 + α Xn
Where Yn is the smoothed outcome, Xn is the current measurement, and α is the weight.
With some thoughts, it can be done with integers and without loss of precision.
edit: i ran a comparison of exponential smoothing vs. (fixed window) moving average. The moving average algorithm was written to be recursive for maximal speed.
the sampled data is a simulated sine wave:
1000 * sin(2pi*n/100) + 100 * noise. n = 0..19999, and noise = -0.5...+0.5.
So snr = 1000 / 50 = 20:1, or about 5 digits. far worse than what you would encounter in a 10-bit adc.

the window I picked is 4.
As you can see, both approaches closely resemble each other. exponential smoothing uses much less ram and is also much faster. older data has lower weight on the output, something generally desirable in most applications.

Memory is not a big issue if you are only averaging 5 values. And the OP's problem cannot be solved by averaging: see the updated question.

@dannyfI tried what you suggested but im getting real measurements too slow, it takes 10-15 sec to value stabilise. It looks more like this but it's too slow. link edit: maybe i shoud change alpha value?

See Arduino Tutorials Smoothing
https://www.arduino.cc/en/tutorial/smoothing
Create an array to hold a series of readings. And a variable to hold the sum.
Incrementally cycle through the array, subtracting the oldest value from the sum and replacing it in the array with the current reading. Divide by the number of readings for the average.
Remember to allow for a delay in each reading as is appropriate for the sensor.

No need here for a moving average: it's simpler to just take N readings and get their average, as in my answer. But note that the OP's problem cannot be solved by averaging: see the updated question.

You could use a moving average. It will update at each cycle whenever you take a new reading. Suppose you want to average over N readings:
double moving_average(double old_average, double new_value) {
    double new_average = old_average;
    new_average -= old_average/N;
    new_average += new_value/N;
    return new_average;
}

I edited the function above. I had typed one of arguments incorrectly.

it is not going to work.

Please elaborate why it will not work

I took the liberty to fix your code, as you forgot to declare new_average. The usual meaning of “moving average” is the one given in @DavidJ's answer. What you are proposing here is instead an exponentially weighted moving average. Essentially an implementation of @dannyf's answer. But note that the OP's problem cannot be solved by averaging: see the updated question.

"Please elaborate why it will not work" quite simple: both the old and new code suffer from one problem - you need to track the old_average exogenous, which is most of the challenges in such an implementation. you could have made that indigenous so your user only need to feed the code with the new_value and it will yield an average with one call.

Are you saying the code will not work because the call has to be made with two arguments?

My sensor is only getting right values in the beginning of the scanning and then it varies. That is why I wanted to make average value but it still does not work.

I had a similar problem. It turned out that I was reading writing and transmitting too fast. It means that since it seems that reading and writing can be interrupted during "their job", when you read a variable and in the same time someone is writing on that you're reading garbage. In my opinion this can be fixed by the application of "semaphores" or mutex or reducing the call of the reading. Randomly it would happen again but less frequently.
An idea can be found here
https://forum.arduino.cc/index.php?topic=132813.0
Best
Gian Maria

Seems too simple. am I missing something?
--- arithmetic-mean.ino.orig    2017-04-27 19:37:01.386458500 +0200
+++ arithmetic-mean.ino 2017-04-27 19:38:14.458114972 +0200
@@ -16,8 +16,11 @@

 void loop()
 {
-  temp = analogRead(tempPin);
-  tempreal=temp * 0.48828125;
+  temp = 0;
+  for (int i = 0; i < 5; i++) {
+    temp += analogRead(tempPin);
+  }
+  tempreal = temp * 0.48828125 / 5;
   delay(1);
   if(tempreal > tempMax)
   {

@najkulime: Then you should rewrite your question. You asked about arithmetic mean, but that's not what you want: you want to sort out the valid from the invalid readings, which is a very different question.

Maybe add a tiny delay after the analogRead. It would be helpful if you could print the values you get to the serial port, and show us that.


text:
Generate 1.7 Mhz with PWM in Uno?
I have this code:
void setup() {
  pinMode(11, OUTPUT);
  TCCR2B = 0;
  TCNT2 = 0;
  TCCR2A = _BV(WGM21);
  TCCR2A |= _BV(COM2A0);
  OCR2A = 249;
}

void loop() {
  soundBuzzer();
}

void soundBuzzer() {
  TCCR2B |= _BV(CS21);
}

void silenceBuzzer() {
  TCCR2B &= ~_BV(CS21);
  TCNT2 = 0;
}

(Got it from here).
And I have an ultrasonic water atomizer that works in a frequency of 1.7 Mhz.
Writing another number instead of 249 in the line "OCR2A = 249;", the frequency generated changes. With 249 it generates a frequency of 4 Khz. So, my question is: Which number do I have to write to get approximately 1.7 Mhz?

You can only divide the clock by an integer, so with a 16 MHz clock the closest you can achieve is 2 MHz.  The data sheet will show you how to find the divider ratio register setting (specifically, if the division will be one more than the loaded count, and if there is a prescaler upstream of what you get to divide).  If there is no perscaler it would seem like switching the board to a 12 MHz crystal and dividing by 7 might be a fit, but you'll need a custom bootloader.

More realistically, to operate this usefully you'll need the power and voltage amplifier from the intended driver circuit, so why not just take the entire original driver circuit, frequency generator and all, and figure out a way to enable/disable it from the Arduino?  Do take appropriate precautions for the voltages which it may generate!

You cannot generate 1.7 MHz on an Uno. The closest you can get is 16 MHz / 9 = 1.778 MHz.

You need to set the CS20 bit, not CS21. That way you have no prescaler. Then have it count to 9, like Edgar calculated. So set OCR2A to 8.

Wow, how did I miss 16/9?  That's not much worse than 12/7, for a lot less trouble.

Expanding from my comment... any signal level generated by this kind of
microcontroller can only last for an integer number of CPU cycles. In
order to generate it, you first have to compute the timing
characteristics of the desired signal in terms of CPU cycles:
period = 16 MHz ÷ 1.7 MHz = 9.412 cycles

The closest you can get is 9 cycles, which gives the frequency
frequency = 16 MHz ÷ 9 = 1.778 MHz

Assuming this is acceptably close to your target, you can configure a
timer to do it. The example code you provided uses Timer 2 with the
OC2A output set to toggle mode. This approach can only give periods
which are an even number of cycles, thus I am using the regular
“non-inverting fast PWM” mode instead in the solution below. In this
mode, the pin OC2A cannot be used with a controlled frequency, then I
changed it to OC2B (pin 3 on the Uno). Here is the code:
const uint8_t OUTPUT_PIN = 3;  // = OC2B
const uint8_t PERIOD = 9;      // 9 CPU cycles ~ 1.778 MHz

void setup()
{
    pinMode(OUTPUT_PIN, OUTPUT);
    TCCR2B = 0;           // stop timer
    TCNT2  = 0;           // reset timer
    TCCR2A = _BV(COM2B1)  // non-inverting PWM on OC2B
           | _BV(WGM20)   // fast PWM mode, TOP = OCR2A
           | _BV(WGM21);  // ...ditto
    TCCR2B = _BV(WGM22);  // ...ditto
    OCR2A = PERIOD - 1;
    OCR2B = PERIOD/2 - 1;
}

void soundBuzzer() {
    TCCR2B |= _BV(CS20);  // F_CPU / 1
}

void silenceBuzzer() {
    TCCR2B &= ~_BV(CS20);
    TCNT2 = 0;
}

The generated signal is slightly asymmetric: it stays HIGH during
4 cycles and LOW for 5 cycles. If you want a symmetric signal
(50% duty cycle), you can set PERIOD to 10 (5 cycles HIGH
and 5 cycles LOW), but then the frequency drops to 1.6 MHz.
Edit: You could also replace your Arduino Uno by a cheap ATtiny85
microcontroller, or maybe an Arduino-compatible dev board based on it,
like the Trinket or the Digispark.
This microcontroller has a built-in PLL which allows it to run one of
its timers at 64 MHz, even though the CPU is running much slower.
A 64 MHz timer allows you to hit the target 1.7 MHz frequency
to within 1%:
64 MHz ÷ 38 = 1.684 MHz

Ditto for SAMD21-based Arduinos; a built-in PLL lets you run a timer at 96MHz.

That’s a great answer, thank you, and I could follow the process in the ATmega328P datasheet. However, I don’t understand why it’s not possible to output the frequency on the OC2A pin. Indeed, there seems to be the same mode for OC2A in table 17-3: Clear OC2A on compare match, set OC2A at BOTTOM, (non-inverting mode). I tried and it doesn’t work, as you said, but I can’t find the part of the docs that say why.

@Olivier'Ölbaum'Scherler: In this mode (Waveform Generation Mode 7) the register OCR2A is used to set the pulse period (via the “TOP” value). You cannot use the same register to set the pulse length. If you set the pulse length with OCR2B, then the PWM signal can only be output on pin OC2B.

source: Stack Exchange

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

sort: votes


text:
Arduino RFID Mifare Classic dump info
I have my Arduino uno setup with RC522 reader. I am able to dump the data that is held on my test card supplied with the reader but I wish to read the data blocks held within another card I have. The reader shows this as a Mifare classic but Does not dump the blocks.
This is with miguelbalboa library
Card UID: EE 67 29 8D
Card SAK: 08
PICC type: MIFARE 1KB
Sector Block   0  1  2  3   4  5  6  7   8  9 10 11  12 13 14 15  AccessBits
  15     63  PCD_Authenticate() failed: Timeout in communication.
  14     59  PCD_Authenticate() failed: Timeout in communication.
  13     55  PCD_Authenticate() failed: Timeout in communication.
  12     51  PCD_Authenticate() failed: Timeout in communication.
  11     47  PCD_Authenticate() failed: Timeout in communication.
  10     43  PCD_Authenticate() failed: Timeout in communication.
   9     39  PCD_Authenticate() failed: Timeout in communication.
   8     35  PCD_Authenticate() failed: Timeout in communication.
   7     31  PCD_Authenticate() failed: Timeout in communication.
   6     27  PCD_Authenticate() failed: Timeout in communication.
   5     23  PCD_Authenticate() failed: Timeout in communication.
   4     19  PCD_Authenticate() failed: Timeout in communication.
   3     15  PCD_Authenticate() failed: Timeout in communication.
   2     11  PCD_Authenticate() failed: Timeout in communication.
   1      7  PCD_Authenticate() failed: Timeout in communication.
   0      3  PCD_Authenticate() failed: Timeout in communication.

I have also tried using these examples https://github.com/BoolLi/RC522_RFID_NFC_Utilities
But they fail to compile for me. All I want to do is dump the data blocks from a university card I have for a project, I don't need to be able to write to the card yet.

Failed authentication probably means you're using incorrect secret keys and there's a good chance that you've locked yourself out permanently. Your test card is a blank card from the manufacturer, with the default access conditions still in place. Where's the second card from?

second card is a uni card I have, it's only use is to allow entry to certain areas ie library and stuff, I have permission to be messing around with it for comp sci project. The card still works after trying this, how would I go about reading with secret keys and such? or even something I could read that covers this.

My bad. Since authentication failed and you never got to actually accessing the data, I doubt you hurt anything. There's an example in your library (rfid_default_keys) that brute-forces authentication with a bunch of known keys. If those dont work, trying out all 2^48 possibilities is not an option; would take millenia. You can try googling for MIFARE hacks.

The person who issues the card would know what the SO-PIN is.  When the factory ships the cards they have a Factory SO-PIN which will be published somewhere and then the Uni's card issuance system will(should) change the SO-PIN to something unique to the Uni so it can't be accessed by anyone without this PIN.  I recommend against trying to hack the card, because you only have a certain number of attempts (3 usually) before you irreparably damage the card (I have done many).

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


text:
LED strip and SD card
My problem is simple yet extremely problematic. For some reason, I cannot interact with an SD card and a LED strip at the same time with my arduino. After hours of testing multiple scripts, I am 99.99% that the issue is due to the SPI.h library.
I have tried the simplest LED strip code, such as turning on led number 5. If I include SPI.h, the code does not work, the data LED of the arduino doesn't even light up, the arduino doesn't send anything to the strip data line. If I remove include SPI.h, the code works.
This is really odd, I have read about the SPI.h messing with the pins, so now I'm looking for a solution, to use the SD card module without the SPI library if it is possible.
Here is an example of a code that does not work due to the use of the SPI.h library.
Any help is greatly appreciated, this is extremely odd and problematic.
#include <Time.h>
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
#include <avr/power.h>
#endif
#include <SPI.h>
#include <SD.h>

Sd2Card card;
SdVolume volume;
SdFile root;

const int chipSelect = 4;

#define PIN            6
#define NUMPIXELS      400

Adafruit_NeoPixel pixels = Adafruit_NeoPixel(NUMPIXELS, PIN, NEO_GRB +   NEO_KHZ800);

boolean stringComplete = false;  // whether the string is complete
boolean readarray=false;
String inString = "";
int c=0;
int cc=0;
int led=0;
int i=0;
int j=0;
int pixel_n=0;
unsigned long start;
unsigned long endd;

//char* ledd[]={"", "", ""};
int ledd[3]={0,0,0};

File myFile;

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

Serial.print("\nInitializing SD card...");

// Now we will try to open the 'volume'/'partition' - it should be FAT16 or FAT32
if (!volume.init(card)) {
  Serial.println("Could not find FAT16/FAT32 partition.\nMake sure you've formatted the card");
  return;
}

// print the type and size of the first FAT-type volume
uint32_t volumesize;
Serial.print("\nVolume type is FAT");
Serial.println(volume.fatType(), DEC);
Serial.println();

Serial.println("Ok we're done");
delay(2000);

pixels.setPixelColor(5, (200,200,200)); // THIS DOES NOT WORK
pixels.show(); // THIS EITHER

  Serial.begin(9600);
}

void loop(void) {

}

I had the same problem with using the SD reader with a SPI SRAM. It turns out that the very cheap SD reader cards do not like multiple SPI components on the same port. Since the Arduino has only one SPI, the only thing that worked was to use a SD data logger card.
To add a tristate solution by using two resistors on the MISO line also did not work in my case.
See my post for the post I created regarding this probably similar problem.

thanks a lot for your help. So the only solution is to use a SD logger card as you say. What difference is this going to make? I looked it up and it seems like it does require the SPI.h library as well.

Please add this as a comment to my answer (and upvote if it helps).
I know it uses also the SPI library. However, it contains some hardware/circuit that makes it possible to have a second (and possibly more) SPI device on the SPI bus simultaneously. If you know what to 'add' to the non working SD part, please let me know.

Hi sorry, I wanted to do add this as an answer, but I didn't have enough reputation. Does it require a lot of tweaking to create another bus on the SD shield or does it automatically allocate it?

I don't think you can add another SPI bus. The Arduino (at least the most) only have one (hardware) SPI bus. The SD data logger can be used together with other SPI components, but the cheap SD readers cannot.


text:
Interrupt handler in library
This is my first library so feel free to burn me and vote this down :D
This is a library that provides me with Watchdog deep sleep on my ATtiny85 projects.
In the test sketch I use the watchdog timer's interrupt vector but I want to place this within the library. How can I do this?
I have tried to add this to the init method but that did not work out;
powernap.h:26: error: expected unqualified-id before string constant
     ISR(WDT_vect) {
Also; feel free to shoot at the rest of the library, I am here to learn.
Test Sketch
#include "powernap.h"

#define LED 0

Napper napper = Napper();

volatile boolean f_wdt = 1;

ISR(WDT_vect) {
  f_wdt=1;
}

void setup() {
  delay(2000);
  napper.setup(8); // configure watchdog timer
}

void loop() { // blink
  pinMode(LED, OUTPUT);
  digitalWrite(LED, LOW);
  delay(200);
  digitalWrite(LED, HIGH);
  delay(200);
  digitalWrite(LED, LOW);
  delay(200);

  napper.sleep(); // deep sleep
}

powernap.cpp
#include "powernap.h"

 #ifndef cbi
   #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
 #endif
 #ifndef sbi
   #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
 #endif

Napper::Napper() {

}

void Napper::init(float initial) {
//  volatile boolean f_wdt = 1;

//  ISR(WDT_vect) {
//  f_wdt=1;
//  }
}

void Napper::setup(int cycle) {
    byte bb;
    int ww;
    if (cycle > 9 ) cycle=9;
    bb=cycle & 7;
    if (cycle > 7) bb|= (1<<5);
    bb|= (1<<WDCE);
    ww=bb;

    MCUSR &= ~(1<<WDRF);
    // start timed sequence
    WDTCR |= (1<<WDCE) | (1<<WDE);
    // set new watchdog timeout value
    WDTCR = bb;
    WDTCR |= _BV(WDIE);
}

void Napper::sleep() {
    cbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter OFF

    set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here
    sleep_enable();

    sleep_mode();                        // System sleeps here

    sleep_disable();                     // System continues execution here when watchdog timed out
    sbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter ON
}

powernap.h
#ifndef Fader_h
#define Fader_h

#if ARDUINO >= 100
  #include "Arduino.h"
#else
  #include "WProgram.h"
  #include "pins_arduino.h"
  #include "WConstants.h"
#endif

#include <avr/sleep.h>
#include <avr/wdt.h>
#include <util/delay.h>

class Napper {
    public:
        Napper();

        void init(float initial);
        void setup(int cycle);
        void sleep();

    private:
        int flag;

};

#endif

To answer your actual question, you just have to define ISR(WDT_vect)
outside any function.
Now, for the general critique, let me start by quoting Antoine de Saint
Exupéry: “It seems that perfection is attained not when there
is nothing more to add, but when there is nothing more to remove.”
There are quite a few things to remove from your code, like unused
variables, parameters or methods. I understand that you may be tempted
to leave useless stuff in there anticipating that you may need it in a
future, extended version. But please, don't do that. Try to keep clean
and lean any code that you post in public, and only add extra stuff when
you actually need it.
I would remove most of the #includes from powernap.h. If the compiler
needs one of these to understand your .h, then live it there. If it's
only needed to compile your library, then it belongs to your .cpp.
Also, there is no point in making your library dependent on the Arduino
core, as you are using no core functionality. By removing this
dependency, you can make your library more versatile, as it can be used
both for Arduino and non-Arduino projects.
The line #ifndef Fader_h looks weird. Standard practice is to use the
name of the .h file, capitalized. Don't depart from common practice
unless you have some reason to do so.
I would also add static to your methods, this way they can be used
without having to instantiate an object, like in
Napper::setup(WDTO_4S);.
You are using three different syntaxes for setting and clearing bits in
I/O registers. Your code will look more consistent if you choose one and
stick with it.
I almost forgot... you have to make sure the timed sequence is done
atomically, i.e. it's not interrupted.
Below is a version of the library that implements the suggestions above:
powernap.h
#ifndef POWERNAP_H
#define POWERNAP_H

#include <stdint.h>

class Napper {
    public:
        Napper() {}
        static void setup(uint8_t cycle);
        static void sleep();
};

#endif  // defined(POWERNAP_H)

powernap.cpp
#include <avr/interrupt.h>
#include <avr/sleep.h>
#include <util/atomic.h>
#include "powernap.h"

// This interrupt is used only as a wakeup source.
EMPTY_INTERRUPT(WDT_vect);

// Configure the watchdog as an interrupt source.
// `cycle' should be an integer from 0 to 9, or one of the constants
// WDTO_XXS from <avr/wdt.h>.
void Napper::setup(uint8_t cycle) {
    uint8_t prescaler;         // prescaler bits in WDTCR
    if (cycle > 9) cycle = 9;  // largest supported value
    prescaler = cycle & 7;     // bits WDP2:WDP0 are right aligned in WDTCR
    if (cycle > 7) prescaler |= _BV(WDP3);

    MCUSR &= ~_BV(WDRF);  // clear this bit: it overrides WDE
    ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
        WDTCR |= _BV(WDCE)    // start timed sequence
              |  _BV(WDE);
        WDTCR =  prescaler    // set new watchdog timeout value
              |  _BV(WDIE);   // enable watchdog interrupt
    }
}

void Napper::sleep() {
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);
    sleep_mode();
}

Awesome, I will improve my library, thank you for being thorough.

It is hard to help you improve your library or code if you don't tell others what your code pieces are trying to do.
In general, you will have a piece of code that sets up the whole thing, a piece of code that will be executed in the isr, and other helper code pieces, like getting status and clear status, as appropriate.
I often use a function pointer that the user can hook to the user handler so my isr portion of the code is fixed. Just hook to different functions in the user space and you are ready to go.
Obviously other ways exist, each with their pros and cons.

Your general directions are all in the code. I do not know what a user hooking function pointers to handlers is..


text:
MPU6050 doesn't work
I am trying to do a self-balancing bot as a school project, but I got stuck with the MPU6050.
I tried using the code by Jeff Rowberg (MPU_6050_raw) but it's reading only zeros.
I tried the MPU_6050_DMP and got stuck at "initializing DMP..." and no reading is shown.
I tried other code, but same thing happens, either reading zeros or getting stuck at "initializing DMP..".
And how can I make sure that the chip isn't broken?

The MPU-6050 is a 3.3V chip. When you are using a 5V Arduino board, you should take care that you don't put current into the SDA and SCL pins of the MPU-6050.
Start with a i2c scanner.
This one: Arduino Playground I2C scanner
Or this one: Nick Gammon I2C scanner
If the I2C scanner halts, then there is a hardware problem with the I2C bus. It might be a shortcut of SDA or SCL to GND, or the MPU-6050 module is not powered.
If the I2C scanner is working, then you know the address (0x68 or 0x69). With that address you can try the Short example sketch to read data from the chip.
If that is working, then you can try the Jeff Rowberg library.

Thanks for replying.
the i2c scanner worked well here is what i got.
    I2C scanner. Scanning ...
    Found address: 104 (0x68)
    Done.
    Found 1 device(s).

but i still get zeros when i try the short examples.
    AcX = 0 | AcY = 0 | AcZ = 0 | Tmp = 36.53 | GyX = 0 | GyY = 0 | GyZ = 0
    AcX = 0 | AcY = 0 | AcZ = 0 | Tmp = 36.53 | GyX = 0 | GyY = 0 | GyZ = 0
    AcX = 0 | AcY = 0 | AcZ = 0 | Tmp = 36.53 | GyX = 0 | GyY = 0 | GyZ = 0

sorry i forgot to mention tham iam using arduino uno board

The temperature is not zero. It seems as if the accelerometer and gyro are not turned on. There are a number of possibilities: a broken sensor, or a bad I2C bus, or wrong voltages, or it is not the MPU-6050. Could you try the long example sketch http://playground.arduino.cc/Main/MPU-6050#sketch , that sketch checks for bus errors. Could you check with a magnifier if it is really a MPU-6050 ? It is a 3.3V sensor and the Arduino Uno is a 5V board. The MPU-6050 might be broken because of the wrong voltages. My suggestion is to buy a new MPU-6050 (or the newer MPU-9250) and a I2C level shifter.

thank you for being patient with me. here is what i got form the code   MPU-6ًInvenSense MPU-6050
June 2012
WHO_AM_I : 68, error = 0
PWR_MGMT_1 : 0, error = 0
MPU-6050
Read accel, temp and gyro, error = 0
accel x,y,z: 0, 0, 0
temperature: 36.506 degrees Celsius
gyro x,y,z : 0, 0, 0,
i use the 3.3 volt pin in the arduino i dont know what you mean that the uno is 5v board. and i consider buying the mpu 9250 .and iam sorry to ask another question. if you know how to test it at the shop and what to do to prevent it from getting burned like the last one. thanks again for your patience

error = 0 means there is no error, but the accelerator and gyro values are still zero. That is weird, and I have not heard of it before. Let's assume it is broken. The Arduino Uno has a ATmega328P microcontroller running at 5V. The MPU-6050 should have 3.3V to power it and also 3.3V signals at the I2C bus (SDA and SCL). You don't have to test it at the shop, it should be fine. It is safer and better to use a I2C level shifter to connect the Arduino Uno to a 3.3V sensor, or else use 4k7 pullup resistors to 3.3V: http://playground.arduino.cc/Main/I2CBi-directionalLevelShifter


text:
Broken Loop and dim LEDs
I want to make 2 LEDs blink back and forth continuously, but they only do so once, and the second one is very dim.
code:
int ledone = 12;
int ledtwo = 10;
int keepgoing = 1;

void setup() {
pinMode(ledone, OUTPUT);
pinMode(ledtwo, OUTPUT);
}

void loop() {
 while (keepgoing == 1) {
  digitalWrite(ledone, HIGH);
  delay(80);
  digitalWrite(ledone, LOW);
  digitalWrite(ledtwo, HIGH);
  delay(80);
  digitalWrite(ledtwo, LOW);
  delay(500);
 }
}

I am using an Arduino Uno and one 220 ohm resistor for each LED.

i have corrected keepgoing == 1, instead of keepgoing = 1, please check now.

By "second one", do you mean one of the LEDs?  If so swap the leads to them and then report back if the same kind of dimness still occurs – maybe one of your LEDs is just dimmer than the other.  If the dimness swaps, then try changing ledtwo = 10 to  ledtwo = 9, ie to some other pin, and rewire accordingly – maybe one of your IO pins has a problem or your wires are loose.  Also try changing those fairly-short 80-ms delays to perhaps twice or three times as long.

@goddland_16, as a condition for an if, keepgoing = 1 will always evaluate as true,which will keep the while statement going.   keepgoing == 1 also will evaluate as true, given that  keepgoing  was initialized to 1.

swapping fixed my brightness, but how do I make my loop keep repeating, it only executes once :(

@JamesWaldby-jwpat7, yes, it is. For this context I assumed he meant it as keepgoing == 1.

it now looks like this:  void loop() {
while (keepgoing == 1) {
digitalWrite(ledone, HIGH);
delay(160);

it still does not run more than once.

NerdyDude101, is the following a correct description of what you see?  When you press reset, LED 1 comes on briefly and goes off.  LED 2 comes on briefly and not as bright and goes off.  Then both LEDs stay off until you press reset again.

yes that is what I see.

Ok, what happens if you delete while (keepgoing == 1) { and the matching closing } ?

it stays the same.

May be some hardware or wiring problem... I would next try things like the following:  (a) with both LEDs wired up, comment out the digitalWrite()'s for one LED at a time, and see if loop() works; (b) pull the wire to one LED at a time, and see if loop() works (ie take one LED out of circuit, run test, put the LED back in, take the other out, run test); (c) try higher-resistance resistors, in case something is wrong with the ones you have.   BTW, does the Blink example sketch, which uses built-in LED, work ok?  And did the 160-ms delays look twice as long as the 80's?

You don't need the while loop. loop() loops forever anyway.

Ok. This is really weird. My code looks like this:

void loop() {
while (keepgoing == 1) {
digitalWrite(ledone, HIGH);
//digitalWrite(ledtwo, LOW);
delay(500);
digitalWrite(ledone, LOW);
//digitalWrite(ledtwo, HIGH);
delay(500);

(of course it has proper spacing)

but both LEDs blinked on and then off once?!

I think the problem is, that your delays are just too short, so you see the blinking not as blinking, but as a dim lit led.
Maybe you can try the following code:
void loop() {
 while (keepgoing == 1) {
  digitalWrite(ledone, HIGH);
  digitalWrite(ledtwo, LOW);
  delay(500);
  digitalWrite(ledone, LOW);
  digitalWrite(ledtwo, HIGH);
  delay(500);
 }
}

Is this working?

I tried this code and each LED only blinked once. This is really confusing!


text:
NodeMCU power consumption measurement and DeepSleep
I'm working on a project using a nodeMCU using a ICR14500(3.7V and 700mAh) battery and I'm experienced some issues when I try to estimate the total current consumption. Firstly I experienced some problems with the power supply (here is the previous question NodeMCU powered with battery and use WiFi) but this problem is now solved.
At this moment if I measure the current consumption connecting the amperimeter in serie between the battery and the nodeMCU input voltage pin I see a current consumption of 140mA continiously (ignoring the deep sleep mode) and I experienced some strange behaviours in my NodeMCU, even the code doesn't work. If I remove the amperimeter from my set up all works smooth and my source code works perfectly.
In order to validate my amperimeter I modified a usb cable and I added the amperimeter in the middle of the wire and I measured the current consumption powering me nodeMCU from the computer and I saw a current consumption of 80mA when the code is run and 14mA when the device is in deep sleep. This behaviour seems the expected one.
Are there any colateral effect measuring the battery current consumption which I haven't considered?

Make sure the battery is fully charged. That might be enough, so the burden-voltage described by Majenko isn't a problem.

An ammeter is basically a small resistor in series over which the voltage drop is measured. That resistance will play a part in the effective output impedance of your power source (battery).
This increased impedance will reduce the overall amount of current the battery can provide before the voltage drops to an unacceptable level.
For instance, I just did a crude measurement of the resistor used for the 200mA range of one of my DMMs and came up with a value of 1.2Ω. At 140mA that would give a voltage drop of (V=IR = 0.14 × 1.2) 0.168V. That's 0.168V that your NodeMCU won't be seeing. Add to that the fact that the WiFi will be creating peaks of current usage up to, say, 500mA (probably less, that's just a wild guestimate), the voltage drop will increase to (0.5 × 1.2) 0.6V. From a battery giving 3.7V nominal that would plummet to 3.1V as seen by the NodeMCU.
Depending on what kind of power regulation you are using that will most likely cause brown-outs of the power and the MCU will reset or crash.
When powered by 5V that 0.6V drop would not be as noticeable, since 4.1V is still well above what is needed to power the chip and the voltage regulation can still work properly.
So how can you measure the current with the battery? Well, there's two options:

Use a much smaller resistance (0.1Ω, for example) and measure the voltage across it - then use Ohm's Law to calculate the current.
Add a large electrolytic capacitor to the input of the NodeMCU after your current measurement to act as an energy source for sustaining the peaks of current required by the WiFi. By big I mean something like 3300µF:

simulate this circuit – Schematic created using CircuitLab

A very good explanation, I hadn't experienced issues due to the ammeter internal impedance. The idea of the filter using the capacitor is very good.  Thanks!!

The NodeMCU has an on-board voltage regulator, that needs excess voltage to supply the 3.3V. So if the voltage for the regulator is too low, the voltage for the ESP8266 may become too low too or it can’t draw enough current as it needs.  (During boot or wifi operation it’s drawing up to 200mA peak current). If that happens, it’ll be stuck in the boot process, in which it’s drawing the 140mA.
So, when you’re running from battery, be sure to power the 3.3V supply of the board, not the 5V input that goes through the regulator first.
When your battery is fully charged it’ll give 4.2V, which may just be enough for the regulator still. With the ampmeter in between it’ll definitely be too low.
Note that with the NodeMCU board you’ll never get the advertised 20μA deep sleep current of the ESP due to the onboard voltage regulator (unless you modify the board).


text:
Different questions regarding Arduino C++ library coding style
I'm reading the two wire library in Arduino libraries and in the C++ source  code I found different methods which I don't know what they mean, in the following:
// Initialize Class Variables //////////////////////////////////////////////////

uint8_t TwoWire::rxBuffer[BUFFER_LENGTH];
uint8_t TwoWire::rxBufferIndex = 0;
uint8_t TwoWire::rxBufferLength = 0;

uint8_t TwoWire::txAddress = 0;
uint8_t TwoWire::txBuffer[BUFFER_LENGTH];
uint8_t TwoWire::txBufferIndex = 0;
uint8_t TwoWire::txBufferLength = 0;

uint8_t TwoWire::transmitting = 0;
void (*TwoWire::user_onRequest)(void);
void (*TwoWire::user_onReceive)(int);

// Public Methods //////////////////////////////////////////////////////////////
void TwoWire::begin(void)
{
  rxBufferIndex = 0;
  rxBufferLength = 0;

  txBufferIndex = 0;
  txBufferLength = 0;

  twi_init();
}

void TwoWire::begin(uint8_t address)
{
  twi_setAddress(address);
  twi_attachSlaveTxEvent(onRequestService);
  twi_attachSlaveRxEvent(onReceiveService);
  begin();
}

void TwoWire::begin(int address)
{
  begin((uint8_t)address);
}

My first question, regarding to class variables:

Why has the author connected the variables to the class with scope-resolution operator "::"?
I want to understand the last two lines of class variables, I know they are function pointers, but I want to know more details and benefits of function pointers?

My second question, regarding to public methods:

There are three versions of the "begin" function, can someone explain why?
Why is begin(); called inside the second function declaration?

Why they connect the variables to the class with scope-resolution operator "::"?

Those are static variables. They don't exist within an instantiated class instance since they are common to all class instances - so they have to be defined elsewhere, and for that you need the full "class path" for them to associate them with the class itself.

I want to understand the last two lines of class variables, I know they are function pointers, but I want to know more details and benefits of function pointers?

Yes, they are function pointers. They are used to store the address of functions the user supplies at runtime. Without them it is very hard for the user to tell the class which of his own functions should be called for various events.

There are three versions of the "begin" function, can someone explain why?

This is called function overloading. It allows you to have the same function but provide different combinations of parameters. In this case one with no functions (in master mode) and two with different numeric parameters (for slave mode) with those numeric parameters in different storage formats.

Why begin(); is called inside the second function declaration?

It saves having to duplicate all the code from the other begin() function within that function. You call the function with a numeric parameter, it does a little bit of "extra" work, then it calls the "common" begin code from the other begin() function. Code duplication is generally a bad thing since any changes you make have to be made in multiple places. This keeps the common code in one location, and the most convenient place for that is the begin() function that takes no parameters.

Guys, first of all thank you very much for Mr Code Gorilla for correcting my English it's really a honor for me that a friend in the technical field is interested to help me with my English skills :), and secondly, thanks to Mr Majenko for answering my questions. I'm really thrilled that one help me with my English and the other one helped me with my technical topic. I understood some answers and others not so quite, so I need more time to understand and comment again for the answers.

There are some complex things there you are looking at. May help: http://www.learncpp.com/cpp-tutorial/811-static-member-variables/ - https://www.tutorialspoint.com/cplusplus/cpp_overloading.htm

For the fisrt answer, I understood half of your answer as static variables are shared and that's it but I didn't understand the second half, "so they have to be defined elsewhere, and for that you need the full "class path" for them to associate them with the class itself." Do you mean by full path is to define their type and connect them with the class name? I think yes, and also I understood in the library that the author is defining them at the beginning and before class definition with the class name. OK this point is now obvious to me :)

@PerchEagle With a static variable the type is defined in the class, but the storage space for that variable has to be manually defined, and that is what those entries are. A normal variable has the storage space allocated in a class instance when it is created (e.g., Servo myServo; allocates the space for the variables within the Servo class). Static variables can't do that since the storage space isn't specific to any one object, but to all objects - so you have to manually create that storage space. And you do that by defining the variables in a source file. The variable's name is ...

... <ClassName>::<VariableName>. You need the <ClassName>:: bit so that the compiler knows you mean the variable in that class, not some other unrelated variable.

The second answer is not obvious because I didn't implement it practically in my AVR C coding yet so I don't know the benefits of function pointers. 3. The third answer is obvious which is function overloading and now I see an example for function overloading but I don't know why the author implemented this function overloading. 4. The fourth answer is not clear.

Re 2: It is not a question of "benefit" - it's a question of how do you implement storing a function passed to you as a parameter, and function pointers are the answer. Re 3: Because he wanted to. It's a clean way of doing it, and you only have to remember "begin", not "beginMaster" and "beginSlaveInt" and "beginSlaveUint8" functions. Re 4: Which would you prefer: to write the same code 3 times or write it once and just call the function with it in?

OK, I understood your reply and the Servo example, but why would I need static variables anyway if its storage is shared with all instances?

Because static storage happens to be the correct solution to a specific problem.

Thank you very much for helping me Re 2, 3, 4 are OK to me because I have to implement these techniques to see the results for C++ applications.

Absolutely thank you for your answers I'm really thankful for your cooperation I've been away of coding because I was busy with my marriage and honeymoon it's been 1 month for my marriage :) I just started off reviewing coding these days :)

I got another question today :) Why the author put two functions to se the frequency or the clock? Regards, void TwoWire::setClock(uint32_t clock)
{
twi_setFrequency(clock);
}

@PerchEagle The bulk of the Wire library code is actually a third party (probably written by Atmel) C library of routines. The TwoWire class is merely a C++ wrapper to those C functions to give an easy user interface. TwoWire::setClock merely calls the relevant function in that library (which is all in the utility directory) to do the actual setting of the clock.

Oh yeah, so clear thank you very much, I'm really happy with your answers :) Please see my new post at avrfreaks, but didn't find a quite clear answer. http://www.avrfreaks.net/forum/twen-twint, or I should post it in this website in a new topic? Regards,


text:
Powering SD breakout board with 3.7V battery
So in a previous post I asked if I could charge an SD card breakout board with a 3.7V LiPo battery, and I got a positive response, so I did it.
The problem is that it seems not to be enough, since, with the exact same wiring, if I supply it with my Arduino Uno, it works perfectly, but when I change the supply to the battery it gives an error. The following text is the result of an Arduino example script:
When connected with the Arduino:
Initializing SD card...Wiring is correct and a card is present.

Card type: SDHC

Volume type is FAT32

Volume size (bytes): 2696937472
Volume size (Kbytes): 2633728
Volume size (Mbytes): 2572

Files found on the card (name, date and size in bytes):
SYSTEM~1/     2017-04-27 15:20:04
  WPSETT~1.DAT  2017-04-27 15:20:04 12
  INDEXE~1      2017-04-27 15:20:14 76
TEST0.TXT     2000-01-01 01:00:00 49050
TEST1.TXT     2000-01-01 01:00:00 60231
TEST2.TXT     2000-01-01 01:00:00 1044
TEST3.TXT     2000-01-01 01:00:00 34831
TEST4.TXT     2000-01-01 01:00:00 189736
TEST5.TXT     2000-01-01 01:00:00 12419

When connected to the battery:
Initializing SD card...initialization failed. Things to check:
* is a card inserted?
* is your wiring correct?
* did you change the chipSelect pin to match your shield or module?

or
Initializing SD card...Wiring is correct and a card is present.

Card type: SD1
Could not find FAT16/FAT32 partition.
Make sure you've formatted the card

I've tried to supply the breakout board both through the 3V and 5V input. Can anyone notice what am I doing wrong?

Did you connect the ground of the SD card board to the ground of the Arduino?

no, i was connectiong to the ground of the battery, should it be the arduino's one?

Yes, all connected devices must share the same ground, otherwise they can't talk to each other.

Makes sense, so i don't connect the battery ground to anything?

Yes, you connect the battery ground to ground. There is only one ground. All "ground" points must be connected together.

Ahh, so in my breadboard i will put the arduino's ground and  the battery ground in series and from there i pull a cable to the breadboard's ground, correct?

It doesn't (much) matter how you connect all the grounds together, as long as they are all connected.

ahh great that was it, thank you, and sorry for the lack of knowledge in electronics.

Don't be sorry. You learned something today.

You haven't connected the grounds together in your circuit. You need to connect all the grounds together so every connection has a return path back to where it came from.  That means connect together:

An Ardino GND pin
The GND pin of the SD card breakout board
The negative (or ground) pin of the battery


text:
ESP8266 sometimes stuck on AT+CIPSEND with "busy s..."
I'm using an ESP8266-01S Wi-Fi module on an Arduino UNO.
When I use AT+CIPSEND=4 and then type test it successfully sends that message to my laptop. However, sometimes the module returns a busy s... after typing the message... Then the module board is "frozen" for a couple of seconds to a full minute before accepting other commands.
What's a way to make sure the message gets send without getting that busy s... response. Or how do I catch it and reset the board or something like that?


text:
How to use ESP8266 for wireless communication?
I saw many tutorial explaining how to program ESP8266 but Specifically I didn't get any tutorials explaining how to use with Arduino or any other Microcontroller for Wireless Communication. I had a doubt how could I use it with Arduino for Serial Communication such that I could use with my handset ( using Blynk ) and with my PC.

http://www.blynk.cc/getting-started/

I'm not very clear on what you are asking but I think you are saying how do you connect an ESP8266 to an Arduino so the Arduino has wireless(WIFI) access.
I'm sure there are tutorials out there so I won't go in to detail (also I don't know the details), but hopefully you will get some better terms to search with.
The basic idea is you connect the serial connection of the ESP8266 to the serial of the Arduino (via a level shifter and connect Tx to Rx).  You then write a series of AT commands to configure the ESP8266 so that what ever is receives over the serial it sends to a TCP endpoint via WIFI (and what it receives is sent to serial).
You can program the ESP via the Arduino IDE, so you could write a 'smarter' version that did all the setup for you, etc.  In fact since the ESP8266 is a faster processor with more RAM you could do a lot more on it.
If you are using an UNO or Nano you might want to look at the software serial library to let you keep the main serial port for debug messages.  If you are using a Mega then you can use one of the secondary serial ports.

But how could I use it with Blynk ???????

All described in tutorial I linked. Please read it, ask then more if not clear.

You follow the instructions from blynk.cc/getting-started which include quite simple steps:

1 create auth id
2 download and install blynk library
3 replace auth id in some example you can find from arduino ide
4 run code

More details from tutorial.


text:
Serial communication with more than two Arduinos
Is my syntax "SoftwareSerial uno1(0,1); // RX, TX" is right to communicate with more than two Arduinos?. How can I communicate with three Unos via single Mega?
#include <SoftwareSerial.h>
SoftwareSerial uno1(0,1); // RX, TX
SoftwareSerial uno2(0,1); // RX, TX
SoftwareSerial uno3(0,1); // RX, TX

float lt[24]={3530,1580,3880,2780,4040,11260,7935,6655,2100,5100,1450,2200,2200,5900,6180,4230,2405,3560,4535,12635,12085,3500,930,3430};
float gt[24]={0,0,0,0,0,0,6320,5496.9,5948,4124.1,3848.4,3573,3022.2,3297.6,3298.2,3573,4123.2,0,0,0,0,0,0};
float lbt[24]={3530,1580,3880,2780,4040,7960,7935,2655,900,1400,1450,1300,1000,3400,3680,1730,2405,3560,4535,9635,9885,3500,930,3430};
float lb1[24]={1580,480,1580,1580,580,1950,3125,1625,250,500,250,600,500,1450,1480,630,530,1655,1475,3225,3300,1450,280,1730};
float lb2[24]={1450,600,1700,600,3080,3005,1655,500,250,500,600,350,250,1700,1700,600,1625,250,1405,3255,4455,1800,500,1450};
float lb3[24]={500,500,600,600,380.3005,3155,530,400,400,600,350,250,250,500,500,250,1655,1655,3155,2130,250,150,250};
float lst[24]={0,0,0,0,0,3300,0,4000,1200,3700,0,900,1200,2500,2500,2500,0,0,0,3000,2200,0,0,0};
float les1[24]={0,0,0,0,0,0,0,2000,1200,0,0,0,0,2500,2500,2500,0,0,0,0,1200,0,0,0};
float les2[24]={0,0,0,0,0,3300,0,0,0,0,0,900,1200,0,0,0,0,0,0,2000,0,0,0,0};
float les3[24]={0,0,0,0,0,0,0,2000,0,3700,0,0,0,0,0,0,0,0,0,1000,1000,0,0,0};
float BatCap[24]={405.83,405.83,405.83,305.83,305.83,305.83,305.83,305.83,588.91,576.24,799.08,936.45,1050.87,811.05,570.85,493.19,590.53,637.47,397.47,397.47,397.47,397.47,397.47,397.47};

float Pvpin=41,Batpin=42,Gridpin=43;

void setup() {
// DEFINING THE MODES OF LOADS, OBEVIOUSLY OUTPUT.
  pinMode(Pvpin,OUTPUT);
  pinMode(Batpin,OUTPUT);
  pinMode(Gridpin,OUTPUT);

  Serial.begin(9600);
  uno1.begin(9600);
  uno2.begin(9600);
  uno3.begin(9600);
  while (!Serial) {
     // wait for serial port to connect. Needed for native USB
  }
}

void loop()
{
  for (int i=0;i<24;i++)
  {
   if (gt[i]>lt[i])
   {
       uno1.write( "100");
       uno2.write( "100");
       uno3.write( "100");
       digitalWrite(Pvpin,HIGH);
   }
   else if (gt[i]+BatCap[i]>lt[i])
   {
       uno1.write( "110");
       uno2.write( "110");
       uno3.write( "110");
       digitalWrite(Batpin,HIGH);
       digitalWrite(Pvpin,HIGH);
   }
   else
   {
       uno1.write( "001");
       uno2.write( "001");
       uno3.write( "001");
       digitalWrite(Gridpin,HIGH);
   }
  }
}

Why use SoftwareSerial when you have 4 UARTs on the Mega?

@EdgarBonet how can i access 4UARTs in Mega? i need syntax for the case of three UARTs.

@EdgarBonet please amend my code for serial communication with more than two Unos via single Mega. tha above code is for Mega.

Serial1.begin(9600); Serial2.begin(9600); ...

@gre_gor yes it is.

If you want to use 3 SoftwareSerial instances, then you need to use 3 different sets of pins. Hence, replace:
SoftwareSerial uno1(0,1); // RX, TX
SoftwareSerial uno2(0,1); // RX, TX
SoftwareSerial uno3(0,1); // RX, TX

with something like:
SoftwareSerial uno1(0,1); // RX, TX
SoftwareSerial uno2(2,3); // RX, TX
SoftwareSerial uno3(4,5); // RX, TX

Also, since SoftwareSerial and Serial (hardware) are interchangeable in code, you should take advantage of the hardware Serial of Arduino UNO:
HardwareSerial uno1 = Serial;

Note that, on UNO, HardwareSerial uses pins 0 and 1, hence you should not use these for something else:
HardwareSerial uno1 = Serial;
SoftwareSerial uno2(2,3); // RX, TX
SoftwareSerial uno3(4,5); // RX, TX


text:
Servo jitter with Arduino
We're complete beginners with Arduino and we're working on a project that moves a pointer based on a color sensor reading.
We used two servo motors each: one performs a specific task, the small servo works pretty fine. The problem is with the larger one.
We used this servo motor model: (towardpro MG996R), Arduino Uno and a color sensor. Because the motor is large we connect it to a 9 V power supply.
But when we run the code it just vibrates in place and the arm won't move :(
Is there anything else we need to add to the circuit like a resistor or some thing?
#include <Servo.h>
Servo largeServo;

void setup() {
  largeServo.attach(6);
  largeServo.write(0);
}

void loop() {
  largeServo.write(0);
  delay (2000);
  largeServo.write(30);
  delay (2000);
  largeServo.write(60);
  delay (2000);
  largeServo.write(90);
  delay (2000);
}

Does the small servo perform well with the very same code on the same pin? If so, chances are there is something wrong with the large servo, or with its power supply.

yes, the code is perfectly fine with the smaller one ,

but if the problem with the battery how would i know ?

"9V power supply" as in 9V PP3 battery...?

YES! exactly , directly connected to the servo and the Arduino GND

Well there you go then. Use a supply that can deliver enough current and you may find it magically starts working...

do you mean we must increase the voltage , because the motor sheet specify 4.4-6 v ?

Welcome to Arduino SE.  Be sure to take the tour to see how this works and to earn a badge:  https://arduino.stackexchange.com/Tour

No, not more voltage.  You need something capable of delivering more current.  A 9V battery is not suitable for driving motors.  They belong in smoke detectors and maybe a transistor radio.  Get 3 or 4 AA or AAA batteries and things will go much better.

Howmany current does the servo draw/need? Stay within the datasheets' voltages and make sure your supply can deliver the required current!

According to (MG996R)'s datasheet
You must connect a 6 volts - 2.5 amps power supply for it's best performance (max. Torque)
Maximum voltage of this servomotor is 6 volts
And be careful, exceeding that voltage can be cause of some damage to it's control board
Try 6 volts 2.5 amps power supply and if doesn't work maybe your servomotor's control-board is damaged by over-voltage.

As already suggested in the comments you need a more powerful current source than your battery.
No device work purely on Voltage, they all operate on Power (watts) or, if you prefer, on a combination of Voltage and Current (ampere).
You are feeding 9V into your beefy motor, but the amount of current your battery can provide is pretty limited due to the battery internal resistance and limited capacity.
Replace the battery with a proper power source capable to deliver 10W or more (1+ ampere at 9 volts equals 9+ watts) and your motor will start to operate and it will also get warm while operating.

Please mind that theoretically putting a higher voltage will give more power. But that soms component can not resist higher voltages. The way to go is to take a supply with a voltage within the voltage range of the device. And to make sure it can supply more current as neccesary. (Not the other way around)

When applied to motors the voltage reflects on speed and current on torque, but if the motor jitters it's because it doesn't get enough current to overcome the windings inductance. So, while it's true higher voltage means more power, that's not going to solve the issue in this case.

Hmm interesting 10v 1a or 20v 0,5a is the same "power". But the first example has more torque and the second one more speed? My conclusion is still true, don't overvolt and be able to supply enough current.

That's correct Paul: higher voltage means you can change the magnetic field in the coils more quickly while higher amperage means you can create stronger magnetic fields. You don't have to exceed in voltage because the the internal windings have a resistance: provide too much voltage and you burn the windings.

To complement the other answers, also make sure that the Arduino itself is being powered properly!
I was attaching Arduino Uno to a nearly out of battery laptop via USB cable, resulting in a jittering servo. As soon as I've put the laptop on charge, the servo started working smoothly!

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


text:
Programming ATUC256L4U using only Arduino ISP
I heard that you can program any AVR Microcontroller by just using Arduino ISP Can I program ATUC256L4U by just hooking it up to Arduino ISP and Caps, Crystals and etc. Or do I need to do some more work like you know the fuses and all ?

You can set the fuses through your ISP programmer.

Only the fuses or anything more.


text:
Running two stepper motors with two rotary encoders
I'm really bad with this coding part of using two rotary encoders to control two stepper motors [using 28BYJ-48 stepper motor with the ULN2003 board].
This code works fine using one rotary encoder for one stepper motor using this off brainy-bits.com:

https://brainy-bits.com/blogs/tutorials/stepper-motor-rotary-encoder-p1
When I slightly modify the code for two encoders and two stepper motors I'm using this: However I'm not getting the results I expected. The two motors just don't respond.
#include "Stepper.h"
#define STEPS 32   // Number of steps for one revolution of Internal shaft
// 2048 steps for one revolution of External shaft

volatile boolean TurnDetected;  // need volatile for Interrupts
volatile boolean rotationdirection;  // CW or CCW rotation

const int PinCLK = 2; // Generating interrupts using CLK signal
const int PinDT = 3;  // Reading DT signal
const int PinSW = 4;  // Reading Push Button switch
const int PinCLK2 = 46;
const int PinDT2 = 47;
const int PinSW2 = 48;

int RotaryPosition = 0;  // To store Stepper Motor Position
int RotaryPosition2 = 0;

int PrevPosition;     // Previous Rotary position Value to check accuracy
int PrevPosition2;
int StepsToTake;      // How much to move Stepper
int StepsToTake2;

// Setup of proper sequencing for Motor Driver Pins
// In1, In2, In3, In4 in the sequence 1-3-2-4
Stepper small_stepper(STEPS, 8, 10, 9, 11);
Stepper small_stepper2(STEPS, 40, 41, 42, 43);

// Interrupt routine runs if CLK goes from HIGH to LOW
void isr () {
  delay(4);  // delay for Debouncing
  if (digitalRead(PinCLK))
    rotationdirection = digitalRead(PinDT);
  else
    rotationdirection = !digitalRead(PinDT);
  TurnDetected = true;
  /////I added this
  delay(4);  // delay for Debouncing
  if (digitalRead(PinCLK2))
    rotationdirection = digitalRead(PinDT2);
  else
    rotationdirection = !digitalRead(PinDT2);
  TurnDetected = true;
}
/////up to here

void setup () {
  pinMode(PinCLK, INPUT);
  pinMode(PinDT, INPUT);
  pinMode(PinSW, INPUT);
  digitalWrite(PinSW, HIGH); // Pull-Up resistor for switch
  attachInterrupt (0, isr, FALLING); // interrupt 0 always connected to pin 2 on Arduino UNO
  pinMode(PinCLK2, INPUT);
  pinMode(PinDT2, INPUT);
  pinMode(PinSW2, INPUT);
  digitalWrite(PinSW2, HIGH); // Pull-Up resistor for switch
  attachInterrupt (0, isr, FALLING); // interrupt 0 always connected to pin 2 on Arduino UNO
}

void loop () {
  small_stepper.setSpeed(600); //Max seems to be 700
  if (!(digitalRead(PinSW))) {   // check if button is pressed
    if (RotaryPosition == 0) {  // check if button was already pressed
    } else {
      small_stepper.step(-(RotaryPosition * 50));
      RotaryPosition = 0; // Reset position to ZERO
    }
  }

  // Runs if rotation was detected
  if (TurnDetected) {
    PrevPosition = RotaryPosition; // Save previous position in variable
    if (rotationdirection) {
      RotaryPosition = RotaryPosition - 1;
    } // decrase Position by 1
    else {
      RotaryPosition = RotaryPosition + 1;
    } // increase Position by 1

    TurnDetected = false;  // do NOT repeat IF loop until new rotation detected

    // Which direction to move Stepper motor
    if ((PrevPosition + 1) == RotaryPosition) { // Move motor CW
      StepsToTake = 50;
      small_stepper.step(StepsToTake);
    }

    if ((RotaryPosition + 1) == PrevPosition) { // Move motor CCW
      StepsToTake = -50;
      small_stepper.step(StepsToTake);
      small_stepper2.setSpeed(600); //Max seems to be 700
      if (!(digitalRead(PinSW2))) {   // check if button is pressed
        if (RotaryPosition2 == 0) {  // check if button was already pressed
        } else {
          small_stepper2.step(-(RotaryPosition * 50));
          RotaryPosition2 = 0; // Reset position to ZERO
        }
      }

      // Runs if rotation was detected
      if (TurnDetected)
      {
        PrevPosition2 = RotaryPosition2; // Save previous position in variable
        if (rotationdirection) {
          RotaryPosition2 = RotaryPosition2 - 1;
        } // decrase Position by 1
        else {
          RotaryPosition2 = RotaryPosition2 + 1;
        } // increase Position by 1

        TurnDetected = false;  // do NOT repeat IF loop until new rotation detected

        // Which direction to move Stepper motor
        if ((PrevPosition2 + 1) == RotaryPosition2) { // Move motor CW
          StepsToTake = 50;
          small_stepper2.step(StepsToTake);
        }

        if ((RotaryPosition2 + 1) == PrevPosition2) { // Move motor CCW
          StepsToTake = -50;
          small_stepper2.step(StepsToTake);
        }
      }
    }
  }
}

Welcome to Arduino SE.  Be sure to take the tour to see how this works and to earn a badge:  https://arduino.stackexchange.com/Tour

simple:
1) write a set of routines that drive your servo motor via interrupts: you will need to specify the on-time for each servo channel.
2) write a set of routines that read the rotary positions.
3) write a set of routines that convert the rotary positions into the on-time parameter.
4) integrate them all.
in  your loop, you will simply need to read one rotary position, convert it into the on-time for that channel, and update the on-time parameter. The servo routines will run in the background transparently to your code.


text:
WiFi connections being lost on connection reset
Look at the trick in the last few lines of this code:
#include <ESP8266WiFi.h>

const char* ssid = "xxxxx";
const char* password = "yyyyyyy";

// Create an instance of the server
// specify the port to listen on as an argument
WiFiServer server(80);

void setup() {
  Serial.begin(115200);
  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");

  // Start the server
  server.begin();
  Serial.println("Server started");

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

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

 int delays = 0;

 // Wait until the client sends some data
 Serial.println("new client");
 while(!client.available()){
    delay(1);
    delays++;  // First line of trick.
    if (delays > 10) {
       return;
    } // Trick ends.
  }
  ...// Handle some events.
}

Code works ok without the trick (only delay(1); inside the loop), but the problem is it gets stucked there, if some responses are asked from browser so that tab is closed in between the requests.
One response is for favicon:
 if (req.indexOf("favicon.ico") != -1) {
    String s = "HTTP/1.1 404 WTF Favicon !!\r\n";
    client.print(s);
    client.flush();
    return;
 }

I had also one similar response starting with 200 OK for certain URLs and then a response of plain json text.
I would like to know why my server gets stucked on this delay(1);? Also, when the trick is needed, what is correct delays value?
Also I did add a client.flush(); after every client.print();. May that affect anything?

WifiServer class has a bug that is now resolved. It causes a phenomenom described like follows:

When I send message to client via WifiServer.avalible, the user is disconnected from server - I can connect to it again, so server is not stopping.

And latest comment on topic is that it is corrected in latest commits.


text:
Two ints declared simultaneously, one "does not name a type"
I have several integers, all of which are declared and set to zero in setup. However, in a method, I can only modify the value of half of those integers. The method is to read several buttons and return which of them have been pressed (precondition is that no more than one buttons are pressed):
  int readButtons(){
  rbuttonState = digitalRead(right);
  lbuttonState = digitalRead(left);
  sbuttonState = digitalRead(sel);
  obuttonState = digitalRead(off);
  nbuttonState = digitalRead(snooze);
  int ret = -1;
  if (rbuttonState != lastrButtonState){
        if (rbuttonState == HIGH) {
            ret = right;
          }
        }
        if (lbuttonState != lastlButtonState){
          if (lbuttonState == HIGH) {
            ret = left;
          }
        }
        if (sbuttonState != lastsButtonState){
          if (sbuttonState == HIGH) {
            ret = sel;
          }
        }
        if (obuttonState != lastoButtonState){
          if (obuttonState == HIGH) {
            ret = off;
          }
        }
        if (nbuttonState != lastnButtonState){
          if (nbuttonState == HIGH) {
            ret = snooze;
          }
        }
  }
  lastrButtonState = rbuttonState;
  lastlButtonState = lbuttonState;
  lastsButtonState = sbuttonState;
  lastoButtonState = obuttonState;
  lastnButtonState = nbuttonState;
  return ret;
}

Yet I have the errors that
Arduino: 1.6.12 (Mac OS X), Board: "Arduino Nano, ATmega328"

Nixie_Clock_0:65: error: 'lastrButtonState' does not name a type
   lastrButtonState = rbuttonState;
   ^
Nixie_Clock_0:66: error: 'lastlButtonState' does not name a type
   lastlButtonState = lbuttonState;
   ^
Nixie_Clock_0:67: error: 'lastsButtonState' does not name a type
   lastsButtonState = sbuttonState;
   ^
Nixie_Clock_0:68: error: 'lastoButtonState' does not name a type
   lastoButtonState = obuttonState;
   ^
Nixie_Clock_0:69: error: 'lastnButtonState' does not name a type
   lastnButtonState = nbuttonState;
   ^
Nixie_Clock_0:70: error: expected unqualified-id before 'return'
   return ret;
   ^
Nixie_Clock_0:71: error: expected declaration before '}' token
 }
 ^
exit status 1
'lastrButtonState' does not name a type

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

(The last line of code is line 72).
I am at a complete loss. Any help?

Where is the rest of your code?

There is an end bracket too many. Indent the code correctly and you will find it.

the posted code does not contain 70 some lines of code.  It only contains 40 lines of code.  Post the actual code.

@Mikael Patel thanks! I can't believe I missed that!

the following code

is properly indented
is missing the declarations of the variables for the 'button states' and the 'prior button states'
has additional text about a format error
is properly indented
has the code blocks properly separated by a single blank line

and now the code
int readButtons()
{
    rbuttonState = digitalRead(right);
    lbuttonState = digitalRead(left);
    sbuttonState = digitalRead(sel);
    obuttonState = digitalRead(off);
    nbuttonState = digitalRead(snooze);
    int ret = -1;

    if (rbuttonState != lastrButtonState)
    {
        if (rbuttonState == HIGH)
        {
            ret = right;
        }
    }

    if (lbuttonState != lastlButtonState)
    {
        if (lbuttonState == HIGH)
        {
            ret = left;
        }
    }

    if (sbuttonState != lastsButtonState)
    {
        if (sbuttonState == HIGH)
        {
            ret = sel;
        }
    }

    if (obuttonState != lastoButtonState)
    {
        if (obuttonState == HIGH)
        {
        ret = off;
        }
    }

    if (nbuttonState != lastnButtonState)
    {
        if (nbuttonState == HIGH)
        {
        ret = snooze;
        }
    }
}  << extranious closing brace ends the actual function

    lastrButtonState = rbuttonState;
    lastlButtonState = lbuttonState;
    lastsButtonState = sbuttonState;
    lastoButtonState = obuttonState;
    lastnButtonState = nbuttonState;
    return ret;
}


text:
Library using another library
I'm writing library for smart home arduino DIY project.
i want to use another library(not written by me).
here is the code:
boiler.cpp
#include "Boiler.h"

Boiler::Boiler(int pin)
{
    _pin = pin;
    dev.setDevice(_pin);                    // Set Device Output (on/off)
    turnOff();
}

boiler.h
#ifndef BOILER_H_
#define BOILER_H_

// include RF24 libs
#include "RF24.h"
#include "RF24Network.h"
#include "RF24Mesh.h"
#include <SPI.h>

// SmartHome Lib Includes
#include "Device.h"
#include "TimerOne.h"
#include "timeSet.h"

class Boiler
{

    private:

        RF24 radio(7, 8);
        RF24Network network(radio);
        RF24Mesh mesh(radio, network);

        int _pin ;

        void timerIsr();
        void DrawSCR();
    public:
        .
        .
        .

        Boiler (int pin );
        void turnOn();
        void turnOff();
};

The problem is it's not compiling
the error I get is :
Boiler.h: 32:14: error: expected identifier before numeric constant
RF24 radio(7, 8)
What am i doing wrong?
Thanks,

I've always had to put the includes of all "sub-libraries" in the main sketch.

But i wish to use it in the library... i only declare the boiler and takes care of the communication ....

You already asked this on SO. Don't cross post.

I Have found the answer (by mistake)
i have added the includes to Boiler.cpp file
#include "RF24.h"
#include "RF24Network.h"
#include "RF24Mesh.h"
#include <SPI.h>
.
.
.
#include "Boiler.h"

RF24 radio(7, 8);                                   // Init RF24 Radio
RF24Network network(radio);                         // Init RF24 Network
RF24Mesh mesh(radio, network);                      // Init RF24 Mesh

Boiler::Boiler(int pin ,float Rev , String Last )
{
    _pin = pin;
    dev.setDevice(_pin);                    // Set Device Output (on/off)
    turnOff();
}

void Boiler::init( char nodeID)
{
    _nodeID = nodeID;
    // Connect to the mesh and set Node ID
    mesh.setNodeID(_nodeID);
    if (_DEBUG) Serial.println(F("Connecting to the mesh..."));
    mesh.begin();

    // init LCD and print init data on LCD
    myGLCD.InitLCD(60);                         // Init LCD 55 contrast
    myGLCD.setFont(SmallFont);                  // Set small font
    myGLCD.clrScr();                            // clr screen
    myGLCD.print("Boiler Device",0,0);          //Print init Data on screen
    myGLCD.print("Rev :" , 0 , 10);
    myGLCD.printNumF(_rev,1 ,35,10,'.',1,'0');
    myGLCD.print(_last,0,40);
    myGLCD.update();                            // Update display

    turnOff();
}

and now it compiles ;-)

What am i doing wrong?

without seeing those includes, it is hard to tell.
I can say is that your original code, with the includes in boiler.h, is the right approach.
the revised code, which doesn't give you the error message, it not the right approach.
the issue is likely that the associated .h and .cpp files are incorrectly coded. unfortunately, without the actual code, it is hard to tell how and what the fixes should be.

you can see the library here: https://github.com/danhajduk/SmartHome

is it posible to declare public variable from method constractor?


text:
Nano clone failure, how to prevent it from happening again?
I'd made an LED driver, and fed both the LEDs and nano clone from 12V. The 12V switched power supply is of dubious quality. The nano itself read a pot, and wrote PWM values on three pins. It has run on-off for 2-3 months. Not long. Now it's dead - my PC does register the serial device on the nano, and the power LED comes on. Apart from that, there's nothing that works.
Before I replace it, I'd like to know if the most likely culprit was my feeding 12V into VIN. Overheating voltage regulator? The LEDs got a bit hot, ~40°, and the nano was in a box with no airflow.

How did you connect the leds?

They were connected through 3 2N7000 MOSFETs, they didn't pull power from the nano. I have considered if they exceeded their rated current, but am unsure. IIRC, it's a 10V MOSFET, which I turned on with a 5V signal. The rated current is 200mA max. In any case, would a burnt MOSFET murder my nano? I've heard the act like shorts when they die. Please apply cluebat.

Did you put a resistor between the Arduino and the gate of the mosfet?

Yes, 220 ohms for good measure. I know the 2N7000 doesn't surge. I checked the MOSFETs, and all LED channels (R, G, B) work. It's just the nano that's dead.

You could try reflashing the boot loader using a separate Arduino. Have you measured the voltage of the power supply? Some are only 12V when under load, and can go as high as e.g. 18V when there is no or minimal load.

Also try measuring the 5V pin when you connect the 12v to Vin. It could be that the voltage regulator is broken.

I see a 5V signal on the 5V pin, but the program in flash is not running as far as I can tell. The PWM pins send out random values, and turning the potentiometer is not affecting these values. The power supply is at 12V, both unloaded and loaded. I use one of these for a small 10W drill. I'll look into flashing it on the RXD/TXD pins first, then I'll try reflashing the bootloader. Thanks. If you post the last comment below as an answer, I'll close this question.

Dyd you try to flash in a simple Blink using the onboard LED? You should go very basic when things start to fail like that. Also, disconnect the 12V power supply and power your nano from USB only when running this simple test: the voltage regulator should not be part of the circuit when powered from USB and you can start factoring things out.

Yes, I did that - the device is not responding. Rxd/Txd pins are dead as well. I'm putting this down to overheating voltage regulator inside an already toasty-hot closed compartment.


text:
Mega SPI communication changing between setup and loop
I am attempting to use an arduino MEGA 2560 to control a digital potentiometer (AD5206), but I am getting some strange behavior. I have attached the CLK and MOSI pins (52 and 51, respectively) to an oscilloscope, and have run the following code:
#include <SPI.h>
void setup() {
    SPI.begin();
    SPI.transfer(5);
    delay(500);
}

void loop() {
    SPI.transfer(5);
    delay(500);
}

When I look at the signal, the transfer in the setup() looks correct (5V x 00000011), but then the transfer in the loop() looks like it's shifted by -5V (-5V x 11111100). Has anyone ever run into this? Is it possible for the MEGA to output a negative voltage?

You are not controlling the chip properly. Read the datasheet, and learn how SPI communication works, then you will know what is blatantly missing from your code.

I realize that the above code is not sufficient to control the AD5206. I have only posted a small piece of code that demonstrates the issue that I am seeing. The problem is that the 8bit spi signal is being shifted by -5V in the loop (but not in the setup).

Except where is the start of the 8 bit SPI signal? Where is your chip select control that frames each transaction and tells the chip where the start of communication is?

In my actual code, I pull the SS low, send the pin address and the resistor value (2x8 bit signals). The code that I have posted is the most concise script that I can post that creates the issue that I am asking about. I am not concerned with the serial formatting for communicating with the AD5206. My question here is purely concerned with the Arduino serial signal being shifted by -5V in the loop.

Well, as it stands that code is invalid and doesn't demonstrate anything at all. With no synchronisation there is no clue what the different clock pulses mean.

Oh, and how are you determining that the output is wrong?

No, there is no problem with SPI on the Mega. If there were it would have been noticed by now.
Instead it's either the way you are measuring it or your method of generating the SPI signals that are at fault (and since you won't show us your real code we can't help you with that).
This is a trace of your provided "code" with the delays reduced to allow easier fitting on a single trace:

Clock goes low when SPI.begin() is called. Then there are the successive transfers - the first being in setup() and the rest in loop(). As you can see they are all identical.


text:
ESP8266 - Parsing last char from a string
I'm trying to parse the last character from the string of the reply from server and print them to serial monitor.
My arduino code:
// This will send the request to the server
  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
           "Host: " + host + "\r\n" +
           "Connection: close\r\n\r\n");
  delay(10);

  // Read all the lines of the reply from server and print them to Serial
  while(client.available()){
    String line = client.readStringUntil('\r');
    Serial.print(line);
  }

My PHP page only shows the following though:
  Output: 1
  Watering: 1

I get the following output from my Serial Monitor:
  HTTP/1.1 200 OK
  Date: Fri, 28 Apr 2017 19:27:40 GMT
  Server: Apache/2.4.25 (Win32) OpenSSL/1.0.2j PHP/7.1.1
  X-Powered-By: PHP/7.1.1
  Content-Length: 9
  Connection: close
  Content-Type: text/html; charset=UTF-8

  Output: 1
  Watering: 1

I want to get the value of Output(In this case it's a 1), and Watering(Also a 1), etc...
Preferably store them in an int.
I tried using startsWith,endsWith,etc. but to no avail :(

Welcome to Arduino SE.  Be sure to take the tour to see how this works and to earn a badge:  https://arduino.stackexchange.com/Tour

I'm voting to close this question as off-topic because it's an elemental programming question, not related to Arduino in any way.

I've converted the string to a char array and just checked if there is a 1 or a 0 at that region.
// Read all the lines of the reply from server and print them to Serial
String line;
int value=0;
while(client.available()){
  line += client.readStringUntil('\r');
}
//Serial.print(line);
char charBuffer[line.length()+1];
line.toCharArray(charBuffer, line.length()+1);
for(int i=207;i<line.length()+1;i++)
{
  if(charBuffer[i] == '1')
  {
    value = charBuffer[i];
  }
  if(charBuffer[i] == '0')
  {
    value = charBuffer[i];
  }
  Serial.print(charBuffer[i]);
  //delay(20);
}

You don't need to copy the entire string to a buffer; charAt give you access to the internal String buffer.  Your method doesn't work for string shorter than 207 chars. Your method return any 1 or 0 in the string, not the last char in the string.

I know it doesn't work for anything shorter than 207 hence why I started to search for info at char 207 and above. charAt won't work properly because the server sends a different responce in the morning opposed to an evening. You didn't even understand this question in the first place and I've already posted a solution that works for me back in April.

Your code is also inefficient, both in time and space. You can read from client char by char and detect/print the last digit at the same time. No need to waste space holding the whole string. No need to make a second pass looking for the last digit.

If you have a String s, then s.charAt(s.length() - 1) give you that last char.
The function length gives you the number of chars in the string (not counting the '0' marker). The function charAt give you a single char at the position. The first char is at position 0.
For converting a single char digit D (0..9), you can use (D - '0').
Demo:
void setup() {
  Serial.begin(9600);
  while(!Serial);
  String s = "Watering: 1";
  char last = s.charAt(s.length() - 1);
  Serial.println(last);
  int value = (int) (last - '0');
  Serial.println(value);
}

void loop() {
}

As I've said previously the char position changes on an hourly basis and won't be in the same place so I need to string search for that integer. Also this was posted back in April..

@William.  Beg your pardon? Your question starts with *I'm trying to parse the last character from the string of the reply from server and print them to serial monitor."


text:
Controlling I2C slave on Arduino with Python
Typically, when I connect my Arduino to a slave device through I2C or SPI, I'll control the slave using instructions coded in the firmware. The output data will be then printed to the Serial port and I'll use Python or MATLAB to read from the serial port and process the data later on.
PC <- Arduino <--> Slave

Now say I want to control the I2C slave from my computer, i.e. write instructions to the I2C slave. How do I go about it? I thought of writing to the Arduino Serial port, making Arduino read it and hence configuring it but this doesn't seem efficient and I have been racking my head over this for a while.

why wouldn't that be efficient? You can put an interrupt on an incoming string.

That use of an Arduino as a 'format converter' to a peripheral from a computer is 'efficient' in the sense that you can use what you have to hand, do it quickly, expect it to work, and debug it easily if it doesn't. It's not efficient in the sense that there's an extra  computer in the way, but, who cares?

Reading the comments I have to agree with you guys. I like the idea of using an interrupt. I'll definitely check on that and I think that is the solution I might be looking for.

Welcome to Arduino SE.  Be sure to take the tour to see how this works and to earn a badge:  https://arduino.stackexchange.com/Tour

Have you looked into the pigpio library?  Do a quick search, maybe?

The OP did not mention the Raspberry Pi which is what the Pigpio library is for.

Since you are using an arduino as a partial bridge to a PC, it appears that you already have a solution in hand.
There is a project on Git that is intended to perform this function that you could use for reference.  (Disclaimer -- I have not tested this code.)
The cheapest stand alone device that I found was a $15 breakout board from Adafruit.


text:
Do they make 2.54mm 2P Crimpable Micro JST Female connectors?
This may be a dumb question but I need some (preferably with wires already attached) and I'm unable to find any like this. Everything I find has male crimps and female surface mount. That doesn't work for very well with my project because I do not have room in my project box for another board. I'm already cramped just adding the headers that I was planning to solder these wires to.
Here is what I'm looking for in the 1.25mm variety:

I don't believe "micro style" is a JST family designator.  You should start by figuring out which JST family you actually want, often they use two letter designations.  Also, voting to close as this has nothing specifically to do with Arduino, but is rather an entirely generic electronics question.

I've found this product listing on Amazon:
2.54mm spacing JST extension cable.
It resembles the connector you've shown only slightly, but may be the only option out there.
And to contest the above statement, one that looks more like your objective:
Another 2.54mm spacing JST cable
There may be others. I used "jst 2.54 mm 2 pin female cable" as the search terms specifically in Amazon, other sources may have similar results.
Firing up the old Google again, using the last set of search terms, I've found an eBay listing:
eBay product listing
with the source in china. The photo appears correct, although the listing is for two cables, one male, one female, there is a third photo with the circuit board mount type connector.
This particular listing calls them a 2.5 mm connector, close enough? Perhaps a translation error.

The first is not the micro style. I don't think that is the same but I could be wrong. It looks much different. The second appears to be a typo because the picture shows male ends on the wires.

I don't think the first type would be interchangeable with the white connector style. I grabbed the second because of the text and didn't look at the image. I've added a third link, but it has caveats as well.


text:
Trying to print "occur = 1" in an if statement but it wont work
Cant seem to get this code to work with my arduino, and yes its all hooked up properally, even used leds to show that the button is being pressed, what am i doing wrong or dont know?
const int digitalInPin3 = 8;     //switch
int Occur = 0;
int Switch = 0;

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

void loop() {
int Switch = digitalRead(digitalInPin3);

if (Switch == 1){
  int Occur = 1;
}

else {
 int occur = 2;
}

   Serial.print("\t Switch =");
   Serial.print(Switch);
   Serial.print("\t occur =");
   Serial.println(Occur);

  delay(1);
}

You have 3 independent Occur variables; 1 global, 2 local. You also spell them differently!

Welcome to Arduino SE.  Be sure to take the tour and earn a badge at https://arduino.stacvkexchange.com/Tour

Remove the int from inside the if and else statement. The code would always show 0 because access of occur, which is assigned value 1 or 2 is limited to the if..else statement. So the global occur remains 0 always.
So change it to:
if (Switch == 1){
 Occur = 1;
}
else {
 Occur = 2;
}

This will work.

The capitalization of the second variable name is incorrect.

oh, yes. Haven't seen it.

The comments are right, as is the other answer.
Also, I see that both Switch and Occur are highlighted as if they are keywords.
I know for sure Switch is a reserved word.
Take all of these suggestions together.  Remove the int from inside the if.
I recommend you change the variable names entirely to something else.  And make them consistent.
Define them one time at the top then just modify them within the code.


text:
Can I make multiple loop() functions with Arduino Uno?
I have a problem. I want to make a car with a motor, front lights and rear lights. I want to run them at the same time but in different loops.
This is my code.
const int red1 = 10;
const int red2 = 11;
const int blue1 = 12;
const int blue2 = 13;
const int front1 = 3;
const int front2 = 4;
const int back1 = 5;
const int back2 = 6;
const int enablePWMPin = 9;
const int controlPinA = 8;
const int controlPinB = 7;
int buzzer = A0;

void setup() {
  pinMode(red1, OUTPUT);
  pinMode(red2, OUTPUT);
  pinMode(blue1, OUTPUT);
  pinMode(blue2, OUTPUT);
  pinMode(front1, OUTPUT);
  pinMode(front2, OUTPUT);
  pinMode(back1, OUTPUT);
  pinMode(back2, OUTPUT);
  pinMode(enablePWMPin, OUTPUT);
  pinMode(controlPinA, OUTPUT);
  pinMode(controlPinB, OUTPUT);

  digitalWrite(enablePWMPin, LOW);
  digitalWrite(front1, LOW);
  digitalWrite(front2, LOW);
  digitalWrite(back1, LOW);
  digitalWrite(back2, LOW);
  digitalWrite(red1, LOW);
  digitalWrite(red2, LOW);
  digitalWrite(blue1, LOW);
  digitalWrite(blue2, LOW);
  noTone(buzzer);
}

void loop() {
  digitalWrite(enablePWMPin, HIGH);
  digitalWrite(controlPinA, HIGH);
  digitalWrite(controlPinB, LOW);
  delay(3000);
  digitalWrite(controlPinA, LOW);
  digitalWrite(controlPinB, HIGH);
  delay(3000);
}

void loop() {
  digitalWrite(red1, HIGH);
  digitalWrite(red2, HIGH);
  digitalWrite(blue1, LOW);
  digitalWrite(blue2, LOW);
  delay(250);
  digitalWrite(red1, LOW);
  digitalWrite(red2, LOW);
  digitalWrite(blue1, HIGH);
  digitalWrite(blue2, HIGH);
  delay(250);
}

void loop() {
  int directionA = digitalRead(controlPinA);
  int directionB = digitalRead(controlPinB);
  if (directionA == HIGH && directionB == LOW) {
    digitalWrite(front1, HIGH);
    digitalWrite(front2, HIGH);
    digitalWrite(back1, LOW);
    digitalWrite(back2, LOW);
  } else if (directionA == LOW && directionB == HIGH) {
    digitalWrite(back1, HIGH);
    digitalWrite(back2, HIGH);
    digitalWrite(front1, LOW);
    digitalWrite(front2, LOW);
  } else {
    digitalWrite(front1, LOW);
    digitalWrite(front2, LOW);
    digitalWrite(back1, LOW);
    digitalWrite(back2, LOW);
  }
}

I'm using an Arduino Uno. Can I start all the loop() functions at the same time?

Just trying to compile it should provide you with an answer...

Not with an Uno, but it is possible with a Due

As the others have stated, no you can't have multiple loop functions. What you need to do is modify your approach so that each thing you are trying to do can be done sequentially without blocking (ie: remove the delay function usage). Expanding on some suggestions by JRobert, Here is how I would make these functions "run at the same time":
void loop() {

    lights1();
    lights2();
    motor();

}

void lights1() {

  static unsigned long lastTime = 0;
  const long interval = 3000;
  static bool state = 0;

  unsigned long now = millis();

  if ( now - lastTime > interval && state == 0) {
    state = 1;
    lastTime = now;
    digitalWrite(enablePWMPin, HIGH);
    digitalWrite(controlPinA, HIGH);
    digitalWrite(controlPinB, LOW);
  }

  if ( now - lastTime > interval && state == 1) {
    state = 0;
    lastTime = now;
    digitalWrite(controlPinA, LOW);
    digitalWrite(controlPinB, HIGH);
  }
}

void lights2() {

  static unsigned long lastTime = 0;
  const long interval = 250;
  static bool state = 0;

  unsigned long now = millis();

  if ( now - lastTime > interval && state == 0) {
    state = 1;
    lastTime = now;
    digitalWrite(red1, HIGH);
    digitalWrite(red2, HIGH);
    digitalWrite(blue1, LOW);
    digitalWrite(blue2, LOW);
  }

  if ( now - lastTime > interval && state == 1) {
    state = 0;
    lastTime = now;
    digitalWrite(red1, LOW);
    digitalWrite(red2, LOW);
    digitalWrite(blue1, HIGH);
    digitalWrite(blue2, HIGH);
  }

}

void motor() {
  int directionA = digitalRead(controlPinA);
  int directionB = digitalRead(controlPinB);
  if (directionA == HIGH && directionB == LOW) {
    digitalWrite(front1, HIGH);
    digitalWrite(front2, HIGH);
    digitalWrite(back1, LOW);
    digitalWrite(back2, LOW);
  } else if (directionA == LOW && directionB == HIGH) {
    digitalWrite(back1, HIGH);
    digitalWrite(back2, HIGH);
    digitalWrite(front1, LOW);
    digitalWrite(front2, LOW);
  } else {
    digitalWrite(front1, LOW);
    digitalWrite(front2, LOW);
    digitalWrite(back1, LOW);
    digitalWrite(back2, LOW);
  }
}

This approach will simulate running all three functions at the same time. Each function runs one at a time. But, since the delay has been removed from the light1/2 functions, they will end quickly during the 'waiting' period instead of pausing execution. This will allow the motor(s) to run and lights to blink all at the same time.

No you cannot.
Not only is it no proper C/C++ to have multiple identical functions, i.e. it will not compile (as jfpoilpret's comment suggests). It is also not in accordance with the idea of programm flow in the Arduino world - the sketches - where you have two methods on the highest (user accessible) level: void setup() and void loop(). setup is run exactly once at the beginning of your program. Following that loop is looped (hence the name) forever. You need to properly restructure your code to implement your intended program flow, i.e. call your own functions from loop. Read more on www.arduino.cc with tutorials worth studying.

What are you trying to accomplish? Are these loops meant to run simultaneously (not possible)? Or one after the other? You could get pretty close to "simultaneous" if "real fast" is good enough. You'd need to

Give each loop function a new, unique name;
Split each of the first two loops at the delay()s for a total of 5 functions;
Use a timer library such as SimpleTimer to run each of the functions at the rate you need them to.
and from the only loop() function, keep calling SimpleTimer's '.run()' function to keep the whole thing going.

You could improve the speed of the individual functions by replacing the digitalRead() and digitalWrite() calls with direct reads and writes to port and bit you want read or set.

I want to run them at the same time but in a different loop.

First of all, you can only do one thing at a time. So that's out.
Secondly, to run multiple loops sequentially (one at a time), it is fairly easy:
void loop1(void) {...}
void loop2(void) {...}
...

void loop(void) {
  loop1(); //run loop1
  loop2(); //run loop2
  ...
  loopn(); //run loopn
}

Whether it works will depend on how you have coded those loops.

To use multiple loops at the same time you need a Arduino Due Board.
It is the only board compatible with library #include <Scheduler.h>
See Examples > Scheduler Library > Multiple Blinks
// Include Scheduler since we want to manage multiple tasks.
#include <Scheduler.h>

int led1 = 13;
int led2 = 12;
int led3 = 11;

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

  // Setup the 3 pins as OUTPUT
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);

  // Add "loop2" and "loop3" to scheduling.
  // "loop" is always started by default.
  Scheduler.startLoop(loop2);
  Scheduler.startLoop(loop3);
}

// Task no.1: blink LED with 1 second delay.
void loop() {
  digitalWrite(led1, HIGH);

  // IMPORTANT:
  // When multiple tasks are running 'delay' passes control to
  // other tasks while waiting and guarantees they get executed.
  delay(1000);

  digitalWrite(led1, LOW);
  delay(1000);
}

// Task no.2: blink LED with 0.1 second delay.
void loop2() {
  digitalWrite(led2, HIGH);
  delay(100);
  digitalWrite(led2, LOW);
  delay(100);
}

// Task no.3: accept commands from Serial port
// '0' turns off LED
// '1' turns on LED
void loop3() {
  if (Serial.available()) {
    char c = Serial.read();
    if (c=='0') {
      digitalWrite(led3, LOW);
      Serial.println("Led turned off!");
    }
    if (c=='1') {
      digitalWrite(led3, HIGH);
      Serial.println("Led turned on!");
    }
  }

  // IMPORTANT:
  // We must call 'yield' at a regular basis to pass
  // control to other tasks.
  yield();
}

void is not a verb.

@gre_gor: Using that word as a verb may void its warranty ;-)

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