texts: Using an Arduino to switching a grounded load powered by a 12 Volt supply

texts:
I wish to use a MOSFET to drive a 12V rated LED strip from an Arduino.
The negative side of the LED strip must be connected to ground, so that means that the driving MOSFET must be between +12V and the LED strip.

This is what I have tried so far.

The load must be between my mosfet and my car battery GND.


texts: Any resources you know with regards to remotely reading data from arduino?

texts:
I am trying to implement arduino101 and my application needs to read data from the Arduino without a USB connection to my laptop. I appreciate you if you know any beginner-level tutorial for this.

Please let me know if you can't understand my question.


texts: SIM800L starts sending garbage values to Arduino after random interval

texts:
I have a SIM800L module connected to Arduino Mega's Serial3. SIM800L is powered by 4.2V power supply and I have put a voltage divider between Arduino's TX3 and SIM800L's RX so that the voltage in the line stays about 2V. The TX line of the module is directly connected to Arduino's RX3.

The problem is that when I try to communicate with the module it responds fine but after some AT commands the module starts panicking and start sending random garbage. The code I'm using is a simple Serial to Serial code :

#include<SoftwareSerial.h>

#define mySerial Serial3
//SoftwareSerial mySerial(10, 11);

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  mySerial.begin(38400);

}

void loop() { // run over and over
  if (mySerial.available()) {
    Serial.write(mySerial.read());
  }
  if (Serial.available()) {
    mySerial.write(Serial.read());
  }
}

Output :

[This is with serial monitor set to 115200 baud rate]

[The garbage values with serial monitor set to 9600 baud rate]

The solutions I have tried so far are :

Put a 220uF cap between SIM800L's VCC and GND. (a 470uF tantalum cap is already included on the module but still to be safe)
Tried various baud rates from 9600 to 115200 (the baud rate setting on the module is set to auto baud rate) but only 38400 works reliably.
Tried to pull the RX3 line up on Arduino with a 100k resistor so that it doesn't float.
Tried to put up to 5s delay between AT commands given to the module but it still goes into panic.

The thing I noticed is that if we enter some wrong command like ATD74xxxxxxxx (which calls a phone number) instead of with proper ending like ATD74xxxxxxxx; the module does the same thing which is spitting garbage values.

Can anybody help me with what is wrong with the module?


texts: Need Help to implement MODBUS TCP Master over Atmega32 MCU

texts:
I am doing a project where I have to interface with Fronius Solar Inverter with Atmega32 MCU over MODBUS TCP. I want to set the MCU as client and The inverter as Server and I have to implement two MODBUS Function only these are READ_HOLDING_REGISTER and WRITE_SIGLE_REGISTER and Function Code are 0x03 and 0x06 respectively.  I am newbie in this field and dont know about networking. Please anybody help me How can I develop the Software in C for this purpose??

The Document of Fronius Inverter for MODBUS TCP is Fronius MODBUS TCP Datamanger


texts: How to discard same string received at Arduino

texts:
I don't want the same string to be printed again and again. I'm getting the data into an Excel sheet.

byte readValue1=0;
byte readValue2=0;
int add=0;
int row=0;
int Zigbee1=0,Zigbee2=0,Zigbee3=0;
void setup() {
    Serial.begin(9600);
        Serial.println("CLEARDATA");
        Serial.println("LABEL,Time,Zigbee,a1,a2,a3,a4,a5,a6,a7");
        row++;
}

void loop(){
  String a1,a2,a3;
  String c1,c2,c3;
  int b;

  if (Serial.available()>21){
        if(Serial.read() == 0x7E) {
            for(int i=0; i<10; i++){
                byte discard = Serial.read();
            }
                        add = Serial.read();
                       if(add == 33)
                        {
                        a1 = func1();
                        if(a1==c1){
                          b=0;
                        }
                        else
                        {
                          b = a1.length();
                        }
                        if(b != 0)
                       {
                        Zigbee=1;
                        Serial.print("DATA,TIME,"); Serial.print(Zigbee);
                        Serial.print(","); Serial.println(a1);
                        row++;
                        }
                        }
                      else if(add == 48)
                        {
                        a2 = func1();
                        b = a2.length();
                        if(b != 0)
                      {
                        Zigbee=2;
                        if(a2!=c2){
                       Serial.print("DATA,TIME,"); Serial.print(Zigbee);
                       Serial.print(","); Serial.println(a2);
                        }
                        c2=a2;
                       row++;
                        }
                        }

                       else if(add == 69)
                        {
                          a3 = func1();
                          b = a3.length();
                          if(b != 0)
                         {
                          Zigbee=3;
                          Serial.print("DATA,TIME,"); Serial.print(Zigbee);
                          Serial.print(","); Serial.println(a3);
                          row++;
                    }
                        }
}
}
}


texts: Why is that any sensor signal need to be hooked up to the interrupt pins on Andruino boards?

texts:
I have come across some Andruino Sensors like Motion, Light and all recommend to be connected to pin 2 or 3 on Andruino Uno board which are interrupt pins. This is especially true if you are looking for HIGH or LOW values. Why is that to be connected to interrupt pins?

One example would be is I used CC3000 Wifi Breakout and Motion sensor. Both were in fight to occupy the interrupt pin 2. I have seen the Motion sesnor not working correctly after getting it's signal hooked to Pin 4[It has pull up resistor enabled]

What should I do if i need to hook up more sensor which uses the limited interrupt pins and how should i handle the above scenario?


texts:
Trying to list root directory of LittleFS; but only files beginging with "/LOG."

String str;

                     if (!LittleFS.begin())
                     {
                          Serial.println("LittleFS failed to mount !");
                     }
                     Dir dir = LittleFS.openDir("/");
                     while (dir.next())
                     {

                        if(strncmp(dir.fileName().c_str(), "/LOG", 4) == 0)
                        {

                            str += "";
                            str += dir.fileName();
                            str += "";
                            str += "    ";
                            str += dir.fileSize();
                            str += "
\r\n";
                        }
                     }

                     client.print(str);

If I comment out "if(strncmp(dir.fileName().c_str(), "/LOG", 4) == 0)" and associated braces; all files list.  Code with "if(strncmp(dir.fileName().c_str(), "/LOG", 4) == 0)" no files are listed.

How can I list only files that begin with "/LOG?"

William


texts: Parsing Integers from Serial data stream

texts:
I'm trying to send sensor data from my Remote Control to my Bot via Bluetooth.
It's 6 numbers that I would like to have read as integers on the other side.
I'm printing them to Serial on the Remote side with the numbers separated by commas. I've also added a start marker "<" and an end marker ">".

The incoming data from the remote looks like this in the Bots Serial Monitor:

<1,1,1,1,1,512>
<1,1,1,1,1,512>
<1,1,1,1,1,513>
<1,1,1,1,1,512>
<1,1,1,1,1,512>
etc

Before adding in the markers I was trying to use Serial.parseInt() to do this, but I kpet getting out of order numbers (probably from no start marker?).

if (Serial1.available() > 0) {

 trig1 = Serial.parseInt();
 trig2 = Serial.parseInt();
 trig3 = Serial.parseInt();
 trig4 = Serial.parseInt();
 trig5 = Serial.parseInt();
 pot = Serial.parseInt();

if (Serial.read() == '\n') {
}
}

But now that I have the markers I don't know the best way to initialize the code.  Anyone have any ideas on how to parse these 6 numbers into usable integers?

EDIT:  I've wrote a code based on VE7JRO's comments.

uint16_t myArray[6] = {};
int counter = 0;

void setup(){

Serial.begin(9600);

}

void loop(){
  if (Serial.available() > 0) {
  char* pch = strtok(Serial.read,"<>,\r\n");
   }
while(pch != NULL){
  myArray[counter] = atoi(pch);
  pch = strtok(NULL, "<>,\r\n");
  counter += 1;
 }

 trig1 = myArray[0];
 trig2 = myArray[1];
 trig3 = myArray[2];
 trig4 = myArray[3];
 trig5 = myArray[4];
 pot   = myArray[5];

 Serial.print (trig1);
 Serial.print (", ");
 Serial.print (trig2);
 Serial.print (", ");
 Serial.print (trig3);
 Serial.print (", ");
 Serial.print (trig4);
 Serial.print (", ");
 Serial.print (trig5);
 Serial.print (", ");
 Serial.println(pot);
 }

I'm getting this error code: invalid use of non-static member function
for this line:

      char* pch = strtok(Serial.read,"<>,\r\n");

Other than that. I subbed out the test input that  VE7JRO put in and inserted "Serial.read". Not sure if that is the correct way to do this.  Any ideas?

I tried your second sketch.  It kind of worked.  The data that printed to the serial monitor looked like this:

1, 1, 1, 1, 1, 519
518, 1, 1, 1, 1, 519
1, 1, 1, 1, 19, 9
1, 1, 1, 1, 1, 519
1, 1, 1, 1, 1, 519
1, 1, 1, 1, 1, 518
1, 1, 519, 518, 1, 518
1, 1, 519, 518, 1, 518
1, 1, 518, 518, 1, 518
1, 1, 1, 1, 1, 8
1, 1, 1, 1, 1, 519
1, 1, 518, 1, 1, 1
8, 1, 518, 1, 1, 1
1, 1, 519, 1, 1, 1
1, 1, 1, 519, 1, 1
1, 1, 1, 519, 1, 1
1, 1, 1, 1, 1, 519
1, 1, 1, 1, 1, 518
1, 1, 1, 1, 519, 8
1, 1, 1, 1, 1, 518
1, 1, 1, 1, 1, 519
1, 1, 1, 1, 1, 518
1, 1, 1, 1, 1, 518
1, 1, 1, 1, 1, 520

it should have all been   1, 1, 1, 1, 1, 518(ish).


texts:
I am using custom shared_ptr class for some program on Arduino, and I need to do something like this:

shared_ptr<Base_class> b_ptr;
shared_ptr<Child_class> ptr((shared_ptr<Child_class>) b_ptr);

In my shared_ptr class I have three constructors:

shared_ptr() : pData(0), reference(0){...}
shared_ptr(T* pValue) : pData(pValue), reference(0){...}
shared_ptr(const shared_ptr<T>& sp) : pData(sp.pData), reference(sp.reference){...}

and some other stuff...
For casting I tried to write the following:

    template< typename T2 >
operator T2 * () const
{
   return (T2 *)pData;
}

and:

    template< typename T2 >
operator shared_ptr<T2> () const
{
    shared_ptr<T2> temp((T2 *)pData);
    return temp;
}

but can't get it to work.


texts: Reading from software serial with an interrupt

texts:
I want to perform a serial read using software serial with Arduino. I am looping for my normal tasks, but whenever something is received on the software serial pins I want to perform a read operation and based on the character received, I want to run a function in the loop.
I think this is possible with interrupts only. But I can not see any documentation or help on how to perform this.
How to write an ISR for this task?


texts: Using the same variable between if-statements within loop()

texts:
I wonder if there is a good way to use the same variable value between two different if-statements within the loop().

Within the Servomotor section of the code, I want to use the value from the first if-statement's RewardTime within the next if-statement's RewardTime. Thus far, I cannot find a way to do it.
(Since there is no communication between these variables right now, the RewardTime remains 0).

I'd appreciate a certain guidance in this matter.

#include <Servo.h> // Library required for the servomotor (Make sure to download if not in the library)
#include <Button.h> // Library required for the microswitch (Make sure to download if not in the lbrary)

// PARAMETERS
// COPY THESE VALUES IN PROCESSING CODE MANUALLY
// Explanation: To prevent possible Arduino-Processing overflow. Do not want too much information flow between Arduino and Processing.
const float Scale = 1 * 1000; // milliseconds
const float Base = 1 * 1000; // milliseconds

Servo Servo1;
int servoPin = 9; // Declare the Servo pin
Button button(7); // Declare the microswitch pin (Can be varied from setup to setup)

unsigned long previousMillis = 0;
bool switching = false;
int State = LOW;

char BirdSings = 0;
//static float RewardTime = 0;

void setup() {
   Servo1.attach(servoPin);
   analogWrite(9, 0);
   Serial.begin(9600);
   button.setDebounceTime(100); // set debounce time to 100 milliseconds
}

void loop(){
   // MICROSWITCH
   // Get onset and offset times of when the bird arrives and leaves the perch
   button.loop();
   if(button.isPressed())
    Serial.println(1);
   if(button.isReleased())
    Serial.println(0);

   // SERVOMOTOR
   // Get times when the feeder is covered (food present) and uncovered (food not present)
    unsigned long currentMillis = millis();
    while (Serial.available() > 0) {
    unsigned long currentMillis = millis();
   if (Serial.read() == '\n') { // When there is a song
     //Serial.println(2); // Food is uncovered
     previousMillis = currentMillis; // 0 becomes the current milli
     static float RewardTime = (Serial.parseFloat() * Scale) + Base; // CALCULATE THE RewardTime HERE
     Serial.println(RewardTime);
     if (State == LOW)
      State = HIGH;
     else
      State = LOW;
    }
   }

  if (State == HIGH && switching == false){
    Servo1.write(0); // 0 degree
    unsigned long secondCurrentMillis = millis();
    if (secondCurrentMillis - previousMillis > RewardTime) { // USE THE ABOVE RewardTime HERE
      switching = true;
      previousMillis = secondCurrentMillis;
      if (State == LOW)
        State = HIGH;
      else
        State = LOW;
    }
  }
  if(State == LOW && switching == true){
    Servo1.write(90); // 90 degrees
    switching = false;
    //Serial.println(3); // Food is covered
    }
}


texts: How do I use Microduino (mCookie) on Linux?

texts:
I'm interested in getting the mCookie working in Linux — specifically, in Fedora 23. The Arduino IDE (version 1.6.4) is already available. I'm very familiar with Linux, fine with C, and completely new to Arduino.

The tutorials for Windows or Mac describe installing a customized version of the IDE along with drivers. Do I need special drivers on Linux? On the projects' GitHub site, I found the examples and a directory called 'avr' which has promising subdirectories like "bootloaders" and "libraries", along with files boards.txt and platform.txt.

Can I download this stuff and add it to the existing "system" arduino package somehow? How, and what will I need?


texts: How can we remove unused feature in Arduino's standard SD library so we can reduce the sketch size?

texts:
With the ReadWrite example in Arduino IDE, the sketch size is 10980 bytes (34%) of an Arduino UNO's storage. How can we reduce the sketch size? There isn't any kind of #define to turn on/off features in SD.h. I only need read, write, append and seek features, not anything else.
I have found the PetitFS port for Arduino, but it doesn't support appending to a file. There is also TinySDLogger but I think it's for good for logging rather than normal file writing. I have found SdFat too.
My main work has used 26234+ bytes of flash and I cannot add more 10KB to the sketch!


texts: OV2640 with 18 Pins - No XLCK System Clock

texts:
I'm trying to connect an OV2640 camera module to a microcontroller.

This camera module has only 18 pins as seen in this schema:
https://imgur.com/a/SGpfrXt

Here an image of the module:
https://imgur.com/a/7MOIDwi

These pins are on the module:

3.3V
GND
VSYNC
SCL
SDA
HREFF
D0 - D7
DCLK
PWDN
NC

Maybe I could set XLCK and PLCK via the DCLK pin but I don't know how.

I am pretty new to camera modules and searched the net a lot of times. Most examples are for the OV7670. This module has also 18 Pins but all are used quiet contrary to the OV2640.

Could anybody help me connect and get a signal?


texts: Basic Arduino Question. Trying to turn off leds turned on through the serial monitor by using a push button

texts:
I'm new to using the serial monitor. I have a code set up so that LEDs turn on when I type an input on the keyboard. I know how to turn them off using a keyboard but I and can't figure out why the leds won't turn off when I press a push button.

    #define led1 10 //10th,
    #define led2 11 //11th
    #define led3 12 //12th
    #define led4 13 //13th
    #define ButtonA 9

    int ButtonState;
    int ButtonState2;
    int state;
    int StateNow;
    int PreviousState = HIGH;

    void setup(){
      pinMode(led1,OUTPUT);
      pinMode(led2,OUTPUT);
      pinMode(led3,OUTPUT);
      pinMode(led4,OUTPUT);
      pinMode(ButtonA,INPUT_PULLUP);
      Serial.begin(9600);
      Serial.println("Enter ch a, b, c, or d:");
    }

    void loop() {
    if (Serial.available())
    {
      ButtonState = digitalRead(ButtonA);
      delay(10);
      ButtonState2 = digitalRead(ButtonA);  //debounce
      if (ButtonState != ButtonState2)
      {
        StateNow = ButtonState2;
      }
      else
      {
        StateNow = ButtonState;
      }
      if(StateNow == LOW && PreviousState == HIGH)
  {
    digitalWrite(led1,LOW);
    digitalWrite(led2,LOW);
    digitalWrite(led3,LOW);
    digitalWrite(led4,LOW);
    Serial.println("Turned off all LEDs");
    PreviousState = LOW;
  }
  else if(StateNow == HIGH && PreviousState == LOW)
  {
    PreviousState = HIGH;
  }
  state = Serial.read();
  if (state == 'a' || state == 'A')
  {
    digitalWrite(led1,HIGH);
    Serial.println("Turned on led 1");
  }
  else if (state == 'b' || state == 'B')
  {
    digitalWrite(led2,HIGH);
    Serial.println("Turned on led 2");
  }
  else if (state == 'c' || state == 'C')
  {
    digitalWrite(led3,HIGH);
    Serial.println("Turned on led 3");
  }
  else if (state == 'd' || state == 'D')
  {
    digitalWrite(led4,HIGH);
    Serial.println("Turned on led 4");
  }
}

}

The LEDs turn on properly and I know the circuit is wired correctly so it's definitely something I'm missing in the software


texts: 2 Channel Relay normal open is not working with NodeMCU but led on board light up

texts:
I am pretty new to NodeMCU (ESP8266) and Arduino IDE in general. I followed various documentation / blogs to set up 2 Channel Relay with NodeMCU chip.

Below is sketch code for it.

#include<CayenneMQTTESP8266.h>
#define CAYENNE_DEBUG
#define CAYENNE_PRINT Serial

#define LEFT_GARAGE 4
#define RIGHT_GARAGE 5

char ssid[] = "XXXXXXXXXXXXXXXXXXXXXXXX";
char password[] = "XXXXXXXXXXXXXXXXXXXXXX";

char username[] = ""XXXXXXXXXXXXXXXXXXXXXX";";
char mqtt_password[] = ""XXXXXXXXXXXXXXXXXXXXXX";";
char client_id[] = ""XXXXXXXXXXXXXXXXXXXXXX";";

void setup() {
  Cayenne.begin(username, mqtt_password, client_id, ssid, password);
  pinMode(LEFT_GARAGE, OUTPUT);
  digitalWrite(LEFT_GARAGE, HIGH);
  pinMode(RIGHT_GARAGE, OUTPUT);
  digitalWrite(RIGHT_GARAGE, HIGH);
}

void loop() {
  Cayenne.loop();
}

// Left Garage Door
CAYENNE_IN(0){
  int currentValue = getValue.asInt();
  digitalWrite(LEFT_GARAGE,!currentValue);
}

//Right Garage Door
CAYENNE_IN(1){
  digitalWrite(RIGHT_GARAGE,!getValue.asInt());
}

On relay board I tried to connect wire in 2 different configuration.

1st Config:

vcc -> 3.3v from NodeMCU
in1 -> D1/GPIO 04 from NodeMCU
in2 -> D2/GPIO 5 from NodeMCU
GND -> GRD from NodeMCU

2nd Config:

vcc -> 5v USB from NodeMCU
in1 -> D1/GPIO 04 from NodeMCU
in2 -> D2/GPIO 5 from NodeMCU
GND -> GRD from NodeMCU

In 1st config, On relay board respective LED's are turning on when Cayenne buttons are pressed but when I check for continuity on multi meter I don't get anything.

In 2nd config, no LED and no continuity.

am I missing something here? Any feedback/comments are highly appreciated.


texts: How do I set up a multi-file project in the Arduino IDE?

texts:
Suppose I have a project with several modules and a main program.  This works well by adding the modules to main_program.

module1.cpp
module1.h
module2.cpp
module2.h
...
main_program.ino

I'm having problems when I have test programs for each of the modules.  These allow the various devices to be tested in isolation.

module1.cpp
module1.h
module1.ino # test program
module2.cpp
module2.h
module2.ino # test program
...
main_program.ino

I'm required to have each ino file in a directory of the same name.  I can add the files to main_program by adding (e.g.) ../module1/module1.{cpp,h}.  But, I discover that it has actually copied module1.{cpp,h} to main_program/.

How do I set this up?  Is there any option other than making each module a library?  If possible I would like to keep these files more local than the library directory, since they're specific to this project and not general-purpose libraries.


texts: How to store incoming serial data to char array in order to send to other module (XBee)?

texts:
I am trying to get the incoming serial data in Arduino from a GPS. I suppose to get the following data:

  $GPRMC,073522.000,A,2607.5285,N,12739.9649,E,0.43,263.10,131217,,,A*6C

However, it is not stable. Following is the code. Appreciate your help.

#include <SoftwareSerial.h>
SoftwareSerial gps(2, 3); // RX, TX
int N = 70; // size of array
char incomingSerialData[70]; //32
int incomingSerialDataIndex = 0;

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

void loop() {
  while(gps.available()) {
    delay(10);
    incomingSerialData[incomingSerialDataIndex] = gps.read();
    incomingSerialDataIndex++;
    if (incomingSerialDataIndex > N-1) incomingSerialDataIndex = 0;
  }
  Serial.println(incomingSerialData);
}


texts:
I asked this question also in Electrical Engineering (stack exchange), however on question is more appropriate on this board (question 5). For completeness, I kept all questions intact, but made question 5 bold.

Electrical Engineering StackExchange Question Link: Using a MIDI connector both as MIDI In and Out (not simultaneously),

In my current (Arduino) project I have (currently) 3 MIDI INs and 2 MIDI OUTs. However, it would be nice if I can configure each of the MIDI connectors as IN or OUT by software (Arduino).

The circuits I am using are:

And

What I would like is to use the connector shown in the above picture as MIDI In OR MIDI out. I have not tried it yet, since I have too many doubts and I do not want to break a component. However, I thought about it (with my limited electronic knowledge), and I think:

Pin 2 afaik for MIDI In, normally has +5V. In the MIDI Input circuit it is not connected, but in the MIDI Output circuit, it is connected to GND. I don't think this is good when being used as MIDI out, resulting in a short circuit (?). So I guess I have to make it +5V when used as MIDI Input and GND when used as MIDI Output (so putting HIGH or LOW 'digital' for Arduino).
Pins 1 and 3 remain in both circuits untouched (so I assume I can do the same).
Pin 4 and 5 is a bit tricky, since they are connected. I think I have to use one or two transistors to create two alternative paths for pins 4 and 5 for MIDI Input and Output. Or can I just set a specific voltage on pins 4 and 5 when used as MIDI In or Out? (and what would those values be?).
For the MIDI input, an optocoupler is used, while for MIDI output, directly the Arduino is used. I wonder if I have to use for both an optocoupler (since people might connect it accidentally to a MIDI output from a MIDI device.

5. I'm not sure how to handle the RX and TX pins ... for 5 MIDI devices, I would need to use 5 RX and TX pins, but the Arduino (Mega) only has 4 of each. But this is probably a question for the Arduino board.


texts: Is EEPROM's location relocated on sketch compile?

texts:
I assumed the microcontroller has 3 components as per storing data:
- flash memory for the program
- RAM for variables
- EEPROM for non-volatile user-storage

And I always assumed those are separate chips on the board. However, working directly with a RobotDyn Uno R3 leads me to believe I may be wrong somehow.

I compiled this program:

#include <EEPROM.h>

struct SettingsStruct {
  String server;
  String port;
  String user;
  String password;
  String description;
} gSettings = {
  "192.168.1.6",
  "8080",
  "fci blah vlak",
  "zangazang4",
  "Extra string here"
};

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

  //saveConfig();

  Serial.print(F("EEPROM size is: "));
  Serial.print(EEPROM.length());
  Serial.print(F(" bytes"));
  Serial.println("");

  loadConfig();
  Serial.print(F("Server: "));
  Serial.print(gSettings.server);
  Serial.println("");
  Serial.print(F("Port: "));
  Serial.print(gSettings.port);
  Serial.println("");
  Serial.print(F("Username: "));
  Serial.print(gSettings.user);
  Serial.println("");
  Serial.print(F("Password: "));
  Serial.print(gSettings.password);
  Serial.println("");
  Serial.print(F("Description: "));
  Serial.print(gSettings.description);
}

void loop()
{
  // nope
}

void loadConfig() {
    for (unsigned int t=0; t<sizeof(gSettings); t++)
      *((char*)&gSettings + t) = EEPROM.read(t);
}

void saveConfig() {
  for (unsigned int t=0; t<sizeof(gSettings); t++)
    EEPROM.write(t, *((char*)&gSettings + t));
}

Problem is that each time I add new elements to the struct, and I run the program, the serial prints different things. I recognize previously saved strings but they are right shifted, meaning that somehow the ZERO address of EEPROM might have moved backwards and previously saved strings move right and offocurse, appear on other struct variables.

This leads me to believe the actual EEPROM is related with the flash memory and depends on it on each compile. As if the ZERO address of EEPROM is established after each compile.

Can anyone confirm this or lead me to some documentation relating this? It's a weird mystery that I would like to clear out.


texts: Why can't I switch off the LED immediately using this sketch?

texts:
I hope the LED can fade out a period of time. Also, I hope I can switch off the LED immediately when it is fading, but I only can fade out.

const int buttonPin = 2;
const int ledPin = 9;
const int fadingDelay = 20000;
int buttonState = 0;
boolean fadingState = false;
void setup() {

// initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
}
void loop() {
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);

  // check whether the button was pressed
  if (buttonState == HIGH) {
    buttonState = LOW;
    // check the current LED status (on/off)
    if (fadingState == false) {
      // turn on the LED
        for (int i = 255; i >= 0; i -= 5) {
          if (buttonState == HIGH && fadingState == true) {
          analogWrite(ledPin, 0); //immediately off
          i=-1;
          }
        analogWrite(ledPin, i);
             delay(fadingDelay);

    }
    fadingState = false;  // save the current LED state (on/off)
  }
}
}


texts: What causes Serial.available() to become false after Serial.read() gets data?

texts:
As serial data bytes are being read from the serial buffer by Serial.read(), are they removed from the Arduino's 64-byte serial buffer altogether?

In my current situation I'm using SoftwareSerial, but this question applies to both software and hardware serial connections.

EDIT: Based on a comment from @dandavis, I'd like to further clarify my question

How does Serial.read() interact with Serial.available()? Let's say that I have the usual setup:

while( Serial.available() ) {
    Serial.read();
}

What causes Serial.available() to become false?

EDIT 2: Changed question title for even further clarification...


texts: How to connect HC-05 to an arduino Galileo?

texts:
I connected a logic analyzer on digital pins 0 and 1 (Rx and Tx). Using Serial. functions on Galileo and the integrated terminal on Arduino IDE, I noticed this UART port was not used when chars were received and transmitted, what is sustained by the blocks diagram of Galileo here.

So, if UART1 is used on PC communications, I would like to use UART0 to other things, like a bluetooth adapter. Any tips?


texts: Using TxD pin and NeoPixel library for RGB LEDs

texts:
I have no free pin on my ESP-12 but GPIO16 and TxD (GPIO1). I use Neo Pixel Library and this design:

GPIO16 powers it on/off
TxD uses to handle single-wire-based for LEDs (GPIO1)

It works but it has one issue. I use USB <> TTL converter to program my ESP, it just worked for 1 2 times and after that burned the converter! I'm afraid there's something wrong with my design. Any better idea to use GPIO16 and TxD to do that? I need to power down LEDs when I don't need them to save power.


texts: RF RX not working when using ATtiny85 at 1MHz

texts:
The ATTiny85 code fails to read input from a 433Mhz RF receiver when working at 1MHz. The following example compiles perfectly and runs OK wihen the ATTiny85 is working at 8MHz. However, it compiles but does not receive anything (the LED connected in pin 3 does not toggle) when working at 1MHz. Any advice to solve this problem?

#include <Manchester.h>
#define LED_PIN 3
uint8_t moo = 1;

#define TX_433_PIN 0
#define RX_433_PIN 1
#define BUFFER_SIZE 10
uint8_t buffer[BUFFER_SIZE];

void setup() {
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, moo);
  man.workAround1MhzTinyCore();
  man.setup(TX_433_PIN, RX_433_PIN, MAN_1200);
  man.beginReceiveArray(BUFFER_SIZE, buffer);
}

void loop() {
  if (man.receiveComplete()) {
    man.stopReceive();
    // Toggle LED in pin 3 if something received
    moo = ++moo % 2; digitalWrite(LED_PIN, moo);
    man.beginReceiveArray(BUFFER_SIZE, buffer);
  }
}

I am using this Manchester based library for the RF transmision. The ATTiny hardware description for Arduino IDE is provided by the Arduino-Tiny library. I am using the 1.0 Arduino IDE.


texts: Looking at the Sparkfun comparison, it seems that the Due is by far the fastest of the Arduinos and has I/O capabilities similar to the Mega. So why was it retired with no obvious successor?


texts: Read an analog signal without changing it? Or should I start over?

texts:
Hi! I'm still working on my kettle project. I want to obtain the kettle temp from the existing thermometer. I'm able to do this, but much like trying to look at an electron my circuits all reduce the voltage going to the kettle control board. This means the kettle's microcontroller (SN8P2722  SONiX) acts as if the kettle is cooler than it really is.

I don't think there is an easy way to program this microcontroller (if there is I'd love to know) -- I suspect the bad temp data will lead to overheating and hot water all over my kitchen.

Is there any way to passively obtain the voltage? I've been looking into the way that voltmeters work. Is this the right idea? is there a breakout board for this?

I really wanted to have the existing buttons still work as they always have. I've done this with power. I can press it remotely or on the kettle and I can tell of the kettle is on or off both on the control panel and remotely.

I can press all the other buttons remotely but I can't tell if it's working without knowing the kettle temp.

Maybe I should try to replace the entire control board? What would be easier? I'm something of a beginner.


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

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

and a bunch of lines like

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

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


texts: Adafruit Feather 32u4 Bluefruit LE and HC-05 Bluetooth module

texts:
Is it possible to connect an Adafruit Feather 32u4 Bluefruit LE with an HC-05 Bluetooth module?

I am making a heart rate monitor using an Adafruit Feather, but it is unable to send the data to LABView for processing as it uses BLE. I do not have the means to buy a Bluetooth dongle to work around the issue.

However, I do have an HC-05 Bluetooth module that can be read by VISA on LABView.

Therefore I would like to ask if it is possible to connect my Adafruit Feather to my HC-05 module and send the data through the HC-05 instead of the built-in BLE.

Thank you!


texts:
I am busy toying with some PIR sensors to detect movement etc for a nightlight for my kids. One of the sensors I ordered is the PYM-1 PIR sensor.

The data sheet states the following:

Operating Voltage: 4,5~5V.
Standby current: 65 micro-amps (65uA)
Operating Current: 40mA (40 milli-amps)

The limit for current on the arduino pins is 40mA. According to documentation at the arduino site 40mA is the upper limit per pin and the site clearly states: Absolute Maximum Ratings - the point where damage will start to happen I would rather avoid sinking the current directly on the Arduino.

So my question is will sinking 40mA on a pin cause damage? I have not been visited by the blue smoke genie yet and would rather avoid it at this point.

I suspect it might be safer to run this via a transistor and external power than directly on the arduino?


texts:
The basic example for ESP32 NTP is very rough:
void setup()
{
  Serial.begin(115200);

  //connect to WiFi
  Serial.printf("Connecting to %s ", ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
  }
  Serial.println(" CONNECTED");

  //init and get the time
  configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
  printLocalTime();

  //disconnect WiFi as it's no longer needed
  WiFi.disconnect(true);
  WiFi.mode(WIFI_OFF);
}

But it tells nothing about the success of the operation.
I need to know if it was able to update the time from the NTP server... is there a method to know that?
I can't rely on the time struct because I must init it manually at startup, say at 1st Jan 2020 00:00.


texts: How to make timed loops after switch / case?

texts:
I am working on a code, which is running a function once a second:

switch (gearbox1) {
  case 1:
    //manually close
    Serial.println("Closing1");
    digitalWrite(gear1OpenPin, OFF);
    t.setTimer(1000, Close1, 1);

    break;

  case 2:
    //manually open
    Serial.println("Opening1");
    digitalWrite(gear1ClosePin, OFF);
    t.setTimer(1000, Open1, 1);

    break;

This part is working fine. But then i want at case 10: call function autoClose() which would work in 10 second cycles.

Struggle is, as my first function is called once a second, it is starting function autoClose() once a second as well. How can I overcome this please?

At the moment I have current, non working code:

  case 10:
    //automatic close
    Serial.println("A Close1");
    digitalWrite(gear1ClosePin, OFF);
    digitalWrite(gear1OpenPin, OFF);

    t.enable(autoClose);
    autoClose();
    break;

Edit: Added minimal possible code. I want autoOpen() and autoClose() to loop in 10 sec. intervals.

#include <SimpleTimer.h>
SimpleTimer t;
int gearbox1;

#define gear1OpenPin 44
#define gear1ClosePin 46

int OFF = HIGH;  // states for relays
int ON = LOW;

byte gear1Open = 0;
byte gear1Close = 0;

void setup() {

  t.setInterval(1000, Control1);
  int autoOpen = t.setInterval(10000, autoOpen);
  int autoClose = t.setInterval(10000, autoClose);
}

void loop() {

  t.run();
}

void Control1() {
  //*****************************************
  switch (gearbox1) {
    case 1:
      //manually close
      Serial.println("Closing");
      digitalWrite(gear1OpenPin, OFF);
      t.setTimer(1000, Close1, 1);

      break;

    case 2:
      //manually open
      //   Serial.println("Opening");
      digitalWrite(gear1ClosePin, OFF);
      t.setTimer(1000, Open1, 1);

      break;

    case 5:
      //stop
      Serial.println("Stopping");
      digitalWrite(gear1ClosePin, OFF);
      digitalWrite(gear1OpenPin, OFF);

      break;

    case 10:
      //automatic close

      digitalWrite(gear1ClosePin, OFF);
      digitalWrite(gear1OpenPin, OFF);
      if (t.isEnabled(autoClose)) {
        autoClose();
      } else {
        t.restartTimer(autoClose) ; t.enable(autoClose);
        autoClose();
      }
      break;

    case 20:
      //automatic open

      digitalWrite(gear1ClosePin, OFF);
      digitalWrite(gear1OpenPin, OFF);
      t.restartTimer(autoOpen); t.enable(autoOpen);
      autoOpen();
      break;
 }
}

void Open1() {
  digitalWrite(gear1OpenPin, ON);
}
//**********************************************
void Close1() {
  digitalWrite(gear1ClosePin, ON);
}
//**********************************************
void autoOpen() {

  if (gear1Open == ON) {
    gear1Open = OFF;
  } else {
    gear1Open = ON;
  }
  digitalWrite(gear1OpenPin, gear1Open);
}
//**********************************************
void autoClose() {
  if (gear1Close == ON) {
    gear1Close = OFF;
  } else {
    gear1Close = ON;
  }
  digitalWrite(gear1ClosePin, gear1Close);
}


texts:
I am looking at modifying the H3LI331DL I2C library posted by Seed Studio for communicating with the H3LI331DL accelerometer. The library hardcodes the address for the accelerometer in the header file. My end goal is to make the library require a slave address input argument so I can talk to 2 accelerometers on the same I2C bus. The chip has a pin that sets the LSB of its address.

Now onto the question. The library's .h file has the following statement:

#define H3LIS331DL_MEMS_I2C_ADDRESS     0x18//0x32

Is the 0x32 simply commented out or am I missing something here?

Thanks,

Emach


texts: Obtaining angular velocity from quaternion data (BNO055)

texts:
I'm able to get quaternion data from the BNO055 sensor, and would like to convert these to angular velocity for my project. I know you can pull the gyroscope directly for the data, but from what I understand using quaternions and converting those is more robust?
I found a function that does this in a Adafruit repository for the sensor. However, I'm not sure what the Delta time variable should be equal to, in relation to the sample frequency. Could anyone advise?
Here is the function code:
  Vector<3> toAngularVelocity(double dt) const {
    Vector<3> ret;
    Quaternion one(1.0, 0.0, 0.0, 0.0);
    Quaternion delta = one - *this;
    Quaternion r = (delta / dt);
    r = r * 2;
    r = r * one;

    ret.x() = r.x();
    ret.y() = r.y();
    ret.z() = r.z();
    return ret;
  }

And the link


texts: string.indexOf() always returns a non-zero value

texts:
I am developing a hardware project which contains a facility to change the stored password by any user, if he/she knows the current password.The new password is stored in arduino eeprom. In the main screen, if the user enters the current password, door is unlocked from inside. . The issue faced here is that the point where current password is entered by user, it works fine, but I want to check that '#' is not entered by user in the new password which is not performed properly.

Because in the main screen, when user presses '#' key, change password function is called up, where user is asked to enter current password.

Here is the screenshot of the circuit prepared from fritzing.

The code snippet for entering new password is as under.

lcd.clear();
lcd.print("New Passkey:");
lcd.setCursor(0, 1);
while (j < 4)
{
  char key = keypad4x4.getKey();

  if (key)
  {
    new_password[j++] = key;
    lcd.print(key);
    tone(buzzer, 1000, 50);

    if (j == 4)
    {
      lcd.print("4 reached");
      delay(1000);
      new_password[5] = '\0';
      String str = String(new_password);
      if (str.indexOf('#'))    /** this condition comes out to be true always i.e. always returns a non-zero value**/
      {
        tone(buzzer, 200, 700);
        lcd.clear();
        lcd.print("Invalid Entry");  /** It is printed everytime on lcd**/
        delay(2000);
        key = 0;
        changePass();
        break;
      }
      else  /** this block is not entered, so new password is not saved in EEPROM **/
      {
        for (int i = 0; i < 4; i++)
        {
          EEPROM.write(i, new_password[i]);
        }
        lcd.print(" Done......");
        delay(1000);
        break;
      }
    }
  }
}

and

new_password[5] is used to store new password entered by user.

Now, I am using a string variable to store this new password.

I am using  string.indexof() function to identify whether this new password contains a '#' character anywhere in it.But it seems that when I put this in an if block in code, it becomes true everytime.I have added comments at respective positions to highlight the problem faced by me. I have tested this code in Proteus simulator, and actual project too.

So, my issue is this one, even if correct password is entered by user,without '#', then also, string.indexOf('#') condition becomes true(returns a non-zero value everytime) and thus even valid password is not saved in EEPROM.
I guess I was able to explain my query accurately, please go through the code, and tell me where I am wrong, because I have gone through it many times and could not find the exact issue. Thanks in advance


texts: Unable to send SMS from interrupt routine

texts:
I am trying to develop a burglar alert system. I am using PIR sensor, Arduino Mega and SIM800L. I have connected PIR sensor to interrupt pin. Whenever motion is dected, a function corresponding to the interrupt will be called. In that function I am sending a SMS to notify with an alert message. If motion is detected 2 times, I will call the emergency contact number.

This is the code I have written.

#include <SoftwareSerial.h>
#define PIR1 2
#define SIREN 13
#define statusLED 12

SoftwareSerial SMS(11, 10);// rx(11-arduino) connect to tx(gsm module)
                         // tx(10-arduino) connect to rx(gsm module)

String CONTACT1 = "xxxxxxxxxx";  //mobile number

boolean status;
byte motionCtr = 0;
unsigned long latestMovementTime = 0;

void setup() {
  pinMode(PIR1,INPUT);
  pinMode(SIREN,OUTPUT);
  pinMode(statusLED,OUTPUT);

  Serial.begin(9600);
  SMS.begin(9600);
  SMS.println("AT+CNMI=2,2,0,0,0");

  delay(5000);
  activateSystem(0);
}

void loop() {
  unsigned long currentTime = millis();
  //If motion is not dected for 5 minutes, turn off the siren.
  if(currentTime - latestMovementTime > 300000 && motionCtr>=1){
    stopSiren(0);
  }
  delay(500);
}

void activateSystem(byte manual){
  delay(60000); //warm up time for PIR sensor
  attachInterrupt(0,motionDetected,RISING);

  status = true;
  digitalWrite(statusLED,HIGH);

  if(manual){
    Serial.println("System ACTIVATED by SMS.");
    notifyBySMS("System ACTIVATED SMS.");
  }else{
    Serial.println("System ACTIVATED.");
    notifyBySMS("System ACTIVATED.");
  }
}

void deactivateSystem(byte manual){
  detachInterrupt(0);

  status = false;
  digitalWrite(statusLED,LOW);

  if(manual){
    Serial.println("System DEACTIVATED by SMS.");
    notifyBySMS("System DEACTIVATED SMS.");
  }else{
    Serial.println("System DEACTIVATED.");
    notifyBySMS("System DEACTIVATED.");
  }
}

void motionDetected(){
  startSiren("Motion at bedroom door.");
}

void startSiren(String msg){
  //Record the time of latest motion dected.
  latestMovementTime = millis();

  motionCtr++;
  Serial.print("Ctr="+motionCtr);
  Serial.println(msg);
  notifyBySMS(msg);

  //Start the siren only if motion is detected 2 times
  if(motionCtr==2){
    digitalWrite(SIREN,HIGH);
    Serial.println("Siren STARTED.");
    notifyBySMS("Siren STARTED.");
    call(CONTACT1);
//    call(CONTACT2);
//    call(CONTACT3);
  }
}

void stopSiren(byte manual){
  motionCtr = 0;
  Serial.println("Ctr="+motionCtr);
  digitalWrite(SIREN,LOW);
  if(manual){
    Serial.println("Siren STOPPED manually.");
    notifyBySMS("Siren STOPPED manually.");
  }else{
    Serial.println("Siren STOPPED");
    notifyBySMS("Siren STOPPED.");
  }
}

void sendSMS(String mobileNumber, String msg){
  Serial.println("Sending SMS to "+mobileNumber);
  //AT command for text mode of gsm module
  SMS.println("AT+CMGF=1");
  delay(100);
  SMS.println("AT+CMGS=\""+mobileNumber+"\"\r");
  delay(100);
  // the text you want to send
  SMS.println(msg);
  delay(100);
  // ASCII code of CTRL+Z
  SMS.println((char)26);
  delay(5000);
  Serial.println("SMS sent to "+mobileNumber);
}

void call(String mobileNumber){
  Serial.println("Calling..."+mobileNumber);
  SMS.println("AT+CMGF=0"); //AT command for PDU mode of gsm module
  SMS.println("ATD"+mobileNumber+";");
  delay(45000);
  SMS.println("ATH");
}

void notifyBySMS(String msg){
  sendSMS(CONTACT1,msg);
  delay(1000);
//  sendSMS(CONTACT2,msg);
//  delay(1000);
//  sendSMS(CONTACT3,msg);
//  delay(1000);
}

I am receiving the SMS from setup(). But I am not receiving the SMS that I have sent from interrupt routine. Also I am receiving the call only sometime, it is random. I guess this is because I am using delay() in interrupt routine.

How can I implement such logic without delay().


texts: Does the SPI library use the internal USART?

texts: I was reading the detailed datasheet for the ATmega328p and noticed that it has an option to use the built-in USART to drive the SPI interface. I just wondered if the arduino SPI library makes use of this? I suspect unlikely because I suppose that the USART is used by the USB on a arduino.


texts: What type of sensor could I use to determine the mass of a small object (under 1 kg)?

texts:
I'm building a robot that needs to pick up a piece of material and then determine its mass. My robot will retrieve the material using a scoop at the ended of a mechanized arm. Once the material is in the scoop, the arm will tilt upwards until the material slides down the arm and into the chassis.
I hope to weigh the material while its in the chassis, but I'm not sure how to do this. I've found that load sensors are useful for taking masses, but I'm not clear on how they're implemented. For example, I've found load beam cells, but how would I implement one in my design? Does it require a metal plate of some sort (like a weighing pan) on top of it like a laboratory scale? The sensor must be able to communicate with an Arduino.

My robot needs to be under 6 lbs and have a footprint of 35 x 35 cm. Thanks!


texts: Any Arduino device that records body data?

texts:
I'd like to conduct a research on transmitting body data like ECG from a device to a another device via Bluetooth.

Is there any any arduino device that allows to collect such data?

I've found this one online Cyton Biosensing Board but it's hella expensive, and not sure how to gather ECG data.

  The OpenBCI  Cyton Board is an Arduino-compatible, 8-channel neural
  interface with a 32-bit processor. At its core, the OpenBCI Cyton
  Board implements the PIC32MX250F128B microcontroller, giving it lots
  of local memory and fast processing speeds. The board comes
  pre-flashed with the chipKIT™ bootloader, and the latest OpenBCI
  firmware. Data is sampled at 250Hz.

  The OpenBCI Cyton Board can be used to sample brain activity (EEG),
  muscle activity (EMG), and heart activity (ECG). The board
  communicates wirelessly to a computer via the the OpenBCI USB dongle
  using RFDuino radio modules. It can also communicate wirelessly to any
  mobile device or tablet compatible with Bluetooth Low Energy (BLE).

Any light on this matter would be highly appreciated.

Edit

I want to integrate this arduino to my react native app via resbery pi.
I need to basically find a way to fetch ecg data from aduino which will have electrodes that is attached to body.


texts: Ideal settings for regulated power using Arduino Uno VIN?

texts:
Is there a downside to providing a lot of amps to Arduino UNO's VIN? Is there any advantage to only supplying a limited amount of amps? I have a regulated power supply and I'm curious what I should set it to when going through the 5v port?

Also, should I stick with 5 volts? I've seen some tutorials say if powering the board through VIN it should ideally be much more than that?

Is there a spec sheet of sort that tells you this?


texts: Discrete H-Bridge very low current output

texts:
I have built two parallel H-bridges from "Design 1" on this page as you can see in the attached schematic.

However when I apply the external power (VCC1 in the center of the diagram) the two motors do not spin.

Using my multimeter, I can see that the entire circuit is working: the motor is getting a 'forward' and 'backward' current as the Arduino sets the pins high. The multimeter is reading +/- 5.54V with the motor replaced by the multimeter. (Across the motor this drops to 0.13V)

So then I measure the current by putting my multimeter both in series with the motors and replacing the motors. There's only 40mA available! Looking around the web I found the suggestion to reduce the 220Ω resistors at R2, R3, R5 and R6. So I switched in (randomly) 27Ω resistors and the output current is still only 40mA.

What else should I try to bring up the current enough to drive the motors?

Edit: So my uneducated guess is that it's likely that the limitation is coming from the transistors. The Ns are BC549 and the Ps are BC559. The datasheets list "low current" as a feature, but I figured that was the collector.

Edit 2: The motor is this one which requires 70mA when running (and presumably more during startup)

Edit 3: Code driving the Arduino:

// Pin setup
int pinLeftMotorFwd   = 5;
int pinLeftMotorBck   = 6;
int pinRightMotorFwd  = 10;
int pinRightMotorBck  = 11;

// Directions for the {left, right} motors to achieve the four directions
int FORWARD[]   = {  1,  1 };
int BACKWARD[]  = { -1, -1 };
int RIGHT[]     = { -1,  1 };
int LEFT[]      = {  1, -1 };

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

    pinMode(pinLeftMotorFwd,  OUTPUT);
    pinMode(pinLeftMotorBck,  OUTPUT);
    pinMode(pinRightMotorFwd, OUTPUT);
    pinMode(pinRightMotorBck, OUTPUT);
}

void loop() {
    go( FORWARD, 10 );
    go( RIGHT,    3 );
    go( FORWARD, 10 );
    go( LEFT,     6 );
}

// Move the bot in a particular direction from the array above for a given number of seconds
void go ( int dir[], int dur ){
    leftMotor(  dir[0] );
    rightMotor( dir[1] );
    delay( dur * 1000 );
}

// Sill both motors (OK, so stop both motors. But stop is a keyword in C)
void still(){
    leftMotor(  0 );
    rightMotor( 0 );
}

// Set the left motor to Backward (-1), Forward (1), or Stop (0)
void leftMotor( int dir ){
    // Pull both pins low
    digitalWrite(pinLeftMotorFwd, LOW );
    Serial.println("pinLeftMotorFwd LOW");
    digitalWrite(pinLeftMotorBck, LOW );
    Serial.println("pinLeftMotorBck LOW");

    // If we're going forward, pull the Fwd pin high
    if( dir == 1 ){
        digitalWrite(pinLeftMotorFwd, HIGH);
        Serial.println("pinLeftMotorFwd HIGH");
    }

    // otherwise, pull the Bck pin high
    else if( dir == -1 ) {
        digitalWrite(pinLeftMotorBck, HIGH);
        Serial.println("pinLeftMotorBck HIGH");
    }
}

// Set the right motor to Backward (-1), Forward (1), or Stop (0)
void rightMotor( int dir ){
    // Pull both pins low
    digitalWrite(pinRightMotorFwd, LOW );
    Serial.println("pinRightMotorFwd LOW");
    digitalWrite(pinRightMotorBck, LOW );
    Serial.println("pinRightMotorBck LOW");

    // If we're going forward, pull the Fwd pin high
    if( dir == 1 ){
        digitalWrite(pinRightMotorFwd, HIGH);
        Serial.println("pinRightMotorFwd HIGH");
    }

    // otherwise, pull the Bck pin high
    else if( dir == -1 ) {
        digitalWrite(pinRightMotorBck, HIGH);
        Serial.println("pinRightMotorBck HIGH");
    }
}


texts: How to Segment Accelerometer Signal at idle points

texts:
I'm using an 3 axis Accelerometer(GY-521) to get the acceleration data and also the gyroscope to get the gyro data. I want to segment the signals at the idle points so that i can get the segmented signal at the idle points.

Is there any algorithm or example code that i could use to segment this kind of signal?

Any help would be appreciated.

Thank You.


texts: Help, I want to turn relay constantly on until a difference is detected, but triggered only one instead

texts:
Help, I want to use arduino to control relay for electricity, i get data from a sensor and when a value is detected it should be constantly on until another detection triggered again, i can get the program to work but triggered only once instead when it should be constantly turned on, here'e my code:

int Pinout = 13;

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

void loop() {
    int val = analogRead(A0);
    if (val <= 500) {
        digitalWrite(Pinout, LOW);
    }
    else {
        digitalWrite(Pinout, HIGH);
    }
}

the relay i am using is a chinese relay module with 3 pin and VCC and GND connected to external power supply, and INput pin to 13 digital pin Arduino and the relay is which i believed is Active LOW, and for analog read i am using moisture sensor


texts: I am making a CNC router from a dremel and 3-5 NEMA 17 steppers. I am really confused on how I can power all those motors. I am using a RAMPS 1.4 with Arduino Mega. I have a 2.4A USB power supply. Is that enough? If not, what is the minimum specs I need to ensure that I don't burn, blow, or under power anything? I am trying to get my hands on a ATX power supply.


texts: Global variables use to much space in the dynamic memory

texts:
I use two simple libraries (see 1, 2) I found online for my code on the Arduino Uno, unfortunately I also use ROS and all those libraries take away to much space, when I compile my code I get this error:

Global variables use 2,112 bytes (103%) of dynamic memory, leaving -64 bytes for local variables. Maximum is 2,048 bytes.

I shortened my Strings, but it was not enough. How can I change the code in the libraries to achieve less used memory?

I think I don't understand the concept of global variables completely. For example I changed all double variables in the libraries to float variables, but it did not change dynamic memory use at all. How can I use less memory?


texts:
I finally understand why people do not allocate memory when it comes to micro-controllers. The reason is because as you allocate different objects on the heap of various sizes and then you delete them you end up with holes. This is called heap fragmentation. Anyways I know what is heap fragmentation. I just want to know how it works. So that I know when I can use the new keyword to allocate memory and when not..
(1) To make things simple consider this example. Lets say my heap looks like this. The bottom numbers represent the addresses. In a real example I will be allocating structs with larger sizes but lets use bytes to make things simple.
0    0    0    0    0    0    0    0    0    0
1    2    3    4    5    6    7    8    9    10

(2)  I allocate a char with value 123 in memory. Now my heap looks like this
1    0   123   0    0    0    0    0    0    0
1    2    3    4    5    6    7    8    9    10

the first 2 bytes 1  0 store the size of the data being allocated followed by the byte 123 that has the actual value.
(3)  I allocate another char with value 111 in memory. Now my heap looks like this
1    0   123   1    0   111   0    0    0    0
1    2    3    4    5    6    7    8    9    10

(4) I delete the first object created on step 2 with value 123. It now looks like:
0    0    0    1    0   111   0    0    0    0
1    2    3    4    5    6    7    8    9    10

I now have a hole at the beginning (heap fragmentation)
Now my question is if I where to allocate another byte say 222 will it be allocated on the beginning like this?
1    0   222   1    0   111   0    0    0    0
1    2    3    4    5    6    7    8    9    10

Or will it be allocated at the end like this?
0    0    0    1    0   111   1    0   222   0
1    2    3    4    5    6    7    8    9    10

If arduino is smart enough to place that object at the beginning, then I will no be that afraid of using the new keyword as long as I am allocating objects of small sizes and never allocating to many of them.
Reason why I am asking this question is because I have a class Queue that I use in c++. Whenever I add an item to that queue it allocates the objects that I create. The objects that I pass to that queue are 10 bytes. The queue size is never larger that size 30. Will it be safe if that queue is constantly allocating (enqueing) and deleting (dequeing) items?

Edit
Sorry for the question I guess I asked this question when I should had done more research. Thanks to your comments and my previous question I now know that this only occurs when allocating memory of different sizes.


texts: config file for Arduino Uno installed on Raspberry PI

texts:
The Arduino code shown runs successfully. My problem is configuring the Arduino IDE so it fits within the Raspberry Pi window. The second image, the built-in serial port /dev/ttyAMA0, is produced. It is blank.

The Arduino Menu bar cannot be accessed. Therefore, the Tools button and other buttons for running the code are not available. The user can adjust the width of the Arduino IDE window but cannot move it around the screen or up or down.

The /boot/config file is setup up for a Adafruit 5" Backback monitor. No other app, Thonny Pi, or the terminal has these problems.

It appears to me that the config file needs some work. That is only a guess.

Any suggestions will be greatly appreciated.


texts: Are there any products based on Arduino that are sold by companies?

texts: Ok, Arduino is a good technology but is it used professionally? Is the quality good enough to be used for professional purposes?


texts:
I have an Arduino 328p (custom) and I can program it using a FTDI header.

However, when I power it from the FTDI using only the RAW (5V) and GND, it only executes simple programs (example blink). If in my sketch I attempt to use SPI for example, it will just get stuck.

If I power the arduino from the FTDI with the DTR pin connected, it will work just as expected for any sketch. I can even remove the DTR pin at this point and there will be no issue.

What could be the cause of this behavior?
Can it be an issue with optiboot fast start?

PS: FTDI is configured for 5V but VCC for the Arduino is 3.3V (I'm using the MCP1703 regulator). This means that the Arduino is powered by 3.3V but the RST pin will have 5V.
PPS: The Arduino is running at 16MHz


texts: Is it possible to find the time taken by millis?

texts:
The function millis would be running in the span of 100+ microseconds or less. Is there a reliable way to go about measuring the time taken by a single millis call?

One approach that comes to mind is using micros, however, a call to micros will include the time taken by the function call of micros itself as well, so depending on how long micros takes, the measurement for millis may be off.

I need to find this as an application I am working on requires accurate time measurements for every step taken in the code, including millis.


texts: Looking for an existing lightweight RF protocol

texts:
I'm currently looking for an RF protocol that doesn't use much power (generally much less than wifi) Something similar to simple AM radio, but with an authentication library readily available. ZigBee has about 250kbps bandwidth. I don't need nearly as much, so something with ~5kbps (dial-up speeds) would be acceptable. Using the Arduino Yun; so i'm constrained to the 5V output.
I'm also trying to stay away from the 2.4 GHz band.

Is there anything out there with this in mind? I was thinking maybe Z-Wave?

As far as the ZWave chips go this is where i'm at: http://pastebin.com/B0Yif3LS


texts: Pro micro Wire.endTransmission() does not return

texts:
I have an Arduino Pro Micro(blue version) and I'm having trouble using the I2C. To test it, I use the code below and the result is an infinite square wave on SCL and SDA lines and I only get the number 1 on the terminal output. I have pullup resistors on both wires, 2k each.
Since the board uses an ATMEGA32U4, I tried the same code on a bare MCU and the code works as expected. The difference between the two is the bootloader type. The bare PCB is flashed over USB, using the factory bootloader(ATMEGA32U4-AU, QFP44).
By debugging the code, I found out that endTransmission does not return.
Does anyone have an idea, why the I2C is not working as expected on the Pro Micro module?
Thanks!
#include <Wire.h>

void setup() {
  Serial.begin (115200);
  // Leonardo: wait for serial port to connect
  while (!Serial)
    {
    }
  Serial.println ();
  Serial.println ("I2C scanner. Scanning ...");
  byte count = 0;
  Wire.begin();
}  // end of setup

void loop() {
  byte count = 0;
  for (byte i = 1; i < 120; i++)
  {
    Serial.println(i);
    Wire.beginTransmission (i);
    Wire.endTransmission ();
    delay(10);
  }
}


texts: How to find the MAC address using NodeMCU when connecting to WiFi?

texts:
I am new to using NodeMCU and IOT. I am testing the NodeMCU (ESP8266) so that I can connect with pubnub server. Have taken code from github but there is error saying

'mac was not declared in this scope'

and some other error too.

Can anyone tell whats the problem?

This code is from pubnub github page - https://github.com/pubnub/arduino

Code:-

#include <Ethernet.h>

#include <PubNub.h>

void setup() {
    /* For debugging, set to speed of your choice */
    Serial.begin(9600);

    /* If you use some other HW, you need to do some other
       initialization of it here... */
    Ethernet.begin();

    /* Start the Pubnub library by giving it a publish and subscribe
       keys */
    PubNub.begin(publisher key, subscriber key);
}

void loop() {
    /* Maintain DHCP lease. For other HW, you may need to do
       something else here, or maybe nothing at all. */
    Ethernet.maintain();

    /* Publish message. You could use `auto` here... */
    PubNonSubClient *pclient = PubNub.publish(pubchannel, "\"message\"");
    if (!pclient) return;
    PublishCracker cheez;
    cheez.read_and_parse(pclient);
    /** You're mostly interested in `outcome()`, and,
        if it's "failed", then `description()`.
    */
    Serial.print("Outcome: "); Serial.print(cheez.outcome());
    Serial.print(' '); Serial.println(cheez.to_str(cheez.outcome()));
    Serial.print("description: "); Serial.println(cheez.description());
    Serial.print("timestamp: "); Serial.println(cheez.timestamp());
    Serial.print("state: "); Serial.print(cheez.state());
    Serial.print(' '); Serial.println(cheez.to_str(cheez.state()));
    pclient->stop();

    /* Wait for news. */
    PubSubClient *sclient = PubNub.subscribe(subchannel);
    if (!sclient) return; // error
    String msg;
    SubscribeCracker ritz(sclient);
    while (!ritz.finished()) {
        ritz.get(msg);
        if (msg.length() > 0) {
            Serial.print("Received: "); Serial.println(msg);
        }
    }
    sclient->stop();

    delay(1000);
}

error :-
  sketch_jan17a:28:47: error: 'pubchannel' was not declared in this scope

     PubNonSubClient *pclient = PubNub.publish(pubchannel, "\"message\"");

                                               ^

sketch_jan17a:44:46: error: 'subchannel' was not declared in this scope

     PubSubClient *sclient = PubNub.subscribe(subchannel);

                                              ^

Multiple libraries were found for "Ethernet.h"
 Used: C:\Users\sultan\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0-beta2\libraries\Ethernet
 Not used: C:\Program Files (x86)\Arduino\libraries\Ethernet
exit status 1
'mac' was not declared in this scope


texts: How to restart void loop if condition is met

texts:
This should be a quick question.

I'm trying to figure out how I can restart void loop() if a certain condition is met. In this instance, if (s>10), I want the loop to restart. Any help will be appreciated.

 void loop() {

  if (getDistance(0) == true)                   //if the car passed the first sensor
  {
    while (getDistance(0) == true && getDistance(1) == false);
    unsigned long currentMillis = millis(); //time when the passed the first sensor

    while (getDistance(1) == true && getDistance(0) == true); //wating car to pass the second sensor

    unsigned long endMillis = millis(); //time at which the car passed the second sensor

    unsigned long timeMillis = endMillis - currentMillis; //get duration in ms
    float timeSeconds = timeMillis / 1000.0; //because 1000ms = 1s

    float s = sensorDistance / timeSeconds; //speed = distance / time

    if(s>=7 && s<=10) // for red to turn on
    {
    Serial.print(s); // printing the speed magnitude
    Serial.print(" m/s");// printing the units of speed
    Serial.println(); // new line in printing

    char msg[2] = {'h','#'}; // sending some random message to indicate that speed is greater than 10
    digitalWrite(led_pin, HIGH); // Flash a light to show transmitting
    vw_send((uint8_t *)msg, 2); // sending a message
    vw_wait_tx(); // Wait until the whole message is gone
    digitalWrite(led_pin, LOW); // again bringing the flash light to low

    }
    else if (s<7)
    {
    Serial.print(s); // printing the speed magnitude
    Serial.print(" m/s");// printing the units of speed
    Serial.println(); // new line in printing

    char msg[4] = {'h','e','l','#'}; // sending some random message to indicate that speed is greater than 10
    digitalWrite(led_pin, HIGH); // Flash a light to show transmitting
    vw_send((uint8_t *)msg, 4); // sending a message
    vw_wait_tx(); // Wait until the whole message is gone
    digitalWrite(led_pin, LOW); // again bringing the flash light to low
    }

    delay(2000);
  }
}


texts: Help Troubleshooting L298n connected to dc motor

texts:
I am relatively new to Arduino, and I am trying to power a DC motor with the L298N dual H-Bridge. I have done as follows:
I am powering everything with the Arduino that is connected to the PC. (I know this isn't ideal, but I don't have a better power supply yet)
I connected the 5V output from Arduino to the 12V terminal of the L298N, and connected it to the Arduino ground. The red light from the L298N shines brightly.
Then, I connected the IN3 and IN4 pins to the Arduino digital pins 7 and 8, respectively.
Finally, I connected the Out 3 and Out 4 to my DC motor, but it doesn't turn at all. I use the following code:

int In3=7;
int In4=8; //idem para In2

void setup() {
  pinMode(In3,OUTPUT); //avisa que nuestros pines son todos outputs
  pinMode(In4,OUTPUT);

  digitalWrite(In3,HIGH);
  digitalWrite(In4,LOW);
}

void loop() {

}

For the time being I decided to not use the PWM, so that I can start simple. I tried changing all cables and even the motor, but it just won't rotate. The L298N is brand new, so it's unlikely that it is damaged. What could I try next?


texts: Adeept Arduino Mega 2560 isn't recognized

texts:
So recently, I purchased an Arduino Mega 2560 Kit from Amazon, which was customized from this company called Adeept. But when I tried to plug it into my computer, it didn't recognize it. This means my device manager didn't change in any way, shape, or form. The Arduino IDE that I fully downloaded couldn't upload code, and I also tried using different USB cords, and I tried using another computer as well, but it still didn't work.
Is there a driver that I need to upload or something else that I'm missing?
Thank you for your time :)


texts:
So I know that millis() doesn't work how it's suppose to if you use it in an interrupt but lets say we have a code that looks like below, will millis() work properly or how it behaves in an interrupt? Do I need to use the delay() instead of millis() when I'm outside of void loop() ?

To clarify, I understand how millis() behaves in an interrupt and why delay() doesn't work in an interrupt.

const int ledPin =  LED_BUILTIN;// the number of the LED pin

// Variables will change:
int ledState = LOW;             // ledState used to set the LED

// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store
unsigned long previousMillis = 0;        // will store last time LED was updated

// constants won't change:
const long interval = 1000;

void setup() {
 pinMode(ledPin, OUTPUT);
}
void loop(){
blink();
}
void blink(){
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);
  }
}


texts: How to add indicator lights to button sketch

texts:
I would like to add leds to each button switch in the first code, The first code sends midi messages to a DAW I would like it to also turn on a led as an indicator light. The switch needs to turn the light on if off and off if on. The second code is an example that does this, it works well with one button. I would like to have the 3 buttons on pins 0, 1, 2 and the leds on pins 3, 4, and 5.

#include <Bounce.h>

const int channel = 1;
Bounce button0 = Bounce(0, 5);
Bounce button1 = Bounce(1, 5);
Bounce button2 = Bounce(2, 5);

void setup() {
  pinMode(0, INPUT_PULLUP);
  pinMode(1, INPUT_PULLUP);
  pinMode(2, INPUT_PULLUP);
}
void loop() {
  button0.update();
  button1.update();
  button2.update();

  if (button0.fallingEdge()) {
    usbMIDI.sendNoteOn(60, 99, channel);  // 60 = C4
  }
  if (button1.fallingEdge()) {
    usbMIDI.sendNoteOn(61, 99, channel);  // 61 = C#4
  }
  if (button2.fallingEdge()) {
    usbMIDI.sendNoteOn(62, 99, channel);  // 62 = D4
  }

  if (button0.risingEdge()) {
    usbMIDI.sendNoteOff(60, 0, channel);// 60 = C4
  }
  if (button1.risingEdge()) {
    usbMIDI.sendNoteOff(61, 0, channel);  // 61 = C#4
  }
  if (button2.risingEdge()) {
    usbMIDI.sendNoteOff(62, 0, channel);  // 62 = D4
  }
  while (usbMIDI.read()) {
  }
}

Second sketch:

/*********************
Simple toggle switch
Created by: P.Agiakatsikas
*********************/

int button = 0;
int led = 13;
int status = false;

void setup(){
  pinMode(led, OUTPUT);
  pinMode(button, INPUT_PULLUP); // set the internal pull up resistor, unpressed button is HIGH
}

void loop(){
//a) if the button is not pressed the false status is reversed by !status and the LED turns on
//b) if the button is pressed the true status is reveresed by !status and the LED turns off

if (digitalRead(button) == true) {
  status = !status;
  digitalWrite(led, status);
} while(digitalRead(button) == true);
  delay(50); // keeps a small delay
}


texts: Does RFID-RC522 supoort tk4100 chip protocol ISO18000-2C 10 digital ID card?

texts:
I have ordered a starter kit and received RFID reader is

  RFID-RC522

module with one card and tag now I need more RFID card for my project and I can't find the supported card type for my project please can any one tell me supported card types and if this card supports my device this is the card type

  tk4100 chip protocol ISO18000-2C 10 digital ID number


texts: How to chose softserial library use on Arduino project?

texts:
I want to do a project that has multiple Arduino communication through UART, that project project one of limit is using Arduino Nano (small and cheap). I need to set 4 serial port instance on Nano to connect other nano to receive and write, I searched about serial port of nano that only have one hardware serial port, so after I found the many softserial library such as pre-bulite softserial and altsoftserial NeoSWSerial and NeoHWSerial and NeoICSerial.
Because library too libraries i don't know which one can help complete my project.


texts:
This is my code which I have written as a library

#include "avr/interrupt.h"
#include "Arduino.h"
#include "AllTimer.h"

AllTimer::AllTimer()
{}

void AllTimer::dofun(void)
{
     //TIFR1 |= _BV(OCF1A);

    TCCR1B = 0X00;
    //TIFR1 = 0X01;
    digitalWrite(13,!digitalRead(13));
    Serial.print("I printed");
    TCNT1 = 0X0000;
    TCCR1B |= (1<<CS12) && (1<<CS10);
    //sei();
}

 void AllTimer::setTimer(void)
 {
    TCNT1 = 0x0000;
    TCCR1A = 0x00;
    TCCR1B = 0x00;
    TCCR1B |= (1<<CS12) && (1<<CS10);
    TIMSK1 |= (1<<TOIE1);
    sei();
 }

ISR (TIMER1_OVF_vect)
{
     AllTimer::dofun();
}

Code in Arduino IDE:

 #include <AllTimer.h>

 AllTimer mytimer;

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

 void loop()
 {
     mytimer.setTimer();
    //delay(200);
  }

But I am not getting anything on the serial monitor. What is the error I have made?


texts:
A brief description of what I'm doing here. I wanna make a pet project, basically a device (be it Arduino or raspberry pi) that I can connect to via bluetooth / wifi (both preferably), that will be connected to a stereo system and allow me to play music. I essentially want to make a wireless sound system in my house.

My question is, is raspberry pi more adequate for my needs? Or would arduino get the job done? I know that raspberry pis are essentially mini computers, so I feel that the raspberry pi would be too much, since all I really need to do is design a bluetooth / wifi interface and send the signal to the aux cable connected to the stereo.

Any help would be really useful here. I've never worked with either/or, and this is my first project with Arduino / Raspberry pi (hello world). Thanks in advance.

EDIT: In response to comments below, a greater idea of what I want to do:

I want to design an item that will appear on local wifi as a sound device. i.e. on an imac / macbook I'd be able to right click on the speaker icon in the upper right and select it there). From there, I'm hoping to stream audio to the device, and have it play to a stereo that the arduino / raspberry pi would be connected to. I'd love to make this universal (i.e. possible to connect via your android phone / a windows machine), but I can imagine that part being a lot more difficult. I'd also like to add bluetooth functionality at some point, but that'd be in the future. Hopefully this gives everybody more of an idea of what I'd like to achieve here! I appreciate all the help so far.


texts: Include Adafruit_RGB LCD Shield library in class

texts:
I'm trying to make a class to expand on the functionality of the Adafruit-RGB-LCD-Shield-Library I'm creating this based on what I see from this post.
class LcdMenu
{
 #include <Adafruit_MCP23017.h>
 #include <Adafruit_RGBLCDShield.h>
 public:
 Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield();
     void Setup()
     {
      lcd.begin(16, 2);
     }
     void Write(int line, char text[17])
     {
      lcd.clear();
     }
};

LcdMenu *LcdM;
#define VIOLET 0x5

void setup()
{
  LcdM->Setup();
  LcdM->lcd.setBacklight(VIOLET);
}

However, I'm getting the following error:

C:\Users\jschere2\AppData\Local\Temp\ccUzvCmX.ltrans0.ltrans.o: In function `main':
ccUzvCmX.ltrans0.o:(.text.startup+0xf0): undefined reference to `LcdMenu::Adafruit_RGBLCDShield::begin(unsigned char, unsigned char, unsigned char)'
ccUzvCmX.ltrans0.o:(.text.startup+0xf8): undefined reference to `LcdMenu::Adafruit_RGBLCDShield::setBacklight(unsigned char)'
collect2.exe: error: ld returned 1 exit status
exit status 1
Error compiling for board Arduino/Genuino Mega or Mega 2560.


texts:
This question is somewhat similar to How to pass non-static class member to callback?, but there are a few differences, especially since a lot of my uses have "interesting" additional complexities. I'd like to understand better my options in using them, since I have not gained enough understanding from other answers (and I need to write both the callback and the function that calls it).

I have a number of libraries that produce "events" that I'd like to be able to write separate classes or functions to respond to (so I don't need to customize every library every time I develop something). The annoying part is that I've long-since discovered the this pointer that's hidden in class method calls, which prevents me from passing currentgui.leftbutton as a function to menu.leftbuttonpressed(void (*callbackfuncptr)(void)).

I'm also using the ESP8266 web server library, which needs a callback in the context of the server object that can call the server as a global to actually get the data sent to it! (Unless the server passes its own this as a parameter to the callback, which I don't know since the documentation consists almost solely of a small number of "examples" which don't show the majority of the actual features of the web server, rather than a real explanation.)

I could use some variant of a pointer to a class method, but the syntax for that is eye-gouging and I'm using more than one class to provide callbacks to (especially for the task scheduler), so this would require customizing the library to handle pointers to every class I use again. I can't use polymorphism, either, since some classes contain multiple scheduler callbacks to be done on different times/conditions.

How do I handle these callbacks? My current method is to write a function that wraps the method's function, but that relies on a specific instance of that method, so it can't be reused. It's also really awkward since I'm now dealing with multiple functions/methods that are now very similar.

I would also like to be able to have a class, that when passed a web server object, registers itself as a callback to a particular page event (I want to write a network connection manager similar to the WiFiManager library, but with the ability to integrate with an existing webpage. I have all the code, but it currently can't be nicely integrated into a standalone class because of this issue). It needs to store a pointer to the server object to get the data once the callback's called, but it also needs to be attached to the callback of the class that holds that particular pointer AND the other handler functions once the data's retrieved.
There is already a library that does something similar, but I can't figure out at all how this works, since I was under the impression that this is not possible. Can someone help me understand how the following class operates?
https://github.com/esp8266/Arduino/tree/master/libraries/ESP8266HTTPUpdateServer/src


texts: How to purge incoming Xbee packets from the buffer?

texts:
I have a need to receive a specific confirmation packet after commanding my transmitting Xbee to stop sending normal packets.

My buffer still has normal packets in it when this happens, so next time I call readPacket(), I don't want to see them. So right before I call my stop command, I try to purge the incoming buffer like this:

void burnSerial(void) {
  while (xbee.readPacket(20)) {
    xbee.getResponse().getRx16Response(rx16);
  } //read all available responses
    // only do this when not in a constant stream of responses or it may hang.

  while (Serial.available()) { Serial.read(); }
  //burn whatever may be in serial buffer
}

But this doesn't work. The next time I call xbee.readPacket(), I see tons of normal packets before I finally see my confirmation packet. Why don't these functions do anything for me at all?


texts: How to use an Arduino Uno + Keyboard Firmware to make a "N Key Rollover" Game Pad

texts: Hello I have flashed my Arduino Uno with USB keyboard firmware from this tutorial http://mitchtech.net/arduino-usb-hid-keyboard/#comment-6786, and I have been successful sending individual key presses but, not when trying to press an hold a key. I am attempting to use this firmware to create a custom Game Pad to USB adapter, the only issue is sending simultaneous keystrokes (not sending them one at a time). If you know how to accomplish this task I would be very happy. The technical term for this is "Key Rollover"


texts:
I'm trying to pass variable addresses to functions/methods within a custom library that should change the values at the specified addresses.  However, I think I'm missing something as it's taking me ages to tweak things just to get it to compile, let alone gather some useful information from it.

Note:
I've not tested the code as I'm focused on understanding (1.) through to (5.) and is just a quick example of the current pipeline:

Main.ino

#include <customLibrary.h>

CustomLibrary cLib();

byte someByte[6];
unsigned int theAddress;

setup(){};

loop(){

    // (1.)
    theAddress = &someByte; // normally need this here, or before setup(), for it to work.

    cLib.setValues(theAddress);

    // because:
    // cLib.setValues(&someByte);
    // doesn't seem to work
};

customLibrary.h

#ifndef CustomLib
#define CustomLib
#if(ARDUINO > 100)
    #include "Arduino.h"
#else
    #include "WProgram.h"
#endif

class CustomLibrary {
    public:
        CustomLibrary();
        void setValues(unsigned int theAddress); // (2.)
    private:
};
#endif

customLibrary.cpp

#include <customLibrary.h>

CustomLibrary::CustomLibrary(){
};

void CustomLibrary::setValues(unsigned int theAddress){ // (3.)

    byte _someNewValues[6] = {a,b,c,d,e,f};

    // Assign the variable from _someNewValues[_x] to (theAddress + _x)
    int _x = 0;
    for(unsigned int i = theAddress;i < (theAddress + 6);i++){ // (4.)
        // (5.)
        _x++;
    };

};

(1.) - Feels like it should be simpler.

(2-3-4-5.) - I have left out any "*" and "&" hoping that someone can provide the preferred way of doing this, or provide a better solution as it's taking far too long to get this working with everything else leading me to think I'm missing something basic.

There are some excellent tutorials out there which I have been
following with great success, but, only when all the pointers are within the same file.  Once I try and use them in a library it's a constant headache at the moment and I don't understand it enough to know what's wrong.

Need to go before I can proof-read and check it, but I think it's all there.  I'll be back later/tomorrow if there's anything that needs clearing up.

Edit:
I didn't know who to mark for the answer as both @dannyf and @KIIV answered perfectly.  I considered marking the answer based on the time it was posted, but decided instead to let @dannyf have it as his reputation was only 1.

Thank you both! Much appreciated!


texts: Getting the voltage of an 18650 battery with an Arduino

texts:
I'm using a Arduino Pro Mini (5v) to sense the voltage of an 18650 battery. The battery (that is being sensed)is also used to power the Pro Mini but the MCU is behind a boost-converter which outputs 5.05v. Would I be able sense the right voltage of the battery?

simulate this circuit – Schematic created using CircuitLab

The boost converter has an input voltage ranges to 0.9 to 5 volts and current of 600mA.


texts:
I have an HM-10 BLE module connected to Arduino Leonardo. It forwards UART from my computer:

#define btSerial Serial1

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

    while (!Serial) {
        delay(50);
    }

    Serial.println("Initialized on 9600");

    btSerial.begin(9600);
    while (!btSerial) {
        delay(50);
    }

    Serial.println("BT initialized on 9600");
}

void loop() {
    if (btSerial.available()) {
        Serial.write(btSerial.read());
    }

    if (Serial.available()) {
        btSerial.write(Serial.read());
    }
}

In general, it works fine, but I've decided to flash it and sent AT+SBLUP command to it, and it's in flash mode now.

Later I've realized that I can't flash it because Parallels Desktop's COM forwarding does not work fine (I work on macOS).

And now I can't quit from the flash mode — it just does not respond to AT commands (however, btSerial is alive).

I've tried to reset the Arduino, disconnect BT for several minutes — it's still in flash mode. How to quit this mode?


texts: Why are my thermistor readings backward?

texts:
I'm trying to build a thermistor that will flash an LED when the temperature is above 30 C. My set-up appeared to be reporting the room temperature correctly to the Serial Monitor, but then I noticed that exposing the thermistor to a hot object causes the reported temperature to drop, whereas exposing it to a cold object causes the reported temperature to rise.

I'd built a simpler thermistor circuit earlier with a similar approach and everything seemed to function correctly. I'm not sure what I broke here:

const int WarningLED = 7;
const int Thermistor = 0;

/* Thermistor information:
 * P/N: BC2301-ND
 * MFG P/n: NTCLE100E3103JB0
 * DESC: THERMISTOR NTC 10KOHM 3977K BEAD, IDX: 1 */

int Vo; // voltage between thermistor and R1
float R1 = 10000; //10 KOHM resistor used for voltage divider
float TR; // resistance of negative temperature coefficient (NTC) thermistor
float beta;  //beta will later equal ln( TR / Rref )
float Tk, Tc, Tf;

/* Steinhart-Hart equation coefficients via data table at
 * http://www.vishay.com/docs/29049/ntcle100.pdf
 * Bead used: 3977K (refer to #9 values on Nominal R table) */
float A = 3.354016e-03,B = 2.569850e-04;
float C = 2.620131e-06,D = 6.383091e-08;

void setup() {
  pinMode(WarningLED, OUTPUT); //sets the warning LED pin as a digital output
  Serial.begin(9600);          //  setup a serial port to enable comms with the computer.
 }

void loop() {

  Vo = analogRead(Thermistor);
  Serial.print("Vo: ");
  Serial.print(Vo);
  Serial.println(" mV");

  //Voltage divider equation: R2 = R1 * [Vo / (Vi - Vo)]
  //where R2 = TR, Vi = 1023.0 :
  TR = R1 * ((float)Vo / (1023.0 - (float)Vo));
  Serial.print("Thermistor resistance: ");
  Serial.print(TR);
  Serial.println(" ohms");

  beta = log(TR/10000); // As per extended Steinhart-Hart equation,
  //  where Rref = 10,000 (refer to page 10 of the PDF linked above)
  Tk = (1.0 / (A + B*beta + C*beta*beta + D*beta*beta*beta));
  Tc = Tk - 273.15;
  Tf = (Tc * 9.0)/ 5.0 + 32.0;

  Serial.print("Temperature: ");
  Serial.print(Tk);
  Serial.print(" K; ");
  Serial.print(Tf);
  Serial.print(" F; ");
  Serial.print(Tc);
  Serial.println(" C");
  Serial.println();

  if (Tc > 30.0) digitalWrite(WarningLED, HIGH);
  else if (Tc < 30.0) digitalWrite(WarningLED, LOW);
  delay(1000);
}

On the Serial Monitor, this reports:

Vo: 550 mV
Thermistor resistance: 11627.91 ohms
Temperature: 294.74 K; 70.86 F; 21.59 C

Exposing this to a warmer temperature incorrectly reports:

Vo: 597 mV
Thermistor resistance: 14014.08 ohms
Temperature: 290.61 K; 63.43 F; 17.46 C

I notice that, among other issues, this is reporting increased resistance in the thermistor despite that I'm using an NTC, but I'm not sure why this is occurring.

Notable parts used in this circuit:

Thermistor: NTCLE100E3103JB0
R1: 10 KOHM
R2: 1 KOHM
C1 & C2: 33 nf


texts: SOLVED -- Switch PIN, Also Trigger Other Pin in Arduino

texts:
I would like to know.

I have Pin 6, 7, 8 and 9 as INPUT_PULLUP. I have switch to each other pin. Why when I press switch at PIN 6. SOMETIMES PIN 7 also getting input. Other case, also when I press switch at 7, other pin also trigger. Why?

This case is random. Sometimes everything is ok when I press 10 times, but after that other pin also trigger. Another case only 4-5 times press, then other pin also trigger.

I use switch on/off not temporary switch.

How to fix this? Is it common problem with arduino?

UPDATE

Program. (Simple Program)

int led1 = 1;
int led2 = 2;
int led3 = 3;
int led4 = 5;

int switch1 = 6;
int switch2 = 7;
int switch3 = 8;
int switch4 = 9;

int led = 13;

//int counter = 0;

void setup()
{
  // put your setup code here, to run once
      pinMode(led1, OUTPUT);
      pinMode(led2, OUTPUT);
      pinMode(led3, OUTPUT);
      pinMode(led4, OUTPUT);
      pinMode(switch1, INPUT_PULLUP);
      pinMode(switch2, INPUT_PULLUP);
      pinMode(switch3, INPUT_PULLUP);
      pinMode(switch4, INPUT_PULLUP);
      pinMode(led, OUTPUT);
}
void loop()
{

if (digitalRead(switch1) == 0){
  digitalWrite(led1, HIGH);
  }

 if (digitalRead(switch1) == 1){
  digitalWrite(led1, LOW);
  }

if (digitalRead(switch2) == 0){
  digitalWrite(led2, HIGH);
  }

 if (digitalRead(switch2) == 1){
  digitalWrite(led2, LOW);
  }

if (digitalRead(switch3) == 0){
  digitalWrite(led3, HIGH);
  }

 if (digitalRead(switch3) == 1){
  digitalWrite(led3, LOW);
  }

if (digitalRead(switch4) == 0){
  digitalWrite(led4, HIGH);
  }

 if (digitalRead(switch4) == 1){
  digitalWrite(led4, LOW);
  }

digitalWrite(led, HIGH);

delay(1000);

digitalWrite(led, LOW);

}

Schematic

My Circuit is simple as like that for the input. For the output only to led, resistor and ground.

I found similar case http://www.instructables.com/id/Arduino-Push-Switch-Debouncing-Interrupts/

  On the website, He said, "The problem with this setup was when the
  button was pressed the interrupt was being called multiple times and
  even toggling other buttons. Why was this happening? It is caused from
  a switch bouncing feedback."

Is there any solution without modifying the hardware?

SOLVE

The problem is the wire.

My wire for switch is jumper cable, and each other closer (touch) to each other cable. I try to separate, and works. There is no other pin will be trigger.


texts: Stepper not working properly using L298N

texts:
If googled and search here but can't find the same issue.
I'm using an Arduino Uno, L298N driver (5v jumper is off - actually just 2 holes where the jumper pins were supposed to be), scavenge stepper motor from a 5 inch drive - TEAC P.no. 14769070-90 (we call it a floppy drive). I used the example from the Arduino IDE that spins the stepper in on direction and then the other.
The stepper motor has a 5 wire ribbon and with an LED test showed that the out side two wires are a pair. I've look at schematics for the 5 wire, I know it's got to do with the uni/bi polar of the motor but I have no idea if I need to connect this middle wire?
I've wired it according to this Maker Guides article
The issue is that in the clockwise direction it is very weak and it just vibrates in the anti-clockwise direction.
How do I go about diagnosing the issue?
(I'm on a beginner level with regards to hw. Sw engineer with a Solder iron - very dangerous)


texts: Can the sf::Packet class of SFML-network be ported over to arduino for use with the Ethernet library or would it be too big? I'm working on a client-program where an arduino is a server and a regular computer is the client making a request. I'm using the SFML-network library to make networking easier on myself and would prefer to use the built in features of SFML to make networking easier. If it is not feasible would I be better off using fixed width data to communicate with the arduino


texts: How do I set a continuous servo to turn on until a switch is flicked?

texts:
I am trying to get a servo to be activated by a momentary button. The arm on the servo will then swing around, which then activates a toggle switch. The activation of this toggle switch will then reverse the direction of the servo making the arm swing back. When the arm gets to the centre of the box, the other end of the arm will then turn the toggle switch the other way, which will then tell some Arduino code to turn the servo off.

Here is the schematic:

Here is my code:

#include <Servo.h>
Servo servo1;

int button = 2; //Assigning pin 2 for the momentary button
int buttonval = 0; //Creating a variable for the buttons value
int green = 12;
int red = 13; //Assigning the green and red LED to pin 12 and pin 13
int red = 13;
int Closed = 8; //Assigning the Inputs of the toggle switch to 8 and 7
int Open = 7;
int Closedval = 0; //Creating two blank variables for the states of the switch
int Openval = 0;

void setup() {
  servo1.attach(4); //Assigning the data pin for the servo
  servo1.write(1); // Giving a starting speed to the servo
  pinMode(button, INPUT); // Setting up the input pin for the momentary button
  digitalWrite(button, HIGH); //  turn on pull up resistors
  pinMode(Closed, INPUT); //Setting up the inputs for the two states of the toggle switch
  pinMode(Open, INPUT);
  pinMode(green, OUTPUT); //Changing the pin modes to OUTPUT for the two LEDS
  pinMode(red, OUTPUT);
  digitalWrite(Closed, HIGH);
  //Turning on pull up resistors for the two inputs from the toggle switch
  digitalWrite(Open, HIGH);
}

void loop() {
  Closedval = digitalRead(Closed); //Assign 'Closedval' to the value of Closed
  Openval = digitalRead(Open); //Assign 'Openval' to the value of Open

  if (Closedval == HIGH) {
    servo1.write(180);
    // If 'Closedval' is 'HIGH' then change the servo to 180 (make the servo go anticlockwise)
  }

  if (Openval == HIGH) {
    servo1.write(86);
    // If 'Openval' is 'HIGH' then change the servo to 86 (stop the servo)
  }

  digitalWrite(red, Closedval); // Change the value of the Red LED to Closedval
  digitalWrite(green, Openval); // Change the Value of the Green LED to Openval
}

Any help would be appreciated.


texts:
I am having difficulty with setting up websockets using the Arduino IDE with an ESP8266 ESP8266 Websockets problem and I have added WiFi.printDiag(Serial) to the main loop of my code. The Output I get (with my comments added) is

14:34:03.325 -> DIAGNOSTIC INFO   Debug Comment I added
14:34:03.325 ->
14:34:03.325 -> Mode: AP          Presume this means ESP is in AP mode
14:34:03.325 -> PHY mode:N        XXX
14:34:03.325 -> Channel: 1        Presume this means AP is on channel 1
14:34:03.325 -> AP id: 0          XXX
14:34:03.325 -> Status: 255       XXX
14:34:03.325 -> Auto connect: 1   XXX
14:34:03.325 -> SSID (0):         XXX
14:34:03.325 -> Passphrase (0):   XXX
14:34:03.325 -> BSSID set: 0      XXX

The AP is setup and I can see it in WiFI Analyser on my phone.
Is there a reference somewhere that explains the lines with XXX in them, or can
someone suggest meanings? Thanks


texts:
In this arduino project we have 3 Leds that lights up according to the voltage of a battery but when we the voltage read is very close, it results into an uncontrolled switching between  Leds  can any one help me ?

int Batpin = A0;
int Led1  = 12;
int Led2  = 11;
int Led3 = 10;

void setup() {
  // put your setup code here, to run once:
  Serial.begin (9600);
  pinMode(Led1,OUTPUT);
  pinMode(Led2,OUTPUT);
  pinMode(Led3,OUTPUT);

}

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

void volt(){
int sensorVal = analogRead(Batpin);
float voltage = sensorVal * (5.0/1023.0);

 Serial.print(" volt: ");
 Serial.println(voltage);
 if (voltage < 3.80){
     digitalWrite(Led1,HIGH);
  }

   if (voltage > 3.80 && voltage <= 4)
   {
      digitalWrite(Led1,LOW);
      digitalWrite(Led2,HIGH);
   }

   if (voltage > 4)
   {
      digitalWrite(Led1,LOW);
      digitalWrite(Led2,LOW);
      digitalWrite(Led3,HIGH);
   }
   delay (1000);
}


texts: Multiple RGB led strips with Uno - options?

texts:
I know there's quite a few threads with similar answers already, but I hope you won't mind me asking anyways. One thread has what looks like a good solution but it's old and thought it may be better to ask fresh.

I have ten 12v rgb strips with 4 wires each, a 12v power supply and 30 mosfets. I want to control them individually with an Uno.

I'd like to make a wave effect where the strips increase and decrease in brightness at separate times. It's fine if they are all the same color during a wave. Then a wave of a different color.

(1) I'm thinking of trying the approach in this thread where AMADANON suggests using 3 pins for the color and then each strip gets its own common pin, 13 pins in my case. If I go this route, will I be able to set a color for all strips and a brightness for individual strips? This would let me make the wave effect I'd like.

(2) Alternately I'm thinking of upgrading to a Mega with 54 pins. I assume I could then control each strip individually using 3x10 = 30 pins?

(3) I've read lots of advice on chips to control the strips, but I'm a newbie and would like to keep it as simple as possible (plus delivery to my country takes 3 weeks or more, and I'd like to get started now)

Thanks for any advice!

EDIT:
(I replied to answers in comments, and I now see I should just instead edit this question. Thanks for your patience with a newbie!)

The mosfets are N-Channel MOSFET 60V 30A.

The led strips are rgb non-addressable with 4 wires, wired on both ends so they can be easily daisy-chained. But in my project the strips are snaking around some tracks and connected them in serial poses a problem. I'd prefer to wire each from only one end.

I think I'll try Gerben's and Andrew's advice about a chip and check out PCA9685 chip module as per Andrew's suggestion. Sounds inexpensive!

chrisl's suggestion for using WS2811 chips sounds easy too and maybe less wiring. In the same vein was an idea from this thread from gre_gor:

Setting 10 RGB Strips Independently from Single Arduino

... which talks about chainable STM32 rgb chips, only about 2 bucks on ebay, no mosfets, and pretty efficient.

Thanks for all the advice guys! I'm finishing the box and strips placement now and waiting for my Arduino to arrive which should be any day. This is my first venture into this domain (though I've done plenty of coding and have some experience with electronics).


texts: My Digispark board won't show up in Ports tab in Arduino IDE (OSX)

texts:
I bought a Digistump/Digispark board online and when i received it, I plugged it into my iMac to see if it works. I went to the apple in the top left corner and clicked "About this Mac". Then I clicked "System Report" and I went to the USB tab and it showed something connected as:

"Vendor-Specific Device:"

I was glad that it showed up but when I went to the Arduino IDE it didn't show up in the ports tab. I downloaded the AVR pack and the driver (i'm pretty sure the driver should work, if there is a specific driver that will work could someone send me to it) I am really frustrated and mad because it seems like this always happens. If someone could help me that would be greatly appreciated! Thank You.

Atmel 1624 tiny85