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:
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'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);
}

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.

source: Stack Exchange

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

sort: votes


text:
ESP8266 module cutting connection with PC via USB
My Arduino UNO is connected directly to the ESP8266 (01) WiFi module. The Red and Blue LED flashes and it seems to work properly. But when I connect the UNO to my computer, the module refreshes at irregular intervals and the PC produces sounds as that of ejecting and inserting a USB. I don't know whether this is caused due to low voltage supplied from the USB or some other reason. Please help me out...

At which pins you connected the ESP8266?
The pins pin 0 (RX) an 1 (TX) are connectet internaly to the FTDI USB-to-TTL Serial chip.
If you using Serial.begin() to communicate with the ESP8266, you can't communicate with the pc at the same time.
Use SoftwareSerial to communicate with the ESP8266 an Serial to PC.
It is also recommed to feed the ESP8266 with an external 3.3V power supply and stabilize with an capacitor. This could  produces the sounds of ejecting and inserting a USB.

I've used pin 0 and 1. Since I'm a newbie to Arduino can you please provide a link for using SoftwareSerial.

A tutorial for using SoftwareSerial can be found here. For the code you can read this. Also this blog post could be helpful.

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


text:
Using VMA-02 / KA-02 Sound Shield to get line-in input on arduino
I bought this VMA-02 audio shield: http://www.velleman.co.uk/contents/en-uk/p623_vma02.html
I want it to get the data from line-in to line-out but with reading it in my arduino scetch first (e.g. for analysis later).
There's a example project to download here: http://www.apogeekits.com/Zip_Files/ka02-sample-code.zip
But I don't know whether it's possible to get the sound input anyway and if yes, with which pins I can read the input / write the output?


text:
Dealing with TCCRx
I am totally beginner in Arduino, and i want to ask some questions :
    TCCR1B = (TCCR1B & ~(0x07<<CS10)) | (2<<CS10);

What does the previous line mean? with good explaination please .
    TCCR1A &= ~(3<<COM1A0);

for the previous line , is there difference if i wrote '1' instead of '3' ? why ?

On the first line, you clear some bits, then set some bits in the same “region” of the byte.
From inside out, get 7 (which is 3 bits of ones: 00000111), shift it upwards (the << operation) by CS10 amount (we don’t know how much, but the compiler does), complement all that (the tilde ~ character) and bitwise ‘and’ it with the value of the TCCR1A register (the & operation). Next, take a 2 (binary 00000010), shift it up by CS10 bits again (<< CS10), and bitwise ‘or’ that bit pattern with the earlier result (the | operator). Finally, assign all that to TCCR1A.
For the second line, yes, changing 3 to 1 will certainly change what happens to TCCR1A. It makes a different bit pattern, and I'm sure you can reason it out after reading the previous explanation.

Your explanation is very clear, I am surprised that I looked so much to find a site with a good explanation and I have not found!
Thank you


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

Note: VCC2 is connected to 5V.

Looks like R1 has both sides connected to GND.

This might be helpful: https://github.com/MCUdude/MegaCore#minimal-setup

See http://www.atmel.com/Images/Atmel-2521-AVR-Hardware-Design-Considerations_ApplicationNote_AVR042.pdf

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

In theory (page 58 and 355 of the datasheet) the reset line has already a 30-60 kOhm pull-up resistor.
Yes, it might not be enough in very noisy/humid/dirty environments (as I found sometimes). I also always put a 10kOhm: it does not harm.

So it does. I'm used to MCUs with no internal pullup, but yes, it's good to add a proper external one anyway since that is quite a high value for a pullup.

Especially if you plan to use an external DTR+100nF based reset circuit for programming - the lower pullup value will recharge the capacitor faster.

Here in the Arduino forum: http://forum.arduino.cc/index.php?topic=152319.msg1143618#msg1143618 they say that just changing the processor, will be enough to work, basing on this: http://arduino.cc/en/Tutorial/ArduinoToBreadboard.

check the datasheet;
I would put a pull-up on the reset pin, plus a small capacitor;
crystal + capacitors as optional;
AVCC to VCC with filtering, if you need good analog performance;
separate Vbat domain, if it has one.

...


text:
#endif without #if
I have an extrange Problem...
I have written this short code:
////////////// BOARD SETTINGS \\\\\\\\\\\\\\
#define BAUD_RATE 9600

// Board type selection
// Uncomment the wanted
//#define WAND 0
//#define GUN 0
#define RIFLE 0

////////////// WAND SETTINGS \\\\\\\\\\\\\\
#ifdef WAND
//#define USE_CHARGER 0

#endif

////////////// GUN SETTINGS \\\\\\\\\\\\\\
#if GUN
//#define USE_CHARGER 0

#endif

////////////// RIFLE SETTINGS \\\\\\\\\\\\\\
#ifdef RIFLE
  #define USE_CHARGER 0

#endif

It's in a file called Settings.h, that I use in the main code:
#include "Settings.h"

void setup(){
  Serial.begin(BAUD_RATE);
  #ifdef WAND
    Serial.println("Initializing Wand...");
  #endif
  #ifdef GUN
    Serial.println("Initializing Gun...");
  #endif
  #ifdef RIFLE
    Serial.println("Initializing Rifle...");
  #endif
}

void loop(){
  #ifdef WAND

  #endif
  #ifdef GUN

  #endif
  #ifdef RIFLE

  #endif
}

But for an extrange reason, it gives me this error: error: #endif without #if
Full error is:
In file included from D:\MEGA\Winsoft\Projects\Hardware\MWands\Arduino_5\Arduino_5.ino:1:0:

Settings.h:15: error: #endif without #if

 #endif

  ^

Settings.h:21: error: #endif without #if

 #endif

  ^

Settings.h:27: error: #endif without #if

 #endif

  ^

exit status 1
#endif without #if

Any idea in where am I wrong?
And taking advantage that I'm asking, is necessary the 0 after #define RIFLE 0, next to each definition?

The way you are using it, no you dont' have to add the 0 #define XYZ is enough. #ifdef XYZ will work for this case.

Also, you have declared #if GUN which you probably meant #ifdef GUN.

Using #ifdef and ending with #endif still showing me that error

I didn't say it would fix the error, I was just answering your second question "is it necessary to have the 0..."

It looks like your comment style is causing the problem.
Remove the ////////////// BOARD SETTINGS \\\\\\\\\\\\\\ style comments, or change them to something like: /*----------- BOARD SETTINGS -----------*/

The \ at the end of the comment continues the current line onto the next one, so you get ///// comment \\\\\#ifdef... which comments out the #ifdef.

If you remove backslashes at the end of comments on lines before #ifdefs, it will work just fine.
The gvim editor was much more helpful in that:


text:
incompatible types in assignment of 'int*' to 'int [0]'
I was coding a class for "a kind of gun". I have this code for the classes:
Gun.h:
#ifndef Gun_h
#define Gun_h

#include "Arduino.h"

class Gun
{
  public:
    Gun(String identifier, String name, int teamIRCodes[]);
    String getIdentifier();
    String getName();
    int getIRCode();
  private:
    String _identifier;
    String _name;
    int _teamIRCodes[];
};

#endif

Gun.cpp:
#include "Arduino.h"
#include "Gun.h"

Gun::Gun(String identifier, String name, int teamIRCodes[])
{
  _identifier = identifier;
  _name = name;
  _teamIRCodes = teamIRCodes;
}

String Gun::getIdentifier(){
  return _identifier;
}
String Gun::getName(){
  return _name;
}
int Gun::getIRCode(){
  return _teamIRCodes[1];
}

It returns me this error while compiling:
sketch\Gun.cpp: In constructor 'Gun::Gun(String, String, int*)':

Gun.cpp:8: error: incompatible types in assignment of 'int*' to 'int [0]'

   _teamIRCodes = teamIRCodes;

                ^

exit status 1
incompatible types in assignment of 'int*' to 'int [0]'

The issue is with flexible array int _teamIRCodes[]; This is an old technique which I don't recommend. But if you want to use it, you need you use malloc to create a class object, adding on enough space for the array:
// Allocate space for the class AND the array
Gun *gun = (Gun *)malloc(sizeof(Gun) + sizeof(teamIRCodes));

However, this does not call the ctor, and you still have to manually copy the data:
for(int i = 0; i < (sizeof(teamIRCodes) / sizeof(teamIRCodes[0])); i++) {
    gun->_teamIRCodes[i] = teamIRCodes[i];
}

I think it's much simpler to use a pointer:
int* _teamIRCodes;

Then you can make your ctor:
Gun(String identifier, String name, int teamIRCodes[], int numberOfCodes) {
    _teamIRCodes = new int[numberOfCodes];
    // memcpy does the same thing as the for loop - copies the array
    memcpy(_teamIRCodes, teamIRCodes, sizeof(teamIRCodes[0]) * numberOfCodes);
}

And don' forget to add a dtor:
~Gun() {
    delete [] _teamIRCodes;
}

Or, if teamIRCodes is persistent throughout the lifetime of the object, you can just use a pointer to it:
 class Gun {
     public:
     int *_teamIRCodes;
     int _numberOfCodes;
     Gun(String identifier, String name, int teamIRCodes[], int numberOfCodes) {
         _teamIRCodes = teamIRCodes;
         _numberOfCodes = numberOfCodes;
   };

(Maybe this is an Arduino thing as this is the 2nd flexible array question I've seen today).

Ok, using this worked:
Replace
_teamIRCodes = teamIRCodes;

For
for(int i = 0; i < (sizeof(teamIRCodes)/sizeof(int)) ;i++)
    _teamIRCodes[i] = teamIRCodes[i];

Needed to iterate through array, cannot copy full array.

Close, but where do you allocate space for _teamIRCodes?

Doesn't it initialize with a value of 0? In Gun::Gun(String identifier, String name, int teamIRCodes[]) I add all the values

By now, it worked

Ok, it complied, but it seems that not working


text:
Having a problem to control digital servo with HC-06 bluetooth module
There are two problems to control digital servo(HD-1810MG) and HC-06 bluetooth module connection.

When I put a specific number to servo(in the video, I put 45), it shakes too much and shows useless movements before get to the right angle. I have no clue why this happens. Should I add more code to control it correctly?

This is my code.
#include SoftwareSerial.h
#include Servo.h

Servo myServo;
int TxD = 10;
int RxD = 11;
SoftwareSerial bluetooth(TxD, RxD);

void setup() {
  myServo.attach(9);
  Serial.begin(9600);       // start serial communication at 9600bps
  bluetooth.begin(9600);
}

void loop() {
  if (bluetooth.available()>0)
  {
    int servopos = bluetooth.read();
    Serial.println(servopos);
    myServo.write(servopos);
    delay(100);
  }
}

I used Nexus 5X and apk app to pair with HC-06. It pairs well at the first time of connection, but it loose connection after servo moved once. Application said it is connected with bluetooth, but HC-06's LED is blinking(which means disconnected). How can I maintain connection with HC-06?

This is my board.

And I made apk app using MIT App Inventor 2.
I'm so new to arduino and I'm not in major of engineering. Please give me an advice!

The Servo you are using, its a standard servo or continuous servo?

Definitely not enough power for the servo. Insufficient power causes the BT module to reset, and can also be a good reason for unexpected servo movements. Power the servo from a separate set of batteries (keep the GND of the battery connected to the GND of Arduino).

@ARK: I think it might be a standard servo. There is no item description about continuous property.

@Gee Bee: Yes, the power source was coming from USB on PC, so as you referred the power problem might have occurred. I bought alternative power source(case for 4 AA batteries, 5V, 1A) for test. I would try again using it. Thank you!

let have a look at following line of code:
int servopos = bluetooth.read();

I think that you are thinking that if you type in 1 in your
Bluetooth application. bluetooth.read() will pass that 1 to
sevopos. But, that's what not happens. What actually happens is that it will pass the ASCII value of whatever you type in you
app, to integer. So, if you have typed in 1, it will pass 49
to servopos.

I put 45

Now, think about it. when you type in 4 of this 45,
bluetooth.available()>0

becomes true.
int servopos = bluetooth.read();

bluetooth.read() will pass 52 (ASCII of 4) to servopos. Next,
myServo.write(servopos);

myservo will move your servo to lets say 52 degrees. and then there will be a delay.
Now, when you type in 5 of this 45, the procedure will be
repeated and your servo will be moved again by 53 degrees.
Now, you might be wondering that why 4 and 5 sepratly? Well,
all these intructution are being executed in MHzs. and secondly,
you, yourself has programmed that if loop you read just once
character. Yes, it will read character by character.

but it loose connection after servo moved once

I think your servo is drawing too much current from Arduino Board
which results in a drop in net voltage. And hence your HC-05 (kind
of) tuns off. This is what happens most of the time.

It is not a problem in serial connection. I have experienced this problem when I was trying to make a biped robot using 12 servos. It is the programming bug where Arduino does not use its timers properly. You can say that it is arduino limitation.
There are two main solutions :
1). Use Raspberry Pi instead of arduino.
2). Secondly you can make a small servo controlling shield of TLC5940 IC + servo controlling library...  Here is he Link: http://bildr.org/2012/03/servos-tlc5940-arduino/


text:
MQ7 Readings are too high
I am currently trying to learn how to use my MQ 7 CO Standalone to read CO in the air around the sensor. Currently Im using this circuit using my Arduino Uno. I get results of 900-1000. Here's a Fritzing Schematic on my setup.
Currently this is the code I am using on the arduino:
[code]
int mqx_analogPin = A0; // connected to the output pin of MQ-X

void setup(){
  Serial.begin(9600); // open serial at 9600 bps
}

void loop()
{
  // give ample warmup time for readings to stabilize

  int mqx_value = analogRead(mqx_analogPin);
  Serial.println(mqx_value);

  delay(100); //Just here to slow down the output.
}

I'm following the setup from this Instructables:
http://www.instructables.com/id/Smoke-Detector/?ALLSTEPS
However his readings are around 150-200ppm outside. I'm unsure how to reach these values since im following basically everything from the guide. Does anyone any experience with a MQ7 sensor?
I've been reading I need to preheat the sensor but I can't find any circuit that clearly shows how to preheat an MQ7 sensor or find any code for the arduino.

You are following a flawed tutorial which does not correctly operate the heater - see the comment by "Gregory0" part way down the page.

I believe you just leave it running for 5 minutes before taking a reading.

Using of this sensor is a bit more complicated than that. You must cycle through 60 seconds of heating and 90 seconds of measurement cycles, during heating you need to provide 5V on its heater pins, during measurement you need to provide 1.4V, so you'll need transistor or some other PWM-controlled current limiter (Arduino pin can't provide enough current for sensor heating).
I've tried to explain all details and calibration process here: https://www.instructables.com/id/Arduino-CO-Monitor-Using-MQ-7-Sensor/

Yes, it is not easy, lot of details to MQ-7 is here: http://www.arduinohobby.euweb.cz/  in the section "Analysator CO"

While this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference.

Yes, thank you. That link can helps. A foreign text can transform Google. MQ7 is element for stable enviroment and continuous ranning. Long brake of Vcc influences of the sensor sensitivity and it takes  time to return it. Basically, the MQ7 is for observing of a hygienic limit CO as 100ppm continuously with a compatator. That limit should be adjusted with a calibration gas and RL resistance. Any other application is comlicated, see that link.  Josef

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


text:
Using ATTiny85 as a USB HID Mouse
Our project involves using an arduino compatible microcontroller to control a mouse on a computer with an accelerometer and flex sensor. We had narrowed down to the ATTiny85 due to its small size.
We found a particular tutorial on the Adafruit tutorial  website, using the Adafruit Pro Trinket using the same ATTiny85.
Is there a reason to believe that this won't work?
Also, does anyone have suggestions as to which board to use apart from Micro as it isn't too available here?

Due to the lack of USB-Support of the ATtiny85 you will be forced to use something like V-USB as the tutorial does. This might have implications when you are targeting a commercial product.
Personally I'd suggest using the ATmega32u4. It has USB build right in.
But basically I don't see any reasons why it should not work.

If we use a breakout board with a USB like

If we use a breakout board with a USB like this one we won't need V-USB right? https://www.amazon.in/dp/B00Z09R3YC/ref=cm_sw_r_cp_apa_i_LKhnyb5J9FFWE

The description tells so. But it does not state how the USB is addressed. I suspect there is a boot loader that is used for programming (and therefore reduces the available space) basing on V-USB or similar. Perhaps it provides a wrapper so you can address USB easily.

There is a USB port right?

@Kwasmich raises a good point about the 32u4. Here is a little more information about it.

Works at 5V and 3.3V
Compatible with the Arduino IDE
Built-in USB
Very close to the ATmega328

Here are a couple of cheap breakouts for it

Arduino Pro Micro (5V/16MHz, 3.3V/8MHz)
Arduino Micro
Dreamer Nano V4

You forgot about the Arduino Leonardo

@Kwasmich, too big, never seen a mouse that big. I suggested the smallest models.

@Kwasmich we were aiming to be as portable as possible.


text:
Having trouble figuring out CTC on Timer 1 with ATTiny85
I'm using Timer1 on the Attiny85 clocked at 1MHz to toggle an LED every 1 second. However, I'm having some issues regarding prescaler and OSC value selection.
I'm using this formula, which I found in the datasheet for the Attiny.
fOCnx = fclk/(2*N*(1+OCRnx))

N = Prescaler
I'm taking fOCnx = 0.5Hz as I want a square wave
So based on the above formula, I tried the following cases

N = 2048, OCR1C = 243
N = 4096, OCR1C = 122
N = 8192, OCR1C = 61
N = 16384, OCR1C = 30

The LED toggles after an interval of 1s for cases 3 and 4. However, for cases 1 and, it seems to toggle after 2 seconds. Can anyone tell me why this is happening? Eventually, I want to use this to time data acquisition from a sensor I have so I need to be accurate.
Here's my code
#include <SoftwareSerial.h>

int ledPin = 1;
int state = 0;

SoftwareSerial ser(3, 4);
void setup() {
  // put your setup code here, to run once:
  TCCR1 |= 0x8F;
  OCR1C = 30;
  TIMSK = (1 << OCIE1A);
  pinMode(ledPin, OUTPUT);
  ser.begin(9600);
}

ISR(TIMER1_COMPA_vect)
{
  state = !state;
  digitalWrite(ledPin, state);
  ser.println(state);
}

void loop() {
  // put your main code here, to run repeatedly:
}

Have you double checked your settings for each case. I don't want to say you made a mistake. But what happens is hard to explain otherwise.  My values would be (TCCR1, OCR1C) -> (0x8f,30), (0x8e,61), (0x8d,122), (0x8c,244). I only see one of them in the code, so I can not say if you used the others. If you by accident use (0x8c,122) and then made just subtract 1 and double for the next text (0x8b,244)  the observation could be explained.  I also have a problem with the 2 in the formula. Where does it come from?

Ah, I see why you used 2 in the formula. You don't want 0,5 Hz, you want 2 Hz to toggle 2 times in a period of 1 second (0.5 sec from toggle to toggle. 0.5 Hz would be 2 sec from toggle to toggle).

I wrote 0.5Hz because the period of the cycle (On+Off) = 1+1 = 2s so 0.5Hz. I hope I could clarify.

yes, then I misunderstood. But then I have no glue why there is the 2 in the formula. fOCnx = fclk/(2*N*(1+OCRnx)) I mean I have no glue why it is in the nominator of the fraction. If I I insert one of the value pairs above I get 1 Hz. If I multiply both sides with 2. I get 2 Herz but not 0.5 Hz. Do you see my problem?

Well, unless there is some serious problem with my understanding, all the values calculated satisfy the formula, which I found from the datasheet on page 72. What is the formula you're using?

Ah, I see. The formula is used to compute the frequency of a squared waveform, but for a full wave length (High and LOW phase included).  So they have to toggle the output pin two times for one wave length. With this formula the interrupt routine where you toggle the pin is fired twice as often as you want it to. The values you computed are correct for this formula, and you get 1 Hz which each pair. But this 1 Hz means a square wave with a frequency of 1 Hz. But you need the IRQ routine to be fire with 1 Hz. To achieve that you had to remove the 2 from the formula and recompute the values.

Yes, but the problem is I'm achieving 1Hz for only cases 3 and 4. What's going on that's giving me the problem?

You're right, we drifted away from that. So I asked you if you've double checked the value you used in the program. I would use the following values: (TCCR1, OCR1C) -> (0x8f,30), (0x8e,61), (0x8d,122), (0x8c,243). I don't want to waste time thinking about other possibilities of failure if this is not clarified.

Ahh now I understand your confusion. The values I've used are given in my question and they're all the same as you've mentioned. I've just given one case in my program, which is case 4 as per the question.

Any solution @Peter Paul Kiefer? I tried all the values you've suggested and only the first two pairs works.

Sorry I didn't see your second last comment, I was not notified.  As I understand, you used exact the same values. Then, the only explanation I have is, that the Software serial must switch off the interrupts globally when it operates (print). I added an answer to explain my assumption. Another finding is that your set the register values with a combined or |= operation. If, for what reason ever, the register has some 1s in it, the resulting value is not what you expected. say  TCCR1 == 0x01 then the assignment TCCR1 |= 0x8E; results in TCCR1 == 0x8F

Ahh I see! I'll try to turn off the Software Serial and check the result. Also I'll try not to mask the output using |= as you've suggested.

The only explanation I have is, that the Software serial switch off the interrupts globally when it operates (print). If interrupts are locked when the timer completes, you loose a tick. It does not explain the different behavior of the four value pairs, but there are some issues reported in a german forum. They did not find an answer, but the assumed it depends on the 'delay()' function, that is used for the software serial and the fact that the interrupts are locked to make the delay function more exact.
If you want to be sure, you can try this by completely removing the Software Serial from your program. If you make the values switchable by e.g. a button press you can change it without having to reload the program. Then it's easier to see different  blinking intervals.
int ledPin = 1;
int state = 0;

int regValues[] = { 0x8f, 0x8e, 0x8d, 0x8c };
int cntValues[] = { 30, 61, 122, 243 };

const int buttonPin = 2;
int buttonState = LOW;

long lastDebounceTime = 0;
long debounceDelay = 80;
int lastButtonState = LOW;

int pairIndex = 0;

void setup()
{
  TCCR1 = regValues[ pairIndex ];
  OCR1C = cntValues[ pairIndex ];

  TIMSK = (1 << OCIE1A);

  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT);
}

ISR(TIMER1_COMPA_vect)
{
  state = !state;
  digitalWrite(ledPin, state);
}

void loop()
{
  int reading = digitalRead(buttonPin);

  if (reading != lastButtonState)
  {
    lastDebounceTime = millis();
  }

  if ( (millis() - lastDebounceTime) > debounceDelay)
  {
   if (reading != buttonState)
   {
      buttonState = reading;

      if (buttonState == HIGH)
      {
        if ( ++pairIndex > 3 )
        {
          pairIndex = 0;
        }

        TCCR1 = regValues[ pairIndex ];
        OCR1C = cntValues[ pairIndex ];
      }

    }

  }

}

I wrote this code without having a attiny to testing it. So hopefully all is correct. If you would try it, can you please report any errors, so I can correct them?

Ahh thank you so much! I'll try this code out and get back to you.

I tried out your suggestions. Looks like it started worked once I changed the assignment to = instead of |= as I was doing earlier. I guess some other bit was influencing the timer value. Thanks for your help!

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


text:
External Flash Memory File System
I'm building a weather data collector and I want to be able to dump that weather data somewhere. I've considered the options, and since I'm going to be storing a fairly small amount of data (in the megabyte range) I don't want to use SD cards (also SD cards are expensive). I've heard of use of NAND flash memory chips (like the W25Q32), and I was hoping that I could possibly interact with them in a simple way (since most ways require writing to each individual address). Is there possibly a way to build a file system within one of these small flash memory chips and interact with them as simply as interacting with an SD card?
TLDR: I want to interact with a flash memory chip easily to store basic ASCII data

While you can put a filesystem on an SPI flash, it's generally a bad idea, as many filesystem map poorly to the block-erase nature of NOR flash, and filesystem APIs don't well represent access carefully tuned to the needs of flash.  If you do, use a fileystem optimized for flash.  Probably better and simpler though to organize your writes as a linear journal of data.

Could you set up a server with a simple web application, put a WiFi module on the Arduino, and have it store data in a database?  Could use apache or IIS if your on windows.  set it up to run PHP.  Set up a MySQL database.  Have a page that accepts GET variables of the data and insert it into the database.  You could set up another page to access/search/analyze  the data.

@rpmerf I've done this before, but it consumes FAR too much power and I plan to put these small weather data collectors in places away from infrastructure.

Why not use the raw device commands and write blocks? Does your sketch really need a file system, i.e. more than a few files?

There are a few Arduino boards out there that have RTC, SPI Flash and RF-modules, and are real low power design. See for instance Anarduino http://www.anarduino.com/miniwireless/, or Moteino https://lowpowerlab.com/guide/moteino/.

the esp8266 lets you store a few MB as a SPIFFS file system, other boards probably offer the same.

@ChrisStratton do you maybe have a link to how to do it anyways?

@CarrotM An SD card doesn't implement a file system either.  In both case you have to implement the file system in your software on top of the storage device.  The inefficiency in doing so is particularly a bad idea on small devices, but if you really want to do it, the process would be comparable to the filesystem code you would use on top of an SD card.

I2C is common for EEPROM chips and can be accessed with a minimal amount of coding effort using the Wire library.

Have you considered FRAM (Ferroelectric RAM)? It comes in both SPI and I2C formats.  I got my first units from Adafruit. You can read and write as much as you want it has a very long life below 85C. I believe they have some application software on there site.

This lib offers a means of reading and writing ASCII arrays to flash devices. This would be a simple solution for such a data logger requirements. It's ASCII orientated.
https://github.com/schinken/Flash

I don't think you need a file system: that is usually needed when you want to manage many files. Your weather data log sounds like a single file.
What you seem to need is to access EEPROM as a stream, exactly like you would for an open file. There are stream wrappers around some EEPROM libraries, e.g. this one for ESP. I suggest you check it out and see if you can adapt it to the EEPROM library you use.

There is a way to do this. Using a $2 adaptor from eBay, you can hook it up to a micro sd card. An sad card for $4 can store 128mb of data, which is plenty for you.
Arduino Storage Tutorial with weather
128mb Micro Sd card

This does not answer the question which was asked.  The poster already seems familiar with what you propose, and is seeking to do something else.

authors: ศราวุฒิ ยงยืน


text:
Compiling sketch vi command line
Since I don't like the text editor of the Arduino IDE, I decided to write a python script that I can invoke from my text editor to compile and upload my source. I program the popular esp8266 chip. So far I found that there is a python builder here. This did not work for me. So is there any way to compile my source (e.g. main.ino) via a terminal command?

In the Arduino IDE  preferences, select  external editor. Then you can write/ edit your sketches with any editor you choose. When you click compile or upload on the IDE toolbar, it will load your changes each time you compile.

I found a makefile created to compile ESP8266 sketches. You can use this makefile from command line:
cd /path/to/sketch
make -f /path/to/makefile/makeEspArduino.mk upload


text:
LED matrix appears dead
I recently purchased a 1.2 8x8 yellow matrix from Adafruit, along with a HT16K33 backpack for it. I joined the matrix and the backpack, connected everything to the arduino, followed the instructions on the site and got it to work. During animation certain rows would not light up and upon later examination I realized that I had to solder up the pins to the backpack because some pins would not completely make contact with the backpack. After soldering the matrix to the backpack, I fired up arduino and uploaded the matrix8x8 sketch that comes with the library to test the matrix and nothing happens.
I don't have a multimeter yet, but tried to check whether electricity is reaching the backpack which turns out to be true. (used a led and connected it to both + and -, and data and clock pins on the backpack.) in both cases the led lights up.
How can I check the health of the backpack and/or matrix?

Buy a multimeter.  It's the single most essential tool for anyone doing anything with electronics. You cannot exist without one. Go out and buy one immediately. It doesn't have to be an expensive one - as long as it can test voltages and has a diode test (or continuity test 'beep' function) it will suffice.

I hate to say it, but a multimeter would really come in handy for you.  Harbor Freight has some for under $10.
That said, without knowing anything specific about what you are using, you could try using the same LED you used to test power and put it in parallel with one of the LEDs on the matrix.  I'm guessing you don't have power at the LEDs though because it seems unlikely that all the LEDs would fail.  Check your solder work and make sure you have not shorted anything.  Also, you could have overheated a component when soldering causing it to fail.  Good luck.


text:
Graphing force sensor data routed through HX711?
I'm using the code off of the sparkfun website HX711 hookup guide (https://learn.sparkfun.com/tutorials/load-cell-amplifier-hx711-breakout-hookup-guide#arduino-code) to attempt to create a scale.
Currently I have output data of weight in the serial monitor - is there an easy way to then graph this data with regards to time? I've spent an hour fooling around with Processing and googling, but haven't had any luck.
Thanks!

Include the Time library in your sketch, then print the time and your sensor output as a comma separated list. Your output to the serial monitor can then be written to .csv file using PuTTY, which you will need to download in order to collect data (I used online tutorials to figure out writing to a file with PuTTY). Once in a .csv, you can open the file in Excel to graph the data.


text:
Value of joystick reduces when I send it over serial
I've got two arduino cards and two bluetooth bluesmirfs. I am currently trying to read value from a joystick and send it over to the other arduino card and use that value to control my servo motor.
Here's my code.
       //Master Code
void loop()
{
    yVal = analogRead(yAxis);   (value between 0 and 1023)
  if(bluetooth.available())
  {

    bluetooth.print(yVal);
  }
  else if(Serial.available())
  {

    Serial.print(yVal);
  }
  delay(100);
}

//Slave code
void loop(){
  while(Serial.available())
  {

    int c = Serial.read();
    Serial.print("Joystick value: ");
    Serial.println(c);
    int val = map(c, 0, 1023, 0, 255);
    Serial.print("Map value: ");
    Serial.println(val);

      myServo.write(val);
    }
  }

Am I doing something wrong? Instead of getting something between 0 and 1023 I get something below 50.

A fundamental lack of understanding of how serial communications works is what you have.
Serial sends bytes. You are attempting to read an int. The two don't match. Not only that, but you are sending the value as text, not a number, so you're interpreting it as gibberish.
My suggestion: do the map on the master not the slave, and send a raw byte between 0 and 255 not a string of text between "0" and "1023".
bluetooth.write(map(yVal, 0, 1023, 0, 255));

I noticed my mistake right after I posted this, but thank you for clearing some doubts :)


text:
Making the speaker play a certain frequency of sound
I'm trying to make the piezo speaker play a sound of certain frequency. However, although I think the code is fine, the sound plays with a frequency between 130 ~160 only, and the frequency actually drops when it should be going up.
The code is as below:
digitalWrite(buzzer, LOW);
delayMicroseconds(1000000 / frequency);
digitalWrite(buzzer, HIGH);
delayMicroseconds(1);

What could be the problem?

Have you looked at the Tone library?  That does what you want, with some other niceties besides.
Anyway, the (or at least "a") problem with your code is that you are leaving the signal LOW almost all the time. You want it to spend half the time high, half the time low:
digitalWrite(buzzer, LOW);
delayMicroseconds(500000 / frequency);
digitalWrite(buzzer, HIGH);
delayMicroseconds(500000 / frequency);


text:
Playing a pcm file through a speaker with arduino
I'm trying to play an audio file through a speaker with arduino.
However, I do not want to use pre-constructed libraries such as the tmrpcm library.
I was instructed to perhaps even recreate the tmrpcm library, and my process so far is that I managed to extract the data chunk from the wav file in integers, and I also managed to turn the wav file into a pcm file.
I am currently studying http://playground.arduino.cc/Code/PCMAudio this link in order to gain more insight about how I might play the pcm file with the speaker. However, I'm stuck with the general concept of the code. In fact, I'm confused with the general concept of playing the pcm file through the speaker.
In my understanding, playing a music through the speaker works by outputting series of voltages to the speaker, so that the current in accordance with the magnetic field creates an outward force onto the voice coil with a certain frequency that creates the sound.
So my question is, what does the data in the pcm file actually mean? The integers cannot be frequencies, and by graphing it I can see that they are amplitudes in a waveform, but what kind of input they are continues to elude me.
So summing up my questions,

What is the theoretical aspect behind the link :http://playground.arduino.cc/Code/PCMAudio
What does the data in a pcm file (or even a wav file) actually represent?

Thank you so much.

Perhaps google for pcm to pwm

I read the entire first page of google on pcm to pwm, but I couldn't find a breakthrough. What would you suggest I look at closely from the google results?

I doubt there's any "breakthrough" information out there; but look up 1-bit delta-sigma DACs, because unless you attach a DAC or use a Due or Teensy 3, you'll be using 1 bit (toggled as needed) plus a low pass filter to generate your waveforms.  Also consider a simple-minded protocol where you use a fast-clocked ADC to read back output from low pass filter, turning a bit on when voltage should go up, or off when it should go down

You are right that the values in a wav file are amplitudes. 16 bit signed values to be precise.
And that amplitude is just a voltage. Negative values are normally a negative voltage, but they don't have to be. They can be just a voltage below a pre-determined mid voltage around which the wave swings (known as a DC offset).
To play the waveform you just have to generate the corresponding voltages at the right times. That is usually done using a timer so you get the frequency right. For instance a 44100Hz file has to have a sample voltage generated 44100 times per second. 44100 samples will be a sound clip lasting 1 second.
But of course the Arduino cannot generate a voltage, so instead PWM is used instead. Filtered through a low-pass filter it turns into a voltage. It also uses 50% duty cycle as "zero" for the waveform, which is scaled to fit into the resolution of the PWM.  The PWM has to be running at a considerably higher frequency than the sample frequency of the waveform so it has a chance to represent a voltage before it is asked to change again.

curious: would a DC offset harm speaker coils or lower output potential? Are arduinos fast enough to dither audio frequencies using PWM? thanks!

It can cause some distortion if the coil movement reaches its limit due to a magnetic offset. It also causes heating in the coil. You would normally remove the DC offset by passing it through a capacitor. And yes, the Arduino is fast enough for crude audio. Not wonderful, but tolerable for small projects.

For anything better you want a 32 bit chip and I2S.

@Majenko in case the wav file is 8bit and sampled at 33100Hz, then the wav file will contain the amplitudes(1 byte correspond to 1 amplitude level) to be sent out to the DAC every 1/44100 seconds. Please correct me if i am wrong.

That is correct, though it is very rare to find an 8-bit WAV file.

authors: Александр Ушаков


text:
how to drive 500W of leds
I am currently developing a project that needs 9 led stripes, each led stripe has 5 meters, 300 leds, it consumes 60W per stripe in a total of 540W...
This are the led stripes - 5M 12W/M 24V SMD 2835
This led stripes use a 24V power supply.
The thing is I want to drive them with an arduino and PWM. What would I need to do it. I was looking for something like CAT4101 but I never dealt with so much power before and I would like your advice.
Thanks

The led strips will have their own current limiting / drivers. A couple of quick calculations:

24V at 12W is (I=P/V) 12/24 = 0.5A per meter
5 meters = 0.5*5 = 2.5A

So each strip takes 2.5A. The CAT4101 is a 1A max driver, but since it is a constant current driver it's not suitable for a strip that has its own current control built in.
I suspect each meter consists of 10 chains of 6 LEDs with a current limiting resistor or two. Out of interest, calculations:

6 LEDs at (say) 3V forward voltage would be 18V.
24 - 18 = 6 volts to drop
500mA divided by 10 chains = 50mA
R=V/I = 6 / 0.05 = 120Ω current limiting resistors.
P=I²R = 0.05²×6 = 300mW dissipated from the resistors.

Instead all you need is an N-channel MOSFET as a low-side switch that can operate with that much current and not dissipate too much heat while switching. The more you derate the MOSFET the less heatsinking it would need.
A quick look on Digikey gave a possible match of PSMN022-30PL - 30V, 30A, 27mΩ (typ) at 4.5V gate voltage.

simulate this circuit – Schematic created using CircuitLab

And I would need one of those for each led stripe? What if I get a 600W power supply? I don't think that the leds have drivers at all? I was thinking on direct power supply connection.... I guess that would be mistake right?

Ideally, yes - spread the load nicely. However one, with proper heat sinking, should be able to do all of them together (22.5A) at a pinch.

sorry I edited the question: What if I get a 600W power supply? I don't think that the leds have drivers at all? I was thinking on direct power supply connection.... I guess that would be mistake right?

Do you have a link to the LED strips?

it's in portuguese, but google translate should handle it:

https://goo.gl/qXX2IQ

Yes, it has current limiting resistors. You can see them between every three LEDs. They have most likely split the resistance across a couple of resistors to spread the dissipation, so they can use smaller resistors. So direct supply connection and a MOSFET to switch them is fine.

And yes, as I thought - you can tell by the cut points (where the metal pads are) that they are parallel chains of 6 LEDs.

Let us continue this discussion in chat.

authors: Дмитро Корпильов


text:
float not a float
I am trying to read a SDM220 meter on my solar setup. I've been reading it using Modbus SCADA, so know it all works ok.
But I want to read it with my Arduino Mega 256. My problem is that when I run the code below the final value MtrKWh , is not float value. it's actual value is printed.
Here is a copy of the output.
17241 MtrKWh1 1129906176 MtrKWh1<<16 57737 MtrKWh2 1129963913 MtrKWh3 11299639.00 MtrKWh 2
the value '1129963913'       MtrKWh3,
if I turn it into Binary is
01000011010110011110000110001001,
if I convert this to binary using https://www.h-schmidt.net/FloatConverter/
it gives me the value
217.881,
the very value I expect. Am I missing some brackets somewhere?
So how do I get MtrKWh to print its float value?
I have left a lot of commented out bits to show the several things I have tried. Sorry if it appears messy, I will tidy it up once I solve this problem.
I'm sure it is something simple, but, I haven't been able to see it so far.
Any sugestions would be appreciated.
    // MtrV, MtrC, MtrW, MtrKWh
    //void AddressRegistry_0()
    result = sdm220_modbus.readInputRegisters(0x48, 2);
    //while (!result == 0) {
    // delay(10);
    // result = sdm220_modbus.readInputRegisters(0x156,4);
    //}
   if (result == sdm220_modbus.ku8MBSuccess)
   {
    // 1 Serial.println((node.getResponseBuffer(0x0D) + node.getResponseBuffer(0x0E) << 16)/100.0f);
    // 2 pvpower = ((long)node.getResponseBuffer(0x03) << 16 | node.getResponseBuffer(0x02)) / 100.0f;
    // 3 long pressure = ((pressure_data_high << 16) | pressure_data_low) / 4;
    // 1 working ?? MtrKWh1 = (((long)sdm220_modbus.getResponseBuffer(0x0) + sdm220_modbus.getResponseBuffer(0x1) << 16)/6.f);
    // 2 working ?? MtrKWh1 = ((long)sdm220_modbus.getResponseBuffer(0x0) << 16 | sdm220_modbus.getResponseBuffer(0x1)) / 100.3f;
    // 3 working MtrKWh1 = (( sdm220_modbus.getResponseBuffer(0x0)  << 16) |  sdm220_modbus.getResponseBuffer(0x1))  / 16.3f;
    //
   // float MtrKWh0 =((float)(sdm220_modbus.getResponseBuffer( 0) << 16 | sdm220_modbus.getResponseBuffer( 1)));
    //      Serial.print(MtrKWh0);
    //    Serial.print(" MtrKWh0     ");

signed long MtrKWh1 = sdm220_modbus.getResponseBuffer(0x0);
Serial.print(" ");
Serial.print(MtrKWh1);
Serial.print(" MtrKWh1");

MtrKWh1 = MtrKWh1 << 16;
Serial.print(" ");
Serial.print(MtrKWh1);
Serial.print(" MtrKWh1<<16");

word MtrKWh2 = sdm220_modbus.getResponseBuffer(0x1);
Serial.print(" ");
Serial.print(MtrKWh2);
Serial.print(" MtrKWh2");

signed long MtrKWh3 = MtrKWh1 | MtrKWh2;
Serial.print(" ");
Serial.print(MtrKWh3);
Serial.print(" MtrKWh3");

float (MtrKWh) = float (MtrKWh3) / 10000.0;
Serial.print(" ");
Serial.print(MtrKWh);
Serial.print(" MtrKWh     ");

//uint32_t x = 0x3f322e3f;
//float y = *(float*)&x;
//Serial.print (y, 6);
// Serial.print(" MtrKWhxxx ");

   }
   else
   {
    rs485DataReceived = false;
    Serial.println("Fail sdm220_modbus.readInputRegisters(0x0, 1) ");
   }

You have your answer commented out in the source code. Conversion of type using pointers, not casting.

Or you could use reinterpret_cast if the compiler supports it - I've never tried.

Casting will convert an integer into a float with the same numeric value (1000 => 1000.000). Instead what is wanted is the overlaying of a float's structure on the memory of the integer value, which is what the nasty type-punning in the commented section is doing. Personally I'd use a union to overlay a 4-byte array over a float.

@majenko reinterpret_cast does exactly that. I think it's a C++11 thing though, and I don't know whether the Arduino compiler supports it.

I put this
reinterpret_cast(MtrKWh)
in the code, i get error during complie
invalid cast from type 'long int' to type 'float'
I thought that was he point of reinterpret_cast, to change type?
Have I got the syntax right?
signed long (MtrKWh) = float (MtrKWh3) / 10000.0;
Serial.print(" ");
Serial.print(MtrKWh);
reinterpret_cast<float>(MtrKWh);
Serial.print("   MtrKWh     ");

You need to convert the format by overlaying one type on top of the other, rather than casting from one type to another.
1000 as an integer cast to a floating point value is still 1000.
You have an example of how it can be done in comments:
//float y = *(float*)&x;

However this method is called type punning and is frowned upon (there are compiler options that can prevent it being used).  Instead using a union is a better option:
union ifloat {
    uint8_t bytes[4];
    float val;
};

void setup() {
    ifloat f;
    Serial.begin(115200);
    f.bytes[3] = 0x43;
    f.bytes[2] = 0x59;
    f.bytes[1] = 0xE1;
    f.bytes[0] = 0x89;
    Serial.println(f.val, 4);

}

void loop() {
}

So you can get the byte order right your current numeric value of 1129963913 is 0x4359E189 in hexadecimal. Byte 3 is therefore the most significant byte and byte 0 the least significant. Note that it can change from system to system depending on the endianness of the chip.
How it works is quite simple. You have 4 bytes in memory, and the union just gives you different views of those 4 bytes.
You can either see them as four individual bytes (f.bytes[0-3]) or as a floating point value (f.val).
You can understand more about how the four bytes describe the floating point number by understanding more about the IEEE 754 Single Precision Floating Point Format.

You can achieve the same thing using reinterpret_cast, but that has to be done using pointers, not the values, which makes it a little more complex to understand:
// Your incoming 32-bit value
uint32_t l = 1129963913;

// A pointer to the same memory with a different type
float *f = reinterpret_cast<float *>(&l);

// Print the *content* of the pointer interpreted as a float.
Serial.println(*f, 3);

Thanks for response. I think I saw a similar solution on my searches earlier. I found it difficult to understand/impliment. I have 2 words, MtrWhr1 and MtrWh2, do I need to convert these two words to bytes, then to hex, then use the code above to get the float conversion?

OK. So I never got the reinterpret_cast, thing to work. Went with Majenko's solution.
This code goes above Setup
// UNION, used to re-jig float
union ifloat {
uint8_t bytes[4];
float val;
};
// END UNION

And this is the modified code, with all the comments and bug print statements removed.
  // MtrV, MtrC, MtrW, MtrKWh
 //void AddressRegistry_0()
 result = sdm220_modbus.readInputRegisters(0x48, 2);
 if (result == sdm220_modbus.ku8MBSuccess)
 {
signed long MtrKWh1 = sdm220_modbus.getResponseBuffer(0x0);
word MtrKWh2 = sdm220_modbus.getResponseBuffer(0x1);
byte msb3 = MtrKWh1;
byte msb4 = MtrKWh1 >> 8;
byte msb1 = MtrKWh2;
byte msb2 = MtrKWh2 >> 8;
ifloat f;
f.bytes[3] = msb4;
f.bytes[2] = msb3;
f.bytes[1] = msb2;
f.bytes[0] = msb1;
Serial.println(f.val,3 );
  }
 else
 {
rs485DataReceived = false;
Serial.println("Fail sdm220_modbus.readInputRegisters(0x0, 1) ");
 }

And it is giving me the right numbers!
Thanks for input to all who did, it helps some times to be show which door to walk through.
Majenko, if you have time, and inclination, it would really help my understanding if you could describe your code. I am using it, but not sure how it works,or what most of it is doing. If you have the time.

Description added to my answer.

authors: Олег Бартенев

authors: Павел Гречка


text:
Using external reset to trigger radio receipt
I am designing a low-power RF application using an ATTiny (Adafruit Trinket).
When the system receives a radio signal, it needs to read some sensors, and transmit with that data. Because I am short on pins, I am trying to think of creative (low-pin count) ways to design this system.
My current idea is:

Put the AVR to sleep.
Connect the radio's Rx Interrupt pin to the AVR Reset pin
When the AVR is reset, check the radio buffer

(if there's nothing in the buffer, assume this is a real power-on reset and go back to sleep)

Otherwise, read sensors, transmit
Go back to sleep

My aim here is that the AVR will use very little power while sleeping (furthermore, it will only need to wake up a few times per day).
Is it reasonable to use the AVR reset pin in this manner? Any gotchas to be aware of?

No gotchas I can think of, except for the fact that the ATtiny's memory
will be re-initialized every time you reset it. But I assume you are
aware of that.
Note that, if you want some data to be preserved across a reset, it is
possible using either the on-chip EEPROM or the .noinit
section of the RAM.

You can also use the EEARL and EEARH registers to store 2 bytes between resets, as those retain their value between resets. This behavior however isn't specified in the datasheet, so not really advised for critical/professional  applications.


text:
Passing a reference as a variable
I have a function for manually jogging a stepper motor using the AccelStepper library. At the beginning of the function I would like the motor in question to be selected until told to stop.
Here is what I imagine it would look like:
AccelStepper X_Axis(AccelStepper::DRIVER, 3, 2);
AccelStepper Y_Axis(AccelStepper::DRIVER, 5, 4);
AccelStepper Z_Axis(AccelStepper::DRIVER, 7, 6);

void ManualJog(int Dir, int Spd, int axis)
{
  int i;
  if (Dir == 0){i = 1;}else{i =- 1;}
  setSpeed(i * Spd);
  switch(axis)
    {
      case 1:
      axis = X_Axis;
      break;

      case 2:
      axis = Y_Axis;

      case 3:
      axis = Z_Axis
    }
  while (!Serial.available()){

      axis.runSpeed();
    }
  }

The axis variable should map to whichever axis is called and so control the desired stepper.
How can I achieve this?
Note: I submitted this to StackOverflow with no response. Any help would be appreciated

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

How about using an array?
const int x = 0;
const int y = 1;
const int z = 2;

AccelStepper axis[] = { {AccelStepper::DRIVER, 3, 2}, ... };

void ManualJog(int Dir, int Spd, int axisIdx)
{
   axis[axisIdx].runSpeed();
}

To do it in the form you have, you would want to use a pointer.
void ManualJog(int Dir, int Spd, int axis)
{
  int i;
  AccellStepper *thisAxis = NULL;

  if (Dir == 0) {
    i = 1;
  } else {
    i =- 1;
  }
  setSpeed(i * Spd);
  switch(axis)
  {
    case 1:
      thisAxis = &X_Axis;
      break;

    case 2:
      thisAxis = &Y_Axis;
      break;

    case 3:
      thisAxis = &Z_Axis
      break
  }

  if (thisAxis != NULL) {
    while (!Serial.available()) {
      thisAxis->runSpeed();
    }
  }
}

Briefly: the & before the name of a variable in assignment means "Give me the address of this variable".  A * before a variable when declaring that variable means "Make this variable hold the address of another variable of this type".  You then have the address variable hold the address of your chosen axel, and then "dereference" that with the "poiner dereference operator" -> (instead of using .).
A check is added to see if thisAxis has actually been assigned anything or not, although you could use the default: case in your switch to abort on an invalid axis number instead.
Depending on how the rest of your program works, though, it may be possible to not use the "axis" integer at all, but pass a reference to the correct stepper to the function:
void ManualJog(int Dir, int Spd, AccelStepper &axis) {
  int i;
  if (Dir == 0) {
    i = 1;
  } else {
    i =- 1;
  }
  setSpeed(i * Spd);
  while (!Serial.available()) {
    axis.runSpeed();
  }
}

In this example the & before the axis variable in the function prototype means "Pass me the address of the variable", and a new variable is created located in the same memory space. This is the pass by reference operator in C++.

I very much don't like using "magical numbers" to select the axis. It would be much nicer (and faster) not to pass int axis into ManualJog method, but pass a reference to AccellStepper so the code is more readable.

@FilipFranik I agree wholeheartedly - however judging by the way the question is worded, and how the function looks like it's meant to work, at some point the correct axis is going to have to be "selected", and that will probably mean setting a pointer at some point in the sequence.

Brilliant, thank you for this. Pointers are something I have not dealt with before. you are correct in that i wish to select the reference of the motor depending on the input. I will give this a go and respond with my working code.


text:
Arduino Clock Speed effect on Stepper Speed
I am running a Pololu A4988 Stepper driver with two (soon to be three) steppers using the AccelStepper library. I have wired 1/8th microstepping on both as smooth running is important.
The motors run fine however, when running simultaneously, if Stepper 1 finishes its move before the Stepper 2, there is a marked increase in speed in the Stepper 2 (evident audibly and visually).
The code I use to run the motors is:
void MoveAccelXY(int Xm, int Ym) // function 6
{
  X_Axis.moveTo(Xm);
  Y_Axis.moveTo(Ym);
  while(X_Axis.distanceToGo() !=0 || Y_Axis.distanceToGo() !=0)
  {
    X_Axis.run();
    Y_Axis.run();
  }
  Xpos = X_Axis.currentPosition();
  Ypos = Y_Axis.currentPosition();
  Serial.print("X" + Xpos);
  delay(50);
  Serial.print("Y" + Ypos);
  delay(50);
  Serial.print("C");
}

I would like there to be no speed drop on any steppers. Increasing the input voltage does not have an effect.
Is the Arduino clock speed the culprit?

Do you set the maximum speed with setMaxSpeed() ?

Without seeing the rest of your code, the best guess - and I think it is quite likely - is the use of delay() and printing within the stepper function. With 2 motors running, and even ignoring the printing time, there will be a total of 200ms taken up by the delays. That means each motor gets serviced a maximum of 5x/sec. Stop one motor, and the other one can double that to 10x/sec.
Look at the Blink Without Delay example for one way of managing timed events without calling delay(). The SimpleTimer library provides another.
Update:

...run() events are triggered within a while() loop ...

Ah, yes, I see that. So it looks like only one motor could run at a time - the while() loop runs until this motor reaches its target. But you said you run two at a time. So yes, I think understanding the rest of the code will help.

This seems most likely. See the documentation for run() https://www.airspayce.com/mikem/arduino/AccelStepper/classAccelStepper.html#a608b2395b64ac15451d16d0371fe13ce

Thanks for the feedback. The function itself is called from the void loop() function when the correct format of bytes is received through the serial port. The actual run() events are triggered within a while() loop so the delay functions only trigger after the motors have moved. I can post the rest of my code if you think this will help?

@MJ2507 You may have the max speed (max steps/second) set too high. If it is too high it will be limited by the MCU clock speed. You can try reducing the max speed until the second motor doesn't speed up after the first stops.

Why would the clockspeed change when driving multiple motors at the same time?
How do you power the motors and Arduino?
I suspect that your power supply is the problem.
Running 2 motors likely doubles the current consumption. Try to measure the input voltage, does it drop when driving both motors?
You should check the current your motors can consume and compare with what your power supply may provide. (Also keep the 1A limit of the driver in mind)

I don't think this would be an issue with stepper motors. Since they move a fixed distance with every step they should only move as fast as the pulses arrive from the arduino.

it is powered by a 30V 2A DC power supply. There are no noticeable voltage drops when it is run. The maximum current of each stepper is 1A but i think both together I don't see anything higher than 1A total (running at around 12V).


text:
I am not able to compile,libraries missing
this was the error  message
Arduino: 1.6.7 (Windows 7), Board: "Arduino/Genuino Uno"
Sketch uses 1,068 bytes (3%) of program storage space. Maximum is 32,256 bytes.
Global variables use 11 bytes (0%) of dynamic memory, leaving 2,037 bytes for local variables. Maximum is 2,048 bytes.
avrdude: ser_open(): can't open device "\.\COM17": The semaphore timeout period has expired.
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.
Invalid library found in C:\Users\nehal\Documents\Arduino\libraries\leddelay: C:\Users\nehal\Documents\Arduino\libraries\leddelay
Invalid library found in C:\Users\nehal\Documents\Arduino\libraries\sketch_jan16c: C:\Users\nehal\Documents\Arduino\libraries\sketch_jan16c
Invalid library found in C:\Users\nehal\Documents\Arduino\libraries\leddelay: C:\Users\nehal\Documents\Arduino\libraries\leddelay
Invalid library found in C:\Users\nehal\Documents\Arduino\libraries\sketch_jan16c: C:\Users\nehal\Documents\Arduino\libraries\sketch_jan16c
This report would have more information with
  "Show verbose output during compilation"
  enabled in File > Preferences.
 What should I do?

You have two distinct issues here, one critical and one probably annoyance-level.  The critical one is that your chosen serial port is not available - maybe the board moved, or something else is trying to talk to it.  Separately, you seem to have some garbage in the libraries folder, maybe a sketch inappropriately saved there.   The IDE is complaining about that, but not refusing to compile on account of it in the way your title implies - you do not actually have a compile error.


text:
Arduino/Genuino not in board list
I've downloaded the Arduino IDE and the Genuino isn't in the list of boards. I'm running Rasbian and used the command line to install.

Which version of the IDE? A lot of Arduino boards are branded Genuino (after the fiasco of the dispute over the "Arduino" name). It could be a Genuino Uno, or Genuino Nano, or whatever.

"Genuino" is just a name, not an identifier. Pick the equivalent Arduino board from the list.


text:
Router with arduino
Is it possible to send and receive data from a normal router using arduino? I need to create a little device that uses a router to communicate with a remote. It's a close circuit.

Please read How do I ask a good question?

If you have a network interface (wired or wireless), yes, of course it is.
Look into the ESP8266, and ESP-12E-based boards such as the Adafruit Huzzah; they can be programmed in an Arduino environment, and have built-in wifi.

I need a normal router. Like the one you would you at home but a lot more powerful.

How powerful your router is is irrelevant. The problem is connecting to the Arduino. The standard boards don't have a network interface; you need an ethernet or wireless shield for that, but there are arduino-compatible boards, usually based on the ESP8266, that have built-in wifi.

So I can do it, directly or not!

Yes ,You CAN.
Use ESP 8266-07.Its a very good Wi-Fi module.You juts need to install ESP8266 board file in Arduno IDE.
For board file installation and some basic tutorial , just
Click here
Its helpful I think.


text:
Motor control using arduino board
I want to control 2 dc motors using the arduino board directly. One motor must rotate clockwise and the other counter clockwise. The directions  doesn't change only the speed of each motors. Can this be done without any shield? Them motors may need a higher voltage than the arduino can provide. If I link the arduino board to a power source of about 15 V (the board is arduino mega limits between 6 and 20 ) and I use "analog.write()" function can I output more than 5 volts(the internal voltage)?

If you post a link to the motors you are intending to drive, you might get an even simpler solution. We need to know both the voltage and the current, preferably from the motor's datasheet.

Simplest way to do this is two MOSFETs (one per motor, because you don't need to change direction), and some miscellaneous passives, and a flyback diode for each motor.
See this tutorial for wiring diagrams and details.

Great link! You saved me! But I still don't get it. What's the difference between a mosfet and a transistor? I searcher a few more pages and they said a mosfet is a transistor. Does any transistor work?

A MOSFET is a type of transistor. BJTs (bipolar junction transistors) are the other dominant type of transistor, and are not as appropriate for this application. The difference between MOSFETs and BJTs is too much to discuss here, but as far as what you should use: use a logic-level MOSFET (low Vgs(on))

@uint128_t it is syaing that link does not exist


text:
80 Apple Homebuttons and a steppermotor
I am graduating in a month and I want to make an installation with 80 apple homebuttons which are connected to a stepper motor. The idea is that each button that is pressed, turns the stepper motor the same amount of degrees each time. Also, each button is connected to an LED which must stay on, even if the button is pressed again and the motor too must not react. Once all 80 buttons have been pressed, the installation should switch off after a minute or so.
I am not sure how to connect 80 inputs to the arduino. Does anyone have any idea?

Start small and figure out exactly what your program should do.  Most keyboards (and comparable devices) with more than a few keys use matrix scanning, which need not match their physical layout.

Why on earth would you use an Apple homebutton? That'll become unnecessary expensive. All the LED's should be controlled at the same time? Or should it be possible to control them individually?

There are input shift registers, however I have no idea what an "apple homebutton" is. I'm going to close this question. Feel free to edit it with new information. Thanks for your understanding and cooperation!

Why Apple home buttons?
Finding out how to get input/output from these things and wiring them in a reliable way may cost you some time (and quite some money).
I don't see how they would have other features than regular buttons.
(You won't get the fingerprint-scanning thing working, I'm afraid.)
Start small
It'll be quite a project to do in one month (especially when you're new to Arduino).
If you start out with 80 buttons and stuff, it will probably end up in a mess, and you'll be unable to show your prof anything.
You should however, order the 80 push-buttons (I shouldn't order the Apple ones, if you don't already know how they work) and LED's. Since they might take some shipping time.
Get yourself a solder-less breadboard, maybe 3 buttons, some LED's and a stepper (if you don't have one already).
Depending on your type of stepper, you may need something to drive it.
Start project
Use two buttons or so, if you press one, it would go clockwise, if you press the other, it would go counter clockwise.
Make sure you pull up or down the button inputs, to be sure that they are not floating when the button is not pressed.
Find a way to drive the steppers, you'll most likely use Arduino libraries for this.
Code will be something like:
if(digitalRead(button1))
  stepper.step(steps++);
if(digitalRead(button2))
  stepper.step(steps--);

Scaling up - alternative
You could use the 80 buttons for each angle of the stepper.
But you could also use a keypad and LCD (or 3x 7segment display) to display a value typed in, and then send it to the motor.
Scaling up
In the case of the 80 buttons.
You could use 10 outputs in combination with 8 inputs.
With each output, you can energize a row of buttons, and with each input you read the columns. This way you only need 18 pins to read all keys.
I'm not sure if you want to control all LED's at the same time, or individually.
Or use shift registers or I/O expanders (JayEye).

Hi Paul. I will only be using the glass top of the buttons! These have a plate which you can click on top of an Arduino button. I am not using the iPhone 6 buttons with the Touch Id, but just want them for aesthetic reasons. Thanks so much for the advice!

Ah, good, I guess, as long as it's not making your project too expensive or too difficult ;) but I think you'll manage that. Do you still have any questions/doubts?

You see I wasn't sure whether a Raspberry Pi or an Arduino would be the best option. Now I guess my best option is to go with the Rasperry. I wanted to know where to start and then I can always find ways to get where I want to be, but as you say yourself - I don't want it to become expensive, so I need all the help I can get. I will definitely be back with further questions once I have the right equipment. Thanks so much!

Paul, jij zit gewoon op de HAN! Ik op ArtEZ

@MissySkae (Klopt ;) )
Hmm, About the Raspberry Pi, there is no actual need to make it any more complicated than it is. You can, however, use processing on the Raspberry Pi to control the GPIO pins of the raspberry. You could even make a fancy "Graphical user interface", since a Raspberry has HDMI output. If you're familiar with the Raspberry Pi, then why not, if you're not familiar, you'll need to learn a new "trick" which is a good thing, but you're really going to have to look at whatever time you have left.

@MissySkae, I've you have some buttons, stepper and an Arduino, you should just really try to get something basic working. From that you can expand to something more complicated.
If you start out with thinking about something complicated, and try to do it all at once, you might not even get started at all (since you know, you might just as well use a xbox controller to move the stepper? xD). I might do some tests when I'm home, but I'm not sure since I'm pretty busy with my internship.

If you follow JayEye's approach (ie, use five MCP23017 units to connect 80 switches, and five more to connect 80 LEDs) the wiring and the software should be fairly simple.  But dealing with all the wires will be a problem unless you use a custom printed circuit board to mount all the switches, LEDs, wiring traces, and connectors.  If you have experience with and hands-on access to printed circuit manufacturing equipment, and fast access to the parts you need, that approach should be ok.
A worthwhile alternative is to scale the project back slightly – say to 64 switches and LEDs instead of 80 – and use two Arduino Mega2650's, one to connect to switches, and another to connect to LEDs.  Or you could use one Mega to handle the first 32 switch-and-LED pairs, and another, identically-wired, to handle the other 32.  The two Mega's could communicate by I²C or via RxD-TxD connections (Arduino Mega's have four hardware serials ports, IIRC).  If you plan to wire stuff up with jumpers and breadboards, this probably would be among the simpler, faster, and cheaper approaches.  The modularity of building two identical units (except that only one of them will have the stepper driver attached) improves reliability and ease of debugging.  You could also use four or five identically-wired Uno or Nano boards.
Note, however, that you are likely to have serious reliability problems if you connect up 80 switches and 80 LEDs via breadboards and jumper wires.   As Chris Stratton suggested, start small.  For example, wire up a dozen or two dozen switches and LEDs on a single Mega.  This will let you see how much of a mess the wiring will be, and whether the original scale is practical.  It will also allow tracking down software bugs on a hardware system that is small enough to allow some confidence that the hardware is working.  If you build an 80-unit system before debugging the software, you are likely to run into problems where hours or days go by while you try to sort out whether the problem is due to a software error, a wiring error, or some combination of both.
Note that use of Charlieplexed connections or matrix connections would let you get by with about 10-20% as many IO lines as the direct-connect methods listed above.  However, unless you have used Charlieplexed or multiplexed LED displays and matrix-connected switches successfully in previous projects, and have experience with building and driving circuit boards, the likelihood of getting the project done on time is rather lower than for the other methods mentioned above.

Thanks! I am well aware that it is a lot. There is expertise at school to help out, I just wondered what the options are. I have already made a circuit with one home button, an LED and a 9v battery. I am going to make my own custom circuits and solder everything together, so that has been thought about. Thanks so much for helping me!

Sure.  Note, please upvote any of these answers that you find useful.

I have no idea what an apple homebutton is, but the easiest way to add more GPIO pins is to use something like an MCP23017; it connects over I2C and gives you 16 GPIO pins. Use five of them and you have your solution.

Why not shift registers? :
But the MCP23017 is indeed a viable/nice solution.

Thanks! I will definitely try this out! The home button is the button which belongs to the iPhone. I have made a simple circuit with on button, an LED and a 9v battery and that works perfectly, so now I just need 80 buttons which send a signal to the Arduino and the stepper.


text:
Can I switch a pulse solenoid from the onboard 5V/3.3V power source?
I have two pulse solenoids.  One is 6V...
http://www.ebay.com.au/itm/282002733837?_trksid=p2057872.m2749.l2649&ssPageName=STRK%3AMEBIDX%3AIT
and the other is 3.6V...
http://www.ebay.com.au/itm/131989042565?_trksid=p2057872.m2749.l2649&ssPageName=STRK%3AMEBIDX%3AIT
I have a Wemos R2 Mini with an ESP8266 chip on it, and I'm running the switching operation through a H Bridge motor shield (which handily switches the polarity of the electricity for a short time, which opens/shuts the solenoid).
I want to run this thing off a smallish battery pack that will supply 5V to the WeMos. I have three questions:
1) Can I send a 3.6V solenoid a 60ms pulse to open/shut it from a 5V power source without burning out the coil or causing any other damage?
2) Is 3.3V too low to power a 3.6V solenoid?
3) Do pulse solenoids still generate back EMF?
I don't know a lot about solenoids or electromagnetic fields so, sorry if my questions are noobish.

They seem more concerned with how beautiful it is than providing a datasheet with real information in it. You buy lemons, expect to make lemonade, not a cream cake.

@Majenko to be fair, it is quite beautiful :D.  I know there is no datasheet/no nothing but for $8 I was happy to give it a crack.  The weird thing is that the design of both solenoids is very solid, and they tested as working when I gave them a go. But yeah, no datasheet.

1) Can I send a 3.6V solenoid a 60ms pulse to open/shut it from a 5V
  power source without burning out the coil or causing any other damage?

No. If it's 3.6V then you need 3.6V - 5V will most likely make it smoke. Use a regulator (preferably a buck one, since it is apparently 500mA) to power your H-bridge.

2) Is 3.3V too low to power a 3.6V solenoid?

Maybe, maybe not. It may be that 3.6V is the absolute maximum and may switch from 3V to 3.6V.

3) Do pulse solenoids still generate back EMF?

Normally, yes, since they are just a coil like any other inductive load. Your H-bridge should deal with that though if designed right.
To get any meaningful answers you will need a datasheet. Buying such things from eBay is never a good idea unless you have used it before and know what it is, what its specifications are, and how you use it, or they provide a link to a datasheet. Without a datasheet most questions will be answered with a "maybe".


text:
C++ Namespace/scope problem when trying to attach arduino interrupt
I have defined a c++ class (RpmDriver) and want to use attachInterrupt in the constructor to link an Arduino pin to its ISR (RpmInt) in the class. When I try this, I get:
error: cannot convert 'RpmDriver::RPMInt' from type 'void (RpmDriver::)()' to type 'void (*)()'
This is the cpp file:
#include "RpmDriver.h"
#include <Arduino.h>
int currentRpm;
long lastMillis;
int pin;

RpmDriver::RpmDriver(int Pins[])
{
    pin=Pins[0];
    currentRpm=0;
    pinMode(pin,INPUT);
    lastMillis = millis();
    attachInterrupt(digitalPinToInterrupt(pin),RPMInt, RISING);
}
RpmDriver::~RpmDriver(void)
{}

bool RpmDriver::GetData(char* dest,char* format)
{
    sprintf(dest,format,currentRpm);
}

void RpmDriver::RPMInt()
{
    double RPMConstant=40000;
    unsigned long newMillis=millis();
    unsigned long t = newMillis-lastMillis;
    t=100;//temp
    currentRpm=(t==0)?0:(int)RPMConstant/t;
    lastMillis=newMillis;
}

and the header file is
#pragma once
class RpmDriver
{
public:
    RpmDriver(int pins[]);
    ~RpmDriver(void);
    bool GetData(char*,char*);
private:
    void RPMInt(void);
};

Any help much appreciated!

See my post Calling an ISR from a class

You can't.
Simply because a class member is not the right format of function for attachInterrupt.
You can only use normal functions with attachInterrupt, so the normal method is to have a normal function outside your class which then calls the member function within your class.  How you arrange it so that it knows where your objects are is up to you.

If you have only one object then assign it to a global pointer in your library using the constructor
If you have lots of instances then create a linked list within your class in a static context and add each object to it in the constructor, then iterate through that list when the interrupt fires.

You should qualify RpmDriver::RPMInt() as static.
Static member functions are very much like plain functions, only using
their class as a sort of namespace. Obviously, you will not be able to
access any member data, but this should not be a problem as it seems
your class is not storing any data anyway.


text:
Connecting two arduinos using WiFi
I have two arduinos (An UNO R3 and a Mega 2560), and I need to communicate them via two ESP8266 modules to exchange some values.
In one arduino I'll use a SW-420 vibrarion module, and I need to send a value wirelessly to the other board, which it'll have an LCD screen that will display a message when a value is recieved.
How can I do that with that specific WiFi modules? Thanks in advance

You could have them both communicate with the same WiFi AP, or you could set one to be in SoftAP mode and connect the other to it. The choice is yours.

@Majenko The second option looks way more attractive to me, can you share a tutorial of how to do it? Thanks.

No, I can't. I never use the modules connected to an Arduino - I program them direct.

Step 1: I would load NodeMCU on you ESP8266: https://github.com/nodemcu/nodemcu-firmware
Step 2: Connect to your home router or make an ap on one of your ESP and connect them... use the api: https://github.com/nodemcu/nodemcu-firmware/wiki/nodemcu_api_en over serial connection
Step 3: write a TCP server:
srv=net.createServer(net.TCP)
srv:listen(80,function(conn)
  conn:on("receive",function(conn,payload)
    print(payload) //This payload will be send to your arduino over soft serial
    conn:send("<h1> Hello, NodeMCU!!! </h1>")
  end)
  conn:on("sent",function(conn) conn:close() end)
end)

Step 4: write a TCP client:
suc = false;
function sendData( host, pathData )
    suc = false;
    print("GoSending!");
    -- A simple http client
    conn=net.createConnection(net.TCP, 0)
    conn:on("receive", function(conn, payload)
        if(string.find(payload, "200 OK")~=nil) then
            suc = true;
            print("AllDone")
        else
            suc = false;
        end
    end)
    conn:on("connection", function(c)
        print("connected");
        conn:send("GET /".. pathData .." HTTP/1.1\r\nHost: ".. host .."\r\n"
            .."Connection: keep-alive\r\nAccept: */*\r\n\r\n")
        end)
    conn:on("disconnection", function()
        if(suc==false) then
            print("ErrorSending")
        end
    end)
    conn:on("reconnection", function() print("reconnection") end )
    conn:connect(80,host)
end

Step 5: Connect your esp boards with software serial to the arduino
Step 6: write (from board 1) to softserial to esp1: sendData( hostIP, yourData)
Step: 7 Parse the Data on sofserial read on the second arduino
Step 8: DONE!
EDIT:
Ok more infos on step 6.
If you got your script running on your esp, you can call functions by sending the function name with parameters over your serial connection.
So, this is some example code for your ardoino if you got the script from above:
SoftwareSerial wifi(3, 2); // RX, TX

//at some time in your programm
//Build up your string that will be send over serial
String i1 = "sendData(\"ipFromTheServer\", \"send.php?d=";
String i2 = i1+dataToSend;
String i3 = i2 +"\");";
wifi.println(i3);

This will call the sendData function on you esp. this will call the send.php on a Server... you can put a server up on an other esp and call it (dont have to be a php page)
More infos on step 7.
the script on top will always print all incoming data. So you just have to read serial data on wifi:
if (wifi.available())
    Serial.write(wifi.read()); //this will print all inc data to your arduino console (serial) parse this data!

Info: I've build this on my own... dont know if this is best practice :)

Thanks for your answer!! Can you provide some more info about steps 6 and 7? Thanks

Add edit part. Hope this will help you :)

I'll send you a link with all the code so you can check it out :)
Link of the codes of my project

ok I have made a google docs: https://docs.google.com/document/d/169xH-7LIu8VFCNlZT9u4TPeKOL4auB6sJ9U0x2Te9ZA/edit?usp=sharing
I can not test this code. If you got problems, just change the google docs and mark your part.


text:
ESP32 FREERTOS crash using Adafruit ST7789 in tasks with the Wifi enabled
I am trying to create a clock using a ST7789 display and a DS3231 RTC. In this clock I want to use NTP to keep it synced and maybe use the WiFi to anything else.
My problem started when I have tried to use tasks to split the code into pieces, manage priorities and to keep the loop code as clean as possible. When I try to update the display text from a task the ESP32 just crash and reboots.
I have cleaned the code to see where is the problem and I have noticed that the problem comes when I connect to my Router and then I try to update the text in the display, but doesn't fail if the WiFi is not started or I update the text outside the task. The cleaned code I am using is this:
#include <WiFi.h>
#include <Adafruit_ST7789.h>

#if CONFIG_FREERTOS_UNICORE
#define ARDUINO_RUNNING_CORE_0 0
#define ARDUINO_RUNNING_CORE_1 0
#else
#define ARDUINO_RUNNING_CORE_0 0
#define ARDUINO_RUNNING_CORE_1 1
#endif

#define TFT_MOSI 23  // SDA Pin on ESP32
#define TFT_SCLK 18  // SCL Pin on ESP32
#define TFT_CS   15  // Chip select control pin
#define TFT_DC    2  // Data Command control pin
#define TFT_RST   4  // Reset pin (could connect to RST pin)

// Colors
#define COLOR_TOP_BG tft.color565(125, 125, 125)
#define COLOR_TL_BG tft.color565(3, 96, 7)
#define COLOR_BL_BG tft.color565(3, 96, 7)
#define COLOR_TR_BG tft.color565(117, 70, 2)
#define COLOR_BR_BG tft.color565(117, 109, 2)

#define COLOR_TOP_TEXT ST77XX_WHITE
#define COLOR_TL_TEXT ST77XX_BLACK
#define COLOR_TL_TEXT ST77XX_BLACK
#define COLOR_TL_TEXT ST77XX_BLACK
#define COLOR_TL_TEXT ST77XX_BLACK

static const char* ssid     = "WIFI_SSID";
static const char* password = "**REDACTED**";

// Initialize Adafruit ST7789 TFT library
Adafruit_ST7789 tft = Adafruit_ST7789(TFT_CS, TFT_DC, TFT_RST);

// the setup function runs once when you press reset or power the board
void setup() {

  // initialize serial communication at 115200 bits per second:
  Serial.begin(115200);

  // Now set up two tasks to run independently.
  xTaskCreate(
    updateDateTime,
    "updateDateTime",   // A name just for humans
    1024,  // This stack size can be checked & adjusted by reading the Stack Highwater
    NULL,
    3,  // Priority, with 3 (configMAX_PRIORITIES - 1) being the highest, and 0 being the lowest.
    NULL
  );

  // Connecting to Wifi
   WiFi.begin(ssid, password);

  tft.init(240, 240, SPI_MODE2);    // Init ST7789 display 135x240 pixel
  tft.setRotation(3);
  drawBackground();
}

void loop() {

}

// Function to draw the display background
void drawBackground() {
  tft.fillScreen(0xFFFFFF);
  tft.fillRect(0, 0, 240, 24, COLOR_TOP_BG);
  tft.fillRect(0, 24, 120, 107, COLOR_TL_BG);
  tft.fillRect(0, 133, 120, 107, COLOR_BL_BG);
  tft.fillRect(120, 24, 120, 107, COLOR_TR_BG);
  tft.fillRect(120, 133, 120, 107, COLOR_BR_BG);

  tft.fillRect(0, 22, 240, 4, ST77XX_BLACK);
  tft.fillRect(0, 130, 240, 3, ST77XX_BLACK);
  tft.fillRect(118, 22, 4, 218, ST77XX_BLACK);
}

// Function to update the date/time
void updateDateTime( void * pvParameters ) {
  for( ;; ) {
    //tft.init(240, 240, SPI_MODE2);
    tft.setTextColor(COLOR_TOP_TEXT, COLOR_TOP_BG);
    tft.setCursor(6, 4);
    tft.println("MIE");

    delay(100);
  }
}

If I comment the WiFi.begin function or I call the function from loop without create a task or just move the three lines to loop function, it works perfectly.
#include <WiFi.h>
#include <Adafruit_ST7789.h>

#if CONFIG_FREERTOS_UNICORE
#define ARDUINO_RUNNING_CORE_0 0
#define ARDUINO_RUNNING_CORE_1 0
#else
#define ARDUINO_RUNNING_CORE_0 0
#define ARDUINO_RUNNING_CORE_1 1
#endif

#define TFT_MOSI 23  // SDA Pin on ESP32
#define TFT_SCLK 18  // SCL Pin on ESP32
#define TFT_CS   15  // Chip select control pin
#define TFT_DC    2  // Data Command control pin
#define TFT_RST   4  // Reset pin (could connect to RST pin)

// Colors
#define COLOR_TOP_BG tft.color565(125, 125, 125)
#define COLOR_TL_BG tft.color565(3, 96, 7)
#define COLOR_BL_BG tft.color565(3, 96, 7)
#define COLOR_TR_BG tft.color565(117, 70, 2)
#define COLOR_BR_BG tft.color565(117, 109, 2)

#define COLOR_TOP_TEXT ST77XX_WHITE
#define COLOR_TL_TEXT ST77XX_BLACK
#define COLOR_TL_TEXT ST77XX_BLACK
#define COLOR_TL_TEXT ST77XX_BLACK
#define COLOR_TL_TEXT ST77XX_BLACK

static const char* ssid     = "WIFI_SSID";
static const char* password = "**REDACTED**";

// Initialize Adafruit ST7789 TFT library
Adafruit_ST7789 tft = Adafruit_ST7789(TFT_CS, TFT_DC, TFT_RST);

// the setup function runs once when you press reset or power the board
void setup() {

  // initialize serial communication at 115200 bits per second:
  Serial.begin(115200);

  // Connecting to Wifi
   WiFi.begin(ssid, password);

  tft.init(240, 240, SPI_MODE2);    // Init ST7789 display 135x240 pixel
  tft.setRotation(3);
  drawBackground();
}

void loop() {
  void * test;
  updateDateTime(test);
}

// Function to draw the display background
void drawBackground() {
  tft.fillScreen(0xFFFFFF);
  tft.fillRect(0, 0, 240, 24, COLOR_TOP_BG);
  tft.fillRect(0, 24, 120, 107, COLOR_TL_BG);
  tft.fillRect(0, 133, 120, 107, COLOR_BL_BG);
  tft.fillRect(120, 24, 120, 107, COLOR_TR_BG);
  tft.fillRect(120, 133, 120, 107, COLOR_BR_BG);

  tft.fillRect(0, 22, 240, 4, ST77XX_BLACK);
  tft.fillRect(0, 130, 240, 3, ST77XX_BLACK);
  tft.fillRect(118, 22, 4, 218, ST77XX_BLACK);
}

// Function to update the date/time
void updateDateTime( void * pvParameters ) {
  for( ;; ) {
    //tft.init(240, 240, SPI_MODE2);
    tft.setTextColor(COLOR_TOP_TEXT, COLOR_TOP_BG);
    tft.setCursor(6, 4);
    tft.println("MIE");

    delay(100);
  }
}

I am starting with FREERTOS and ESP32, and I am not sure what I am doing wrong... I have thougth that the problem was the RTC but after remove the RTC code and see that was the WiFi, I am not sure what can be the problem.
Best regards and thanks.

The ESP32 has a built in RTC. Why waste time adding an external one as well?

You're not the first to have problems using a display with code running on the same core as the WiFi (core 0). Bind the task to core 1.

Hello @Majenko, the internal RTC doesn't have battery to keep the hour even when the energy is gone, and that's the real reason. Also I have read that the internal RTC is not as precise as an external. I'll try to bind it, Thanks!.

But if you're using NTP for the time, what does any of that matter?

@Majenko I am also thinking in the posibility of loose the internet connection or doesn't have it at all. Also a way to learn doing things ;)

To pin the function to a core was not working for me surely because the init code is outside the function, so I have moved the init code to inside the function, out of the loop:
#include <WiFi.h>
#include <Adafruit_ST7789.h>

#if CONFIG_FREERTOS_UNICORE
#define ARDUINO_RUNNING_CORE_0 0
#define ARDUINO_RUNNING_CORE_1 0
#else
#define ARDUINO_RUNNING_CORE_0 0
#define ARDUINO_RUNNING_CORE_1 1
#endif

#define TFT_MOSI 23  // SDA Pin on ESP32
#define TFT_SCLK 18  // SCL Pin on ESP32
#define TFT_CS   15  // Chip select control pin
#define TFT_DC    2  // Data Command control pin
#define TFT_RST   4  // Reset pin (could connect to RST pin)

// Colors
#define COLOR_TOP_BG tft.color565(125, 125, 125)
#define COLOR_TL_BG tft.color565(3, 96, 7)
#define COLOR_BL_BG tft.color565(3, 96, 7)
#define COLOR_TR_BG tft.color565(117, 70, 2)
#define COLOR_BR_BG tft.color565(117, 109, 2)

#define COLOR_TOP_TEXT ST77XX_WHITE
#define COLOR_TL_TEXT ST77XX_BLACK
#define COLOR_TL_TEXT ST77XX_BLACK
#define COLOR_TL_TEXT ST77XX_BLACK
#define COLOR_TL_TEXT ST77XX_BLACK

static const char* ssid     = "MOVISTAR_F6112";
static const char* password = "C89qlqMifsjDMWhbdsJQ";

// Initialize Adafruit ST7789 TFT library
Adafruit_ST7789 tft = Adafruit_ST7789(TFT_CS, TFT_DC, TFT_RST);

// the setup function runs once when you press reset or power the board
void setup() {

  // initialize serial communication at 115200 bits per second:
  Serial.begin(115200);

  xTaskCreatePinnedToCore(
    updateDateTime,   /* Function to implement the task */
    "updateDateTime", /* Name of the task */
    1024,      /* Stack size in words */
    NULL,       /* Task input parameter */
    3,          /* Priority of the task */
    NULL,       /* Task handle. */
    0
  );

  // Connecting to Wifi
   WiFi.begin(ssid, password);

  //tft.init(240, 240, SPI_MODE2);    // Init ST7789 display 135x240 pixel
//  tft.setRotation(3);
//  drawBackground();
}

void loop() {
}

// Function to draw the display background
void drawBackground() {
  tft.fillScreen(0xFFFFFF);
  tft.fillRect(0, 0, 240, 24, COLOR_TOP_BG);
  tft.fillRect(0, 24, 120, 107, COLOR_TL_BG);
  tft.fillRect(0, 133, 120, 107, COLOR_BL_BG);
  tft.fillRect(120, 24, 120, 107, COLOR_TR_BG);
  tft.fillRect(120, 133, 120, 107, COLOR_BR_BG);

  tft.fillRect(0, 22, 240, 4, ST77XX_BLACK);
  tft.fillRect(0, 130, 240, 3, ST77XX_BLACK);
  tft.fillRect(118, 22, 4, 218, ST77XX_BLACK);
}

// Function to update the date/time
void updateDateTime( void * pvParameters ) {
  tft.init(240, 240, SPI_MODE2);
  tft.setRotation(3);
  drawBackground();

  for( ;; ) {
    //tft.init(240, 240, SPI_MODE2);
    tft.setTextColor(COLOR_TOP_TEXT, COLOR_TOP_BG);
    tft.setCursor(6, 4);
    tft.println("MIE");

    delay(100);
  }
}

I have kept the function pinned to a core to avoid problems if RTOS decides to run the function on another core later. I have to do more tests, but seems to works.
Best regards.


text:
Powering Arduino with 12V AC-DC Adapter Jack
I have 12V,700mA AC-DC adapter power jack. Is it ok power on arduino board directly using this power jack?
Though Arduino webpage suggests that arduino can stand and upto 20V power supply, I ask this because somewhere it is written that supply 12v, 700mA will end up the board to smoke and need a converter to make it 5V.
Is this correct?
Thanks,
Jyoti Raj

You can use that to power the Arduino through the barrel jack or the VIN pin.  The only way you end up with smoke is if you try to pull too much current through that setup.  Don't power any motors or solenoids directly off of output pins for example.

I am using barrel Jack. My setup is simple it just has temperature, moisture sensors and ZigBee attached.

I don't know how much power the ZigBee draws,  but if it is very much then you might consider powering it separately.  When you supply 12V to the barrel jack then there's a lot of power that has to be dissipated across the regulator as heat.  Since there's not a very big heat sink on the regulator on the Arduino this can cause it to get hot and shut down.  If you're just running the processor off the on-board regulator and nothing else is pulling power through it then you're fine at 12V.

Is it ok power on arduino board directly using this power jack?

it depends on the regulator used and the current you expect to draw from the regulator.
essentially, you want to make sure that the power dissipation over the regulator isn't too much. that power dissipation is proportional to the voltage drop over the regulator (Vin - Vcc) and the current draw (20ma + whatever you may draw from the arduino).
once you have that, check against the regulator datasheet to make sure that its temperature rise is within range.