text:
Interfacing WM8731 code to Arduino Due
WM8731 codec was successfully interfaced with Atmega328 like variants in Arduino. It was first done successfully by Open music labs who are the makers of the breakout board for WM8731. Taking this library as reference another library was developed for atmega2560 Arduino and it also works fine. But now I am trying to get it work with Arduino Due which unlike other AVR micro-controllers in the Arduino family is an ARM. I found some useful code.It compiles well and is able to communicate with the WM8731 codec in I2C. I will post the original library and also explain in parts how the code for Due is built.
Original library is here:
http://cdn.sparkfun.com/datasheets/Dev/Arduino/Shields/AudioCodecNew.zip
My code split looking at the AudioCodec.h file.

#include <Wire.h>
#include <SPI.h>

#define LINVOL 23
#define RINVOL 23
#define LHPVOL 121
#define RHPVOL 121
#define ADCHPD 0
#define SIDEATT 0
#define SIDETONE 0
#define DACSEL 1
#define BYPASS 0
#define INSEL 0
#define MUTEMIC 1
#define MICBOOST 0
#define SAMPLE_RATE 44

volatile boolean l;

unsigned int temp = 0,temp1=0;
int temp_spi[4];
int m1[301],m2[301];
//TC1 ch 0
int left_in,right_in,left_out,right_out;
void TC0_Handler()
{
TC_GetStatus(TC0, 0);

    temp = random(65535);
    //temp = left_out;
    //temp1 = right_out;
    temp_spi[0] = SPI.transfer(10,highByte(temp),SPI_CONTINUE);
    temp_spi[1] = SPI.transfer(10,lowByte(temp),SPI_CONTINUE);
    temp_spi[2] = SPI.transfer(10,highByte(temp),SPI_CONTINUE);
    temp_spi[3] = SPI.transfer(10,lowByte(temp),SPI_LAST);
    //left_in - (temp_spi[0]<<8)|temp_spi[1];
    //right_in = (temp_spi[2]<<8)|temp_spi[3];
    /*Serial.println("Hello");
    Serial.println(temp_spi[0]);
    Serial.println(temp_spi[1]);
    Serial.println(temp_spi[2]);
    Serial.println(temp_spi[3]);*/
}

void startTimer(Tc *tc, uint32_t channel, IRQn_Type irq, uint32_t     frequency) {
    pmc_set_writeprotect(false);
    pmc_enable_periph_clk((uint32_t)irq);
    TC_Configure(tc, channel, TC_CMR_WAVE | TC_CMR_WAVSEL_UP_RC | TC_CMR_TCCLKS_TIMER_CLOCK4);
    uint32_t rc = VARIANT_MCK/128/frequency; //128 because we selected TIMER_CLOCK4 above
    TC_SetRA(tc, channel, rc/2); //50% high, 50% low
    TC_SetRC(tc, channel, rc);
    TC_Start(tc, channel);
    tc->TC_CHANNEL[channel].TC_IER=TC_IER_CPCS;
    tc->TC_CHANNEL[channel].TC_IDR=~TC_IER_CPCS;
    NVIC_EnableIRQ(irq);
}

void AudioCodec_init() {
    randomSeed(analogRead(0));
    SPI.begin(10);
    SPI.setBitOrder(MSBFIRST);
    SPI.setClockDivider(10,21); // select to ss pin 10, 4 MHz
    SPI.setDataMode(10,SPI_MODE0);

    // setup i2c pins and configure codec
    // the new Wire library has trouble with 0x00, so (uint8_t) is added
    // To change the Wire interface speed, go to:
    // <path_from_arduino>\hardware\arduino\sam\libraries\Wire\Wire.h
    // and change the parameters TWI_CLOCK, RECV_TIMEOUT and XMIT_TIMEOUT
    // to the desire frequency.
    int temp_wire1;
    int temp_wire2;

    Wire.begin();
    Wire.beginTransmission(0x1a);
    Wire.write(0x0c); // power reduction register
    Wire.write((uint8_t)0x00); // turn everything on
    temp_wire1 = Wire.endTransmission();

    Wire.beginTransmission(0x1a);
    Wire.write(0x0e); // digital data format
    Wire.write(0x03); // 16b SPI mode
    temp_wire2 = Wire.endTransmission();

    //Serial.println(temp_wire1);
    //Serial.println(temp_wire2);

    Wire.beginTransmission(0x1a);
    Wire.write((uint8_t)0x00); // left in setup register
    Wire.write((uint8_t)LINVOL);
    Wire.endTransmission();

    Wire.beginTransmission(0x1a);
    Wire.write(0x02); // right in setup register
    Wire.write((uint8_t)RINVOL);
    Wire.endTransmission();

    Wire.beginTransmission(0x1a);
    Wire.write(0x04); // left headphone out register
    Wire.write((uint8_t)LHPVOL);
    Wire.endTransmission();

    Wire.beginTransmission(0x1a);
    Wire.write(0x06); // right headphone out register
    Wire.write((uint8_t)RHPVOL);
    Wire.endTransmission();

    Wire.beginTransmission(0x1a);
    Wire.write(0x0a); // digital audio path configuration
    Wire.write((uint8_t)ADCHPD);
    Wire.endTransmission();

    Wire.beginTransmission(0x1a);
    Wire.write(0x08); // analog audio pathway configuration
    Wire.write((uint8_t)((SIDEATT << 6)|(SIDETONE << 5)|(DACSEL << 4)|(BYPASS << 3)|(INSEL << 2)|(MUTEMIC << 1)|(MICBOOST << 0)));
    Wire.endTransmission();

    Wire.beginTransmission(0x1a);
    Wire.write(0x10); // clock configuration
    #if SAMPLE_RATE == 88
      Wire.write(0xbc);
    #elif SAMPLE_RATE == 44
      Wire.write(0xa0);
    #elif SAMPLE_RATE == 22
      Wire.write(0xe0);
    #elif SAMPLE_RATE == 8
      Wire.write(0xac);
    #elif SAMPLE_RATE == 2
      Wire.write(0xce);
    #endif
    Wire.endTransmission();

    Wire.beginTransmission(0x1a);
    Wire.write(0x12); // codec enable
    Wire.write(0x01);
    Wire.endTransmission();

}

void setup(){

    pinMode(2,INPUT);
    pinMode(10,OUTPUT);
    Serial.begin(115200);
    Serial1.begin(9600);
    Serial.println("Hello");
AudioCodec_init();
startTimer(TC0, 0, TC0_IRQn, 2000); //startTimer(TC1, 0, TC3_IRQn,   44100); //TC1 channel 0, the IRQ for that channel and the desired frequency
}

void loop(){
//Serial.println("Hello");
/*for(int i =0;i<300;i++)
{
m1[i]=map(analogRead(0),300,800,-400,400);
m2[i]=map(analogRead(1),300,800,-400,400);
}*/
//for(int j =0;j<300;j++)
//{
/*Serial1.print("a");
Serial1.print(m1[j]);
Serial1.print("b");
Serial1.print(m2[j]);*/
//Serial1.println(left_in);
Serial.print(temp_spi[0]);
Serial.print(" ");
Serial.print(temp_spi[1]);
Serial.print(" ");
Serial.print(temp_spi[2]);
Serial.print(" ");
Serial.println(temp_spi[3]);
//Serial1.println("c");
//Serial.println("In loop");
//h23}
}

So on atmega328 the clockout from the WM8731 was give to T1 pin and on atmega2560 timer 5 was used and clockout was attached to pin T5. I am just starting with Due and I dont know much about ARM but I set the code to TC0,TC0 timer and pin 2.
As described here in this link:
http://forum.arduino.cc/index.php?topic=130423.0
Some how the SPI part in this code and the timer is not working as I cannot get any voice out from the codec.I am also printing the temp_spi[x] variables over serial port and all of them are just zeros all the time. Could some one help me make this code work with the codec? The code compiles fine for Due in the arduino IDE.


text:
Adding a kill switch for servos with states - blink without delay code
I have many LEDs and two servos connected to one Arduino Uno, and the servos are programmed to move randomly indefinitely. However, I would like to install a kill switch for the servos by reading a pot connected to the A0 pin, and when the input from the pot is over a certain value, the servos stop moving. Then, when the pot is "turned down" again, they resume the movement sequence.
I'm a novice, so please be gentle with me! I'm just in a time crunch and know you all probably have an elegant way of getting this done. Thanks!

#include <Servo.h>

// ----CONSTANTS (won't change)

const int led2 = 2;
const int led3 = 3;// the pin numbers for the LEDs
const int led4 = 4;
const int led5 = 5;
const int led6 = 6;
const int led7 = 7;
const int led11 = 11;
const int led12 = 12;
const int led13 = 13;
const int killpot = A0; // analog pin for kill switch pot

const int servoPin1 = 9; // the pin number for the servo signal
const int servoPin2 = 10;

const int led_3_Interval = 2000;
const int led_5_Interval = 4000;
const int led_6_Interval = 3000;
const int led_7_Interval = 10000;
const int led_11_Interval = 1000;
const int led_12_Interval = 1000;
const int led_13_Interval = 6000;
const int led_4_Interval = 3000;

const int blinkDuration = 2000; // number of millisecs that Led's are on - all three leds use this

const int servoMinDegrees = 15; // the limits to servo movement
const int servoMaxDegrees = 165;

//------- VARIABLES (will change)

byte led_2_state = LOW;
byte led_3_state = LOW;
byte led_4_state = LOW;
byte led_5_state = LOW;
byte led_6_state = LOW;
byte led_7_state = LOW;
byte led_11_state = LOW;
byte led_12_state = LOW;
byte led_13_state = LOW;// used to record whether the LEDs are on or off

Servo left_servo;  // create servo object to control a servo
Servo right_servo;

int servoPosition1 = 90;     // the current angle of the servo - starting at 90.
int servoPosition2 = 90;     // the current angle of the servo - starting at 90.
int servoSlowInterval = 2000; // millisecs between servo moves
int servoFastInterval = 1000;
int servoInterval = servoSlowInterval; // initial millisecs between servo moves
int servoDegrees = random(5, 50);       // amount servo moves at each step
                           //    will be changed to negative value for movement in the other direction

unsigned long currentMillis = 0;    // stores the value of millis() in each iteration of loop()
unsigned long previousLed2Millis = 0;   // will store last time the LED was updated
unsigned long previousLed3Millis = 0;
unsigned long previousLed4Millis = 0;
unsigned long previousLed5Millis = 0;
unsigned long previousLed6Millis = 0;
unsigned long previousLed7Millis = 0;
unsigned long previousLed11Millis = 0;
unsigned long previousLed12Millis = 0;
unsigned long previousLed13Millis = 0;

unsigned long previousServoLeftMillis = 0; // the time when the servo was last moved
unsigned long previousServoRightMillis = 0;

//========

void setup() {

 Serial.begin(9600);
 Serial.println("Starting SeveralThingsAtTheSameTimeRev1.ino");  // so we know what sketch is running

     // set the Led pins as output:
 pinMode(led2, OUTPUT);
 pinMode(led3, OUTPUT);
 pinMode(led4, OUTPUT);
 pinMode(led5, OUTPUT);
 pinMode(led6, OUTPUT);
 pinMode(led7, OUTPUT);
 pinMode(led11, OUTPUT);
 pinMode(led12, OUTPUT);
 pinMode(led13, OUTPUT);

     // set the button pin as input with a pullup resistor to ensure it defaults to HIGH

 left_servo.write(servoPosition1); // sets the initial position
 left_servo.attach(servoPin1);
 right_servo.write(servoPosition2); // sets the initial position
 right_servo.attach(servoPin2);
}

//=======

void loop() {

     // Notice that none of the action happens in loop() apart from reading millis()
     //   it just calls the functions that have the action code

 currentMillis = millis();   // capture the latest value of millis()
                             //   this is equivalent to noting the time from a clock
                             //   use the same time for all LED flashes to keep them synchronized
 analogRead(resswitch);
 updateLed_2_State();
 updateLed_3_State();
 updateLed_4_State();
 updateLed_5_State();
 updateLed_6_State();
 updateLed_7_State();
 updateLed_11_State();
 updateLed_12_State();
 updateLed_13_State();
 switchLeds();
 servoLeft_Sweep();
 servoRight_Sweep();

}

//========

void updateLed_2_State() {

 digitalWrite(led2, HIGH); // turn eye LEDs on
}

//=======

void updateLed_3_State() {

 if (led_3_state == LOW) {
   if (currentMillis - previousLed3Millis >= led_3_Interval) {
      led_3_state = HIGH;
      previousLed3Millis += led_3_Interval;
   }
 }
 else {
   if (currentMillis - previousLed3Millis >= blinkDuration) {
      led_3_state = LOW;
      previousLed3Millis += blinkDuration;
   }
 }
}

//=======

void updateLed_4_State() {

 if (led_4_state == LOW) {
   if (currentMillis - previousLed4Millis >= led_4_Interval) {
      led_4_state = HIGH;
      previousLed4Millis += led_4_Interval;
   }
 }
 else {
   if (currentMillis - previousLed4Millis >= blinkDuration) {
      led_4_state = LOW;
      previousLed4Millis += blinkDuration;
   }
 }
}
//=======

void updateLed_5_State() {

 if (led_5_state == LOW) {
   if (currentMillis - previousLed5Millis >= led_5_Interval) {
      led_5_state = HIGH;
      previousLed5Millis += led_5_Interval;
   }
 }
 else {
   if (currentMillis - previousLed5Millis >= blinkDuration) {
      led_5_state = LOW;
      previousLed5Millis += blinkDuration;
   }
 }
}
//=======

void updateLed_6_State() {

 if (led_6_state == LOW) {
   if (currentMillis - previousLed6Millis >= led_6_Interval) {
      led_6_state = HIGH;
      previousLed6Millis += led_6_Interval;
   }
 }
 else {
   if (currentMillis - previousLed6Millis >= blinkDuration) {
      led_6_state = LOW;
      previousLed6Millis += blinkDuration;
   }
 }
}
//=======

void updateLed_7_State() {

 if (led_7_state == LOW) {
   if (currentMillis - previousLed7Millis >= led_7_Interval) {
      led_7_state = HIGH;
      previousLed7Millis += led_7_Interval;
   }
 }
 else {
   if (currentMillis - previousLed7Millis >= blinkDuration) {
      led_7_state = LOW;
      previousLed7Millis += blinkDuration;
   }
 }
}
//=======

void updateLed_11_State() {

 if (led_11_state == LOW) {
   if (currentMillis - previousLed11Millis >= led_11_Interval) {
      led_11_state = HIGH;
      previousLed11Millis += led_11_Interval;
   }
 }
 else {
   if (currentMillis - previousLed11Millis >= blinkDuration) {
      led_11_state = LOW;
      previousLed11Millis += blinkDuration;
   }
 }
}
//=======

void updateLed_12_State() {

 if (led_12_state == LOW) {
   if (currentMillis - previousLed12Millis >= led_12_Interval) {
      led_12_state = HIGH;
      previousLed12Millis += led_12_Interval;
   }
 }
 else {
   if (currentMillis - previousLed12Millis >= blinkDuration) {
      led_12_state = LOW;
      previousLed12Millis += blinkDuration;
   }
 }
}

//=======

void updateLed_13_State() {

 if (led_13_state == LOW) {
   if (currentMillis - previousLed13Millis >= led_13_Interval) {
      led_13_state = HIGH;
      previousLed13Millis += led_13_Interval;
   }
 }
 else {
   if (currentMillis - previousLed13Millis >= blinkDuration) {
      led_13_state = LOW;
      previousLed13Millis += blinkDuration;
   }
 }
}

//========

void switchLeds() {
     // this is the code that actually switches the LEDs on and off

 digitalWrite(led3, led_3_state);
 digitalWrite(led4, led_4_state);
 digitalWrite(led5, led_5_state);
 digitalWrite(led6, led_6_state);
 digitalWrite(led7, led_7_state);
 digitalWrite(led11, led_11_state);
 digitalWrite(led12, led_12_state);
 digitalWrite(led13, led_13_state);

}

//========

void servoLeft_Sweep() {

     // this is similar to the servo sweep example except that it uses millis() rather than delay()

     // nothing happens unless the interval has expired
     // the value of currentMillis was set in loop()

 if (currentMillis - previousServoLeftMillis >= servoInterval) {
       // its time for another move
   previousServoLeftMillis += servoInterval;

   servoPosition1 = servoPosition1 + servoDegrees; // servoDegrees might be negative

   if (servoPosition1 <= servoMinDegrees) {
         // when the servo gets to its minimum position change the interval to change the speed
      if (servoInterval == servoSlowInterval) {
        servoInterval = servoFastInterval;
      }
      else {
       servoInterval = servoSlowInterval;
      }
   }
   if ((servoPosition1 >= servoMaxDegrees) || (servoPosition1 <= servoMinDegrees))  {
         // if the servo is at either extreme change the sign of the degrees to make it move the other way
     servoDegrees = - servoDegrees; // reverse direction
         // and update the position to ensure it is within range
     servoPosition1 = servoPosition1 + servoDegrees;
   }
       // make the servo move to the next position
   left_servo.write(servoPosition1);
       // and record the time when the move happened
 }
}

//========

void servoRight_Sweep() {

     // this is similar to the servo sweep example except that it uses millis() rather than delay()

     // nothing happens unless the interval has expired
     // the value of currentMillis was set in loop()

 if (currentMillis - previousServoRightMillis >= servoInterval) {
       // its time for another move
   previousServoRightMillis += servoInterval;

   servoPosition1 = servoPosition1 + servoDegrees; // servoDegrees might be negative

   if ((servoPosition1 >= servoMaxDegrees) || (servoPosition1 <= servoMinDegrees))  {
         // if the servo is at either extreme change the sign of the degrees to make it move the other way
     servoDegrees = - servoDegrees; // reverse direction
         // and update the position to ensure it is within range
     servoPosition1 = servoPosition1 + servoDegrees;
   }
      else {
       servoInterval = servoSlowInterval;
      }
       if (servoPosition1 <= servoMinDegrees) {
         // when the servo gets to its minimum position change the interval to change the speed
      if (servoInterval == servoSlowInterval) {
        servoInterval = servoFastInterval;
      }

   }
       // make the servo move to the next position
   right_servo.write(servoPosition1);
       // and record the time when the move happened
 }
}
//=====END

while (analogRead(resswitch) > 700);

Thank you! I've inserted that line in the servoLeft_Sweep()  and servoRight_Sweep() sections, and the LEDs pause where they are and the servos halt, which is good. But, is there a way to insert the "while" argument and have the LED sequence continue to run with the servos stopping?

Turn it into an if, invert the logic, and wrap it around the servo functions.

Please excuse my novice ability... but like this?
if (analogRead(resswitch) > 700);    {
if (currentMillis - previousServoLeftMillis >= servoInterval) {...

It's rather if (analogRead(resswitch) < 700) { servoLeft_Sweep(); servoRight_Sweep(); }

source: Stack Exchange

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

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

sort: votes


text:
Passing arguments to LCD.print through another function
I'd like to write a function like this:
void lcdPositionPrint(int row, int col,  content) {
    lcdPosition(row, col);
    LCD.print(content);
}

but I'm not certain how to declare "content", because it might be a string, or an int, or who knows what, just as it is for the "Serial.print" function or the LCD.print() function. Is there an easy way to do this?

There isn't really a great way to do it, but there are a few ways to get it to work. Most of the problem here is that there is actually a different LCD.print function for every data type. You aren't really calling the same function, your calling different functions that share the same name.
You could use templates. They are a powerful system built into C plus plus for generating functions and avr-gcc supports them well. With them, you can make the compiler generate all the necessary versions of your function for you. Your function would then look like this:
template<typename T>
void lcdPositionPrint(int x, int y, T content) throw() {
  lcdPosition(row, col);
  LCD.print(content);
}

That part about throw() isn't doing anything except keeping the ".ino" preprocessor from messing the template function up. You can call the templated function like normal, or with an explicit type
lcdPositionPrint(0,0,"hello");
lcdPositionPrint<float>(0,0,32.0f);

You could also use the preprocessor. Your function is very simple, so you could just as easily make it a preprocessor macro that just places you code you want in the file whenever your "function call" appears. It looks like this:
#define lcdPositionPrint2(row,col,content) \
    do { lcdPosition(row, col); LCD.print(content); } while (0)

The \ there tells the preprocessor that the next line is also part of the macro, and you will need one on every line but the last of your function. Wrapping it in a do loop that immediately ends makes it nicely substitute into more situations. Micros don't scale up well, but they are a bit simpler for quick debugging situations. The code is duplicated in each call location instead of being bundled into functions though.

Thanks; I didn't know that templates existed in the language. (To be honest, although I've written a few hundred lines, I've never been clear on what language I'm using -- I just kinda wing it). My own solution was to write two near-identical copies, one for "int content" and one for "String content", and that covered all my bases.

One more thought: an improved version of your preprocessor solution puts braces around the {lcdPosition(row, col); LCD.print(content);} lines so that "if (x < 10) lcdPositionPrint(r, c, 14); " doesn't always end up printing "14", either at (r, c) or at the current cursor location.

That's what wrapping it in do { ... } while (0) is for (and all of the other issues that can show up when just using braces).

One way to do this is to use generics. And we also need to use an unnamed namespace to get around the IDE's "helpfulness":
namespace {
    template<typename T>
    void lcdPositionPrint(int row, int col, T content) {
        lcdPosition(row, col);
        LCD.print(content);
    }
}

This will cause the compiler to create one function for each type passed in content that the function is actually called with.

Thanks very much. I didn't know that there were templates to work with!

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


text:
Strange problem with serial communication
I'm developing a little project with Arduino, using a small web page to show data. Well, I have been develop the web page and the small code to communicate with Arduino board in my local computer and all work fine.
But, after, I uploaded the code to a Raspberry Pi and then the problems appear.
This is very strange, because when I execute the code inside a WSGI like  django (in my case is other, webapp2) the code works well. I call a specific URL and this WSGI call a method inside a class that communicated with the Arduino board through serial port, so far, so good.
The problem appears when I decided build a method to execute the lines that do the communication, in this moment Arduino does not response and only lights the led number 13 and the 'L' led twice (the led inside the board).
I don't understand why this happens. The code is exactly the same. Any idea?
For the other hand, because I don't have GUI in the raspberry I don't can view the serial port communication easy.
Do you  know any way to view or debug the serial communications between a pc and Arduino without GUI, over the command line?
This is the code:

# -*- coding: utf-8 -*-
import serial
import time

arduino=serial.Serial('/dev/ttyACM0', baudrate=9600, timeout=3.0)
arduino.close()
arduino.open()

sensorTemp=''
arduino.write('a')
while arduino.inWaiting() > 0:
        sensorTemp+=arduino.read(1)
print sensorTemp

Thanks you so much. Any idea is welcome.

Opening the port typically resets the arduino and incurs the bootloader delay (causing it to miss your 'a') unless you change the hupctl setting.  It has been covered in existing questions here.

You can SSH to the PI, then use ```screen /dev/ttyACM0´´´ to open the serial port to the Arduino (when nothing else is using it) just to make sure the Arduino is behaving.

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


text:
Pilot the the reset line by two input
I have two input signal that when activated have to restart the ardiuno board so I have to connect them to the RESET pin. As you know the arduino board have only one RESET pin so I can't connect both to the same pin.
I think that a good idea is a circuit that takes the two inputs and activate the RESTART pin when one of the two is active.
Have you any idea to solve that problem?
Thank you.

use a logic IC (OR gate) or two reset lines in parallel with appropriate resistors.

Can you tell us why? What are those signals and why do you want to reset the arduino? Such questions might be the xy-problem: http://xyproblem.info/

Just use diode logic.
The resistor is probably not needed because the Arduino has an internal pullup resistor.
This assumes that the two reset inputs are active low

simulate this circuit – Schematic created using CircuitLab

This seems like the simplest solution. (Voted)

What you want is an AND gate (e.g., 74HC08, which contains 4 AND gates).
An AND gate is a chip which sets its output HIGH when both inputs to it are HIGH.
Symbolically it looks like:

simulate this circuit – Schematic created using CircuitLab
This, of course, is assuming that both your reset signals are active low - that is, they are normally in the HIGH state, but when they want to reset the board they go LOW.
You can do the same thing with three transistors.  Two transistors in series make a NAND gate (like an AND gate but the output is inverted), and a third makes a NOT gate to invert the output:

simulate this circuit
Note that R4 is optional, since the RESET pin already has a 10KΩ pullup resistor in it.


text:
5V DC Mini Water Pump with Arduino Mega 2560?
First of all, it is my first topic and i want to say hi to you all!! Secondly, i am really a terrible noob and sorry for that  :(
I need to make a smart greenhouse project with Arduino Mega 2560, and i found a video to help me with my servomotor(MG996R) which will start working when raindrops module detect rain and 12v DC Fan which will start working when LM35 sensor calculates the weather as hot. However, my third actuator, 5V DC Mini Water Pump, which needs to become turned on when soil humidity sensor measures the soil as dry, is where i am left without an opinion. All the water pumps people use is 12 V, so i dont know which specific components i should use. I researched a bit and found that people use transistors and diodes for it. Which ones should i use and how to make the connections?
I would appreciate if someone helps me what components, specifically, should i buy and how to connect them together with Arduino 2560? It would be great if you can draw it, like with fritzing or something.
Thanks if you read this far :)

Welcome to arduino.stackexchange.com .
As motor is usually a high current load, controlling a switch to control the motor's power is the solution.
If you are not interested in h/w design just want to use a interface out of box you can use relay module like this relay. For only one load connection will be simple and I don't think Arduino current supply limit will be a problem.
see this answer for example connection using relay. It is almost similar use case I think. Also here is a Fritzing image using the relay in the first link. I have used four 3V battery pack as 12V source. It doesn't have to be battery.

If you like to do from scratch, you can use BJT(Bi polar junction transistor) or MOSFET.
Here is a possible schematic.

simulate this circuit – Schematic created using CircuitLab
Different power supplies are used for Arduino and Motor because recommended voltage range is 7-12V in Vin pin. Different sources, voltage levels like 5V from USB may be used according to your ease.
node b, c and e are base, collector and emitter of the BJT. Diode D1 is called flyback diode.
Let, the current needed for motor IL, motor voltage needed VL, collector current Ic and base current Ib and the resistor between arduino and base Rb. Note that IL = Ic
Operating mode of transistor will be saturation mode. So, the base current (supplied by arduino) will be,

Ibe = (current gain at saturation)*Ic

How to find the current gain? Look through the datasheet of transistor for hfe(sat) which is basically Ic/Ib at saturation mode. Some datasheet may use α instead of hfe(sat)
Then find the Vbe(sat) as you will be operating in saturation mode. Find the needed base resistor value Rb,

Ib = 5-Vbe/Rb

While designing this you have to be careful about these condition (I am talking about design using BJT)

Vce(max)(max) > VL
Ice(max) > IL
Arduino digital pin max I > Ib

All the devices should have same ground. Be sure to use the diode(D1) mentioned in the design as motor is an inductive load, sudden powering down may create large voltage across motor.


text:
How to add extra USB port to Arduino Nano?
I'm trying to use V-USB library to emulate a keyboard using Arduino Nano but because of precaution, I don't want to use it's built-in USB port.
My idea is to add another USB port so I cant power my device with the new USB port and use free digital pins as input/output of the new USB serial port in V-USB project.
What circuit I should use and how to add extra USB port to Arduino Nano.

By far the easiest way would be to buy a second Nano and connect the two together.

@Andrew of course it's easiest way but I care about the cost of the project!

The circuit diagram for connecting V-USB http://read.pudn.com/downloads194/sourcecode/embed/911688/vusb-20090822/circuits/with-zener.png

USB is deceptively simple.  The underlying protocol is very complex. So a complete answer to your question requires some USB background.
USB is divided into 2 types.  USB Hosts and USB Devices. We are not concerned about USB Hosts here.  USB Devices only need to know about their own functions / features.  If they are a serial port device, like the FTDI chip on the Arduino Nano, they only need to "speak" basic USB protocol and the serial CDC USB protocol.  If the USB Device was a keyboard, it only needs to know the basic USB protocol and the HID USB protocol.
In order to offer up a USB port the Arduino Nano uses an FTDI chip FT232RL.  This chip supports a Serial Port USB Device.  It does not appear to support HID USB Devices.  So your decision to use V-USB is necessary not because of power but because the Arduino Nano's built in USB port supports a protocol other than USB CDC.

What circuit I should use and how to add extra USB port to Arduino
  Nano.

The circuit suggested is on the V-USB web page appears to contain the necessary information:

Of course you will have to do some research into V-USB software to see which are the appropriate pins to use on your Arduino Nano.

The OP wants to use V-USB!

I see what you mean.  I'll edit my answer.  Thanks.

Since Arduino Nano have internal oscillator, can I setup only left side of the circuit?

My understanding is that USB is very picky about frequency.  Perhaps this is the reason that the V-USB web page included the external crystal.  However, the V-USB web page does say: "Can be clocked with 12 MHz, 15 MHz, 16 MHz 18 MHz or 20 MHz crystal or from a 12.8 MHz or 16.5 MHz internal RC oscillator.".

You can use a USB host mini module for the Arduino NANO and the USB Host Library r2.0

You can implement a keyboard with this...


text:
How to reprogram Arduino if USB port is already in use?
I'm developing a keyboard emulator using Digispark Pro (based on Arduino) which uses USB port as the keyboard interface. I haven't programmed it yet because I doubt how should I recognize the chip to Arduino IDE again using USB port after programming the board.
So my question is, how to reprogram Arduino if USB port is already recognized as keyboard HID?

Is the Arduino running with it's bootloader, or it is programmed with the target app only?

@EugeneSh. I haven't programmed it yet. Digispark Pro has Arduino bootloader by itself.

@joware you can make low speed  USB keyboard host in software mainly with arduino ng oe better

@yabbadabba I already bought digispark pro. My only problem is reprogramming the board.

If I'm correct, after a reset, it will first enumerate as an Digispark in the bootloader. Then after a timeout, it will run the main program and enumerate as a keyboard. The only problem might be that you'd have to manually press the reset button when you want to program the chip.

@Gerben Thank you, this is what I'm asking. So after programming the chip, for reprogramming it, I must connect it to PC and then press reset button and before reaching timeout (about 5 secs I think), I must program it again?

That's the way I understood it worked.

https://digistump.com/wiki/digispark/tutorials/connectingpro
It is suggested that in order to upload using the Arduino IDE you must:

Add the repository http://digistump.com/package_digistump_index.json in Preferences > Additional Boards Manager URLs
Install Digistump from the boards manager.
select the DigiSpark in Tools > Boards.
Then this is perhaps the important bit "You do not need to plug in your Digispark Pro before invoking upload"   So hit upload before connecting the Digispark.
Then connect the Digispark when prompted by the Arduino IDE.


text:
HC-05 bluetooth module
I was able to connect my HC-05, pair it with my phone, and I can see data in the Serial Bluetooth Terminal Android App.  But when I try to connect it to a certain application it says it cannot find it.  Can the application force a certain version of Bluetooth?  Am I missing something?  Thanks.

What to you mean by a "certain application"? Does the app (Android side) say it can't see the HC? Does the HC say it can't send data? More details please :)

The HC-05 modules use bluetooth 2.0. Certain apps would only be compatible with bluetooth 4.0 devices (BLE - Bluetooth Low Energy), such as an HM10 or AT09.
It could be that your app requires the device to use v4.0+. Are you able to find, and pair with the device using your android's default bluetooth device scanning/pairing features?
Assuming that your app does not require v4.0+, have you removed the connection from 'en'/'ch_pd' to 3.3v? If that was still connected (which is a required connection to enter AT command mode), then your bt module would not be able to accept incoming pair requests etc.
hope this has helped. :)

Thank you for your reply.  I think the app may be 4.0.  My understanding is the app is supposed to automatically connect.  You are not to manually pair it.  I can connect to it through my Android Bluetooth settings and also through the Bluetooth Terminal app.  So if the app requires 4.0 would which module would you recommend?  Thanks again.

HM10 would be my recommendation, but there are loads of what look like AT09 (also v4.0) claiming to be HM10's on ebay/amazon. I havent had issues with my AT09 (as of yet, not done much with it, and i ordered more hc05's as the antenna on the AT09 seemed very thin)
I'm sure there are android apps that allow you to scan for bluetooth devices using either 'classic' or v4+. haven't tried any of those out myself though.

Thank you.  I will get an HM10 and try it.


text:
STM32 Nucleo F401RE in Arduino IDE - how to enable more than 1 Serial?
I just received a Nucleo F401RE and can't get my sketch to work on it because the compiler says Serial1 is not defined.
My sketch uses multiple serials because I need to use the usb serial monitor while also communicating to another device on a different serial port.
Here is a screenshot of the flags I selected.

According to the F401 specs it has at least 6 different serials, so the real question is: is there an easy way to use Serial1 and so on straight out of the box in the Arduino IDE?
I'm quite new and unexperienced to this field, so please excuse me if this question is too trivial.

http://www.stm32duino.com/

could you elaborate more, please? I've looked for an answer on stm32duino.com forum before posting here, but couldn't find any. I also wanted to post my question there, but it seems like it's impossible to register as a new user, so I'm stranded at the moment

the options from Tools menu are evaluated in WSerial.h. SerialUSB and/or Serial are defined. the way described in answer is the right one to create additional Serial interfaces

Frederic Pillon on Github has been very helpful and suggested me the solution, which is to define the serial via:
HardwareSerial Serial1(PA10, PA9);

instead of just giving Serial1 for granted as you would do on a regular Arduino mega


text:
Serial Monitor Just Stops Working
I am communicating with two Arduinos with serial. The program works great for a while but then the serial monitor stops showing values in the RX code and will not work again unless the code is uploaded again. Why is this happening?
TX code:

/*
  Transmitting Code
  Reads potentiometers and sends them through serial
*/

int data [12];     // to send bytes
int start [2];

int Pin1A = A0;
int Joystick1A;  //crab

int Pin1B = A1;
int Joystick1B;  //up down

int Pin2A = A2;
int Joystick2A;   // pitch

int Pin2B = A3;
int Joystick2B;  // up down

int Pin3A = A4;   // yaw r-l
int Joystick3A;

int Pin3B = A5;
int Joystick3B;   // forward-back

unsigned char checksum0;
unsigned char checksum1;
unsigned char checksum2;
unsigned char checksum3;
unsigned char checksum4;
unsigned char checksum5;
unsigned char handshake;
unsigned char handshake2;
unsigned char handshake3;

void setup() {
  Serial.begin(4800);
  Serial1.begin(4800);
  pinMode(19, INPUT);
  pinMode(18, OUTPUT);
}

void loop() {

// READ THE POTENTIOMETERS:

  Joystick1A = analogRead(Pin1A);   // reads the value of the potentiometer (Joystick1Aue between 0 and 1023)
  data[0] = Joystick1A & 0xFF; //least significant 8 bit byte
  data[1] = (Joystick1A >> 8); //most significant 2 bits

  Joystick1B = analogRead(Pin1B);
  data[2] = Joystick1B & 0xFF;
  data[3] = (Joystick1B >> 8);

  Joystick2A = analogRead(Pin2A);
  data[4] = Joystick2A & 0xFF;
  data[5] = (Joystick2A >> 8);

  Joystick2B = analogRead(Pin2B);   // reads the value of the potentiometer (Joystick1Aue between 0 and 1023)
  data[6] = Joystick2B & 0xFF; //least significant 8 bit byte
  data[7] = (Joystick2B >> 8); //most significant 2 bits

  Joystick3A = analogRead(Pin3A);
  data[8] = Joystick3A & 0xFF;
  data[9] = (Joystick3A >> 8);

  Joystick3B = analogRead(Pin3B);
  data[10] = Joystick3B & 0xFF;
  data[11] = (Joystick3B >> 8);

// CREATE CHECKSUMS:

  checksum0 = ~(data[0]+data[1]) + 1;

  checksum1 = ~(data[2]+data[3]) + 1;

  checksum2 = ~(data[4]+data[5]) + 1;

  checksum3 = ~(data[6]+data[7]) + 1;

  checksum4 = ~(data[8]+data[9]) + 1;

  checksum5 = ~(data[10]+data[11]) + 1;
// WRITE VALUES AND CHECKSUMS TO SERIAL:

while (Serial1.available()<3) {
  ; //wait for request from receiver
}
  handshake = Serial1.read();
  handshake2 = Serial1.read();
  handshake3 = Serial1.read();

  if ((handshake == 1) && (handshake2 == 2) && (handshake3 == 3)) {

Serial1.write(1);

  Serial1.write(data[0]);
  Serial1.write(data[1]);
    Serial1.write(checksum0);

  Serial1.write(data[2]);
  Serial1.write(data[3]); //bytes sent
    Serial1.write(checksum1);

  Serial1.write(data[4]);
  Serial1.write(data[5]);
    Serial1.write(checksum2);

  Serial1.write(data[6]);
  Serial1.write(data[7]);
    Serial1.write(checksum3);

  Serial1.write(data[8]);
  Serial1.write(data[9]); //bytes sent
    Serial1.write(checksum4);

  Serial1.write(data[10]);
  Serial1.write(data[11]);
    Serial1.write(checksum5);

Serial1.write(2);

   delay(10);     // delay in between reads for stability
  }

// VIEW IN SERIAL MONTIOR:

}

RX code:
/*
  Receving Code
  Reads bytes from Transmitting Code and put thems back together
  Applies the read bytes to our motor control board
*/

unsigned char val[12];    // variable to read the value from the analog pin
int Joystick1A;      // 0-1024 received from serial
int Joystick1B;
int Joystick2A;
int Joystick2B;      // 0-1024 received from serial
int Joystick3A;
int Joystick3B;

unsigned char checksum0;
unsigned char checksum1;
unsigned char checksum2;
unsigned char checksum3;
unsigned char checksum4;
unsigned char checksum5;
unsigned char FirstByte;
unsigned char LastByte;

unsigned char checkit0;
unsigned char checkit1;
unsigned char checkit2;
unsigned char checkit3;
unsigned char checkit4;
unsigned char checkit5;

//ALL MOTORS:
int V1Direction = 31;
int V1PWM = 2;     //MOTOR V1
int V1Motor;

int V2Direction = 33;
int V2PWM = 3;     //MOTOR V2
int V2Motor;

int V3Direction = 35;
int V3PWM = 4;     //MOTOR V3
int V3Motor;

int V4Direction = 37;
int V4PWM = 5;     //MOTOR V4
int V4Motor;

int H1Direction = 39;
int H1PWM = 6;     //MOTOR H1
int H1Motor;

int H2Direction = 41;
int H2PWM = 7;     //MOTOR H2
int H2Motor;

int H3Direction = 43;
int H3PWM = 8;     //MOTOR H3
int H3Motor;

int H4Direction = 45;
int H4PWM = 9;     //MOTOR H4
int H4Motor;

void setup() {
  Serial.begin(4800);
  Serial1.begin(4800);
//  Serial1.begin(4800);
  pinMode(10, INPUT);
  pinMode(18, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
  delay(1000);
}

void loop() {

  Serial1.write(1);
  Serial1.write(2);
  Serial1.write(3);

  if (Serial1.available()>18) {

  FirstByte=Serial1.read();

  if (FirstByte == 1) {
    val[0]=Serial1.read();         // least significant 8 bits
    val[1]=Serial1.read();         // most significant 2 bits
     checksum0=Serial1.read();     // checksum

    val[2]=Serial1.read();
    val[3]=Serial1.read();
     checksum1=Serial1.read();

    val[4]=Serial1.read();
    val[5]=Serial1.read();
     checksum2=Serial1.read();

    val[6]=Serial1.read();         // least significant 8 bits
    val[7]=Serial1.read();         // most significant 2 bits
     checksum3=Serial1.read();     // checksum

    val[8]=Serial1.read();
    val[9]=Serial1.read();
     checksum4=Serial1.read();

    val[10]=Serial1.read();
    val[11]=Serial1.read();
     checksum5=Serial1.read();

   LastByte = Serial1.read();

// get the checksum last

    checkit0 = val[0]+val[1]+checksum0;
    checkit1 = val[2]+val[3]+checksum1;
    checkit2 = val[4]+val[5]+checksum2;
    checkit3 = val[6]+val[7]+checksum3;
    checkit4 = val[8]+val[9]+checksum4;
    checkit5 = val[10]+val[11]+checksum5;

if (LastByte == 2) {
  if (checkit0==0)  {
    Joystick1A = val[1]<<8 | val[0]; }

  if (checkit1==0)  {
    Joystick1B = val[3]<<8 | val[2]; }

  if (checkit2==0)  {
    Joystick2A = val[5]<<8 | val[4]; }

  if (checkit3==0)  {
    Joystick2B = val[7]<<8 | val[6]; }

  if (checkit4==0)  {
    Joystick3A = val[9]<<8 | val[8]; }

  if (checkit5==0)  {
    Joystick3B = val[11]<<8 | val[10]; }

}
else (Serial.println("Goodbye"));
    Serial.print(Joystick1A);
    Serial.print(" ");
    Serial.print(Joystick1B);
    Serial.print(" ");
    Serial.print(Joystick2A);
    Serial.print(" ");
    Serial.print(Joystick2B);
    Serial.print(" ");
    Serial.print(Joystick3A);
    Serial.print(" ");
    Serial.println(Joystick3B);
    delay(10);

  }
  }
  }

Please edit question and tell what happens in the following cases: (a) restart serial monitor (ie exit from it then restart it; (b) push reset button on the Mega; (c) replug USB cables (ie unplug them and then plug in again).  Also, please edit question and indicate whether you are referring to serial communications via USB link, whether each Arduino is plugged into a USB port, etc.

And when does it stop? Is it always at the end of a cycle, or is it at a random point half way through? Also, how long does it work for before it fails - is it the same each time?

You might want to think about refactoring you code by using loops it will make it easier to track down the fault.


text:
Arduino micro window focus troubles
I'm currently attempting to use an Arduino Micro as a ducky USB for penetration testing, and currently when I attempt to open a command prompt (or any other window) the window loses focus which prevents me from typing anything in it. Here's my sample code:

#include <Keyboard.h>

void setup() {
  delay(5000); //Delay for testing
  Keyboard.begin();

  Keyboard.write(KEY_LEFT_GUI);
  delay(400);
  print(F("notepad"));
  enter();

  Keyboard.print("This is a test");
  enter();

  clear();
  Keyboard.end();
}

void print(const __FlashStringHelper *value) {
  Keyboard.print(value);
}

void clear() {
  Keyboard.releaseAll();
}

void enter() {
  Keyboard.write(KEY_RETURN);
  Keyboard.releaseAll();
}
void loop(){}

Any thoughts on what might be causing this? I'm testing it on windows 10 home (not sure if that matters).


text:
Sending GPS data between two Arduinos using Easy Transfer
I'm trying to get GPS data transmitted from one Arduino UNO to a second unit to eventually be displayed on an LCD and stored in an SD card.  I am using Xbees S2C's on Xbee Shield's to do this.  The GPS information is coming from an Adafruit ultimate GPS breakout.
First I wanted so send two NMEA sentences as strings, but have since found that the EasyTransfer library does not like that.  I was getting information but it was just random characters, sort of.  The pattern was repeated, so it was consistent.
After doing some searching I thought the best way to do it was to convert my strings to character arrays and send those.  I managed to successfully convert them to character arrays, but I can't seem to get them over to the other Arduino.  I do get the FIX int as well as the Length int that I sent over just to make sure it is working.  Any ideas on what I am doing wrong?
Sender code:

#include <EasyTransfer.h>
#include <Adafruit_GPS.h>
#include <SoftwareSerial.h>

SoftwareSerial mySerial(3, 2); //Initialize SoftwareSerial, and tell it you will be connecting through pins 2 and 3
Adafruit_GPS GPS(&mySerial); //Create GPS object

String NMEA1;  //We will use this variable to hold our first NMEA sentence
String NMEA2;  //We will use this variable to hold our second NMEA sentence
char c;       //Used to read the characters spewing from the GPS module
int fix = 0;
long GPStime = 0;
int val = 0;

EasyTransfer ET;

//Declare Data Structure for the EasyTransfer Library
//Note: Data Structure must be same on TX and RX...

struct DATA_STRUCTURE{
 int fixed;
 int length1;
 int length2;
 char* nmea1;
 char* nmea2;
};

DATA_STRUCTURE myData;

void setup()
{
  //Initalizing EasyTransfer Serial Ports
  Serial.begin(115200);
  ET.begin(details(myData), &Serial);
  GPS.begin(9600);       //Turn GPS on at baud rate of 9600
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
  //Serial.println("Two GPS Sentences From GPS");
  GPS.sendCommand("$PGCMD,33,0*6D"); // Turn Off GPS Antenna Update
  GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA); //Tell GPS we want only $GPRMC and $GPGGA NMEA sentences
  GPS.sendCommand(PMTK_SET_NMEA_UPDATE_10HZ);   // 10 Hz update rate
  delay(1000);  //Pause
}

void loop()
{
  readGPS();  //This is a function we define below which reads two NMEA sentences from GPS
  //Sending Data
  ET.sendData();
}

void readGPS()    //This function will read and remember two NMEA sentences from GPS
{
  clearGPS();    //Serial port probably has old or corrupt data, so begin by clearing it all out
  while(!GPS.newNMEAreceived())   //Keep reading characters in this loop until a good NMEA sentence is received
  {
    c=GPS.read(); //read a character from the GPS
  }
  GPS.parse(GPS.lastNMEA());  //Once you get a good NMEA, parse it
  NMEA1=GPS.lastNMEA();      //Once parsed, save NMEA sentence into NMEA1
  while(!GPS.newNMEAreceived()) //Go out and get the second NMEA sentence, should be different type than the first one read above.
  {
    c=GPS.read();
  }
  GPS.parse(GPS.lastNMEA());
  NMEA2=GPS.lastNMEA();

  fix = GPS.fix;
  if (fix == 1)
  {
    //Serial.print("FIXED");
    digitalWrite(13, HIGH);
    //Serial.print(NMEA1);
    myData.fixed = 1;
    int str_len1 = NMEA1.length();
    char char_array1[str_len1];
    NMEA1.toCharArray(char_array1, str_len1);
    myData.length1 = str_len1;

    //Serial.print(char_array1);
    //Serial.println("");
    //Serial.println("");
    myData.nmea1 = char_array1;

  }
  else
  {
    //Serial.println("No fix");
    digitalWrite(13, LOW);
    myData.fixed = 0;

  }
}

void clearGPS() //Since between GPS reads, we still have data streaming in, we need to clear the old data by reading a few sentences, and discarding these
{
  while(!GPS.newNMEAreceived())
  {
    c=GPS.read();
  }
  GPS.parse(GPS.lastNMEA());
  while(!GPS.newNMEAreceived())
  {
    c=GPS.read();
  }
  GPS.parse(GPS.lastNMEA());
}

Receiver Code:
#include <EasyTransfer.h>
#include "Wire.h"
#include "Adafruit_LiquidCrystal.h"

EasyTransfer ET;

Adafruit_LiquidCrystal lcd(0);

//Declare Data Structure for the EasyTransfer Library
//Note: Data Structure must be same on TX and RX...

struct DATA_STRUCTURE{
 int fixed;
 int length1;
 int length2;
 char* nmea1;
 char* nmea2;
 //int pause;
};

DATA_STRUCTURE myData;

char* NMEA1[100] = {0};

void setup()
{
 //Initalizing EasyTransfer Serial Ports
 Serial.begin(115200);
 ET.begin(details(myData), &Serial);

 lcd.begin(20, 4);
 lcd.clear();
 lcd.setBacklight(HIGH);

 pinMode(13, OUTPUT);
 digitalWrite(13, LOW);

}

void loop()
{
  //check and see if a data packet has come in.
  if(ET.receiveData()){
    //this is how you access the variables. [name of the group].[variable name]
    int FIX = myData.fixed;
    int LENGTH1 = myData.length1;
    char* NMEA1 = myData.nmea1;
    Serial.println(FIX);
    Serial.println(LENGTH1);
    Serial.print(NMEA1);
    Serial.println("");
    if (myData.fixed == 1)
    {
      digitalWrite(13, HIGH);
      lcd.setCursor(10, 3);
      lcd.print(" GPS Fixed");
    }
    else
    {
      digitalWrite(13, LOW);
      lcd.setCursor(10, 3);
      lcd.print("No GPS Fix");
    }
  }

  delay(1000);
}

Any help would be appreciated.
Thanks!
K-Bert

Possible duplicate of Casting a struct member between uint8_t and char, with regard to serial transfer


text:
NodeMCU keeps disconnecting
I have made a home automation system consisting of a NodeMCU, 4 channel relay board running on Blynk and IFTTT.
At the moment I'm only controlling a string of fairy lights and two LED strips from it, both connected to the relay of course.
The only code running on the NodeMCU is the Blynk ESP8266 Standalone code. Here it is (with the necessary changes of course) -

#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>

// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "YourAuthToken";

// Your WiFi credentials.
// Set password to "" for open networks.
char ssid[] = "YourNetworkName";
char pass[] = "YourPassword";

void setup()
{
  // Debug console
  Serial.begin(9600);

  Blynk.begin(auth, ssid, pass);
  // You can also specify server:
  //Blynk.begin(auth, ssid, pass, "blynk-cloud.com", 80);
  //Blynk.begin(auth, ssid, pass, IPAddress(192,168,1,100), 8080);
}

void loop()
{
  Blynk.run();
  // You can inject your own code or combine it with other sketches.
  // Check other examples on how to communicate with Blynk. Remember
  // to avoid delay() function!
}

Now the thing is, the NodeMCU automatically disconnects from the WiFi randomly. Sometimes it reconnects immediately, sometimes it doesn't reconnect at all and I have to keep hitting the reset button to get it working again.
This is really annoying as everything I got connected to the NodeMCU also comes on all of a sudden and scares the hell out of me.
The code is all fine, the power supply is stable (5v 1A), all the cables are in place and the NodeMCU is tucked away in a corner where nobody touches it.
I can't seem to work out why is this happening.
Any fixes for this?

esp8266 core version? try 2.4.2 or 2.5.2. does it happen only on relay switching? is WiFi reception good at the location?

@Juraj The NodeMCU is literally like 10 cm from the router. And no, it happens randomly. There is no pattern or trigger whatsoever to the disconnection. Could you please elaborate on the ESP core thing?

@Juraj I've got 2.5.2.

I use Blynk almost 2 years now and yesterday it did suddenly disconnect for the first time. so it could be a temporary problem with Blynk cloud

@Juraj Nope. It has been happening to me. It happened in my previous project too

and did you try esp8266 package version 2.4.2?

in my projects with esp8266 I had problems only with servers on esp8266 (a known problem of SDK), but clients worked good

I had this same issue with an ESP8266 NodeMCU-12E using Cayenne in the past. It would drop connection for no apparent reason, but no matter what, most of the time it'd never reconnect until a reset. Here's what I did:
CAYENNE_DISCONNECTED(){
  Serial.println(F("Cayenne disconnected, rebooting..."));
  ESP.restart();
}

I've never used Blynk before, but after a quick look, this may do the same thing (untested):
if (! Blynk.connected){
  Serial.println(F("Blynk disconnected, rebooting..."));
  ESP.restart();
}

It effectively reboots the ESP unit if the connection to Blynk drops for any reason.

Just a side-note: In my case, my ESP was simply polling an Arduino Metro Mini over a serial connection (using a pair of Cat-5 Ethernet cable) inside of my water purification plant, then sending that data over wifi to my network inside my house. My point here is that I never had to worry about the pin state or anything after the reboot. More care may be needed if your ESP is in an important cycle doing sensor or other work, and not just relaying information or other basic/non-critical tasks

My ESP does automatically reboot after the connection drops. The problem is, whenever this, happens all the appliances connected to the ESP come on. Hence, I don't want it to drop connection at all


text:
How to control a DC Motor with absolute encoder using Arduino and Motor Driver?
I am a beginner in Arduino, I have only basic knowledge and a big appetite :)
I'm working on my cable-cam project. I've made all the mechanical parts by myself, bought all electricity parts through eBay, and everything works fine so far. With the basic RC controller I steer forward / back and I also have a speed potentiometer.
Now there is a question of security:
Since cable-cam runing on a rope fastened to two hubs/buildings/trees/piers,
up to 40 mph.
I would like to have the opportunity to program two points through which the cable-cam cannot overdrive, so that it would not go to the end of the rope and break itself.
THE concept: cable-cam is driven to point A and is marked. Then it is driven to point B and also marked. When the cable-cam reaches point B, it stops and can not go further, but it can go back to point A. And vice versa. Something like a "operation range control points" that can be programmed. Something like this: end points with Hall sensor
THE idea: on a non-powered wheel (for avoiding slippage and incorrect reading of data on the encoder), I'll set an absolute encoder to measure axis rotations and thus calculate the distance in both directions. The encoder would then be connected to the Arduino that would send the ESC signal to stop the engine when it reached that point, A or B. Stopping should be soft, not at the moment. The speed of the cable cam can be significant, so abrupt stoppage would also be a problem.
So...am I pre-ambitious? I need help with code for Arduino.
Parts:
RC: Turnigy 9X
ESC:Syren 50A and it has an Arduino library,
and the encoder:Koyo TRD NA1024NW

tie a string from A to B. the string passes through the carriage of the device. attach a "stopper" at each end of the travel. something like this https://www.google.co.in/search?q=drawstring+cord+lock&source=lnms&tbm=isch  .... then use a switch on each side of the carriage to detect the end points

Cannot do that,  I need more sturdy solution...

This is a quite high-level question, so I will answer in general terms,
skipping the fine details. You can ask here more specific questions once
you are implementing the stuff.
Yours is a 10-bit absolute encoder. It can tell you its shaft position
with a resolution of 1/1024 revolution. It's way overkill for your
application. I suggest you connect only the four most significant bits
(pins 9 – 12), which will give you a resolution of 1/16 revolution.
It's better to read the four bits simultaneously. This can be done using
direct port
manipulation. I
would connect pins 9 – 12 of the encoder to pins 4 – 7 of the Arduino
respectively. As the encoder outputs are open-collector, you have to
enable the pullups in setup():
PORTD |= 0xf0;  // enable pullups on pins 4..7

and you can read the encoder simply as
uint8_t ecoder_value = PIND & 0xf0;

Notice that this will give you a result that is left-aligned. This way
you can treat it as an 8-bit Gray code.
Next step is to decode the Gray code. I let you research how to do that,
as you can probably find examples, or even ready-made libraries for
that.
Next, you have to extend the value to a wider bit length in order to
know the absolute position of the cable-cam. The encoder only tells you
where you are within a revolution, but it doesn't tell you how many
revolutions you did. The extension is done by comparing the current
encoder position with the previous one, taking the difference (which can
be positive or negative), and adding it to the previously computed
absolute position. Something like this:
int32_t absolute_position;

void update_absolute_position(uint8_t encoder_position)
{
    uint8_t old_position = absolute_position;  // extract LSB
    int8_t delta = encoder_position - old_position;
    absolute_position += delta;
}

Beware of the types of the variables. The type of delta, for instance,
ensures that the result of the subtraction is wrapped the correct way to
yield a number between −128 and +127. Thus, the sign will tell you which
is the shortest path (clockwise or counterclockwise) from the previous
to the current position.
Note also that you have to call this function frequently enough: more
than once per half revolution. Otherwise it won't know which direction
the wheel turned. If your loop() runs fast enough (you don't use
delay(), right?), you just have to call this function once in
loop(). Otherwise you would have to setup a timer interrupt to ensure
the updates are frequent enough.
Lastly, you have to define the limits:
int32_t left_limit = INT32_MIN;
int32_t right_limit = INT32_MAX;

// To set the left limit to the current position:
if (user_pressed_the_relevant_button()) {
    left_limit = absolute_position;
}
// and likewise for the right limit.

and condition the maximum speed on the distance to the closets limit.
Assuming you store the speed as a signed number (the sign being the
direction), you would constrain it to always be between a negative
min_speed and a positive max_speed, which could be updated as
follows:
// Slow down if close to a position limit.
if (absolute_position - left_limit < BREAKING_DISTANCE) {
    min_speed = map(absolute_position,
        left_limit, left_limit + BREAKING_DISTANCE,
        0, -ABSOLUTE_MAX_SPEED);
} else {
    min_speed = -ABSOLUTE_MAX_SPEED;
}
if (right_limit - absolute_position < BREAKING_DISTANCE) {
    max_speed = map(absolute_position,
        right_limit - BREAKING_DISTANCE, right_limit,
        +ABSOLUTE_MAX_SPEED, 0);
} else {
    max_speed = +ABSOLUTE_MAX_SPEED;
}
speed_to_apply = constrain(requested_speed, min_speed, max_speed);

Note that this makes the speed limit a linear function of the position.
You may want to look into easing functions to have a smoother breaking.

Thx everyone for your effort to help me!!
I am aware that specific absolute encoder is overkill for my project, but I need it because of high rpm count. Cable-cam runs up to 40 mp/h and wheel is rotating up to 1500rpm. I have no problem to use it at lower resolutions.
Main point is to free drive cable-cam between two points, in any direction, at any speed. ONLY when cable-cam reach one of predefine points-it stops. Softly. You can manually drive it backwards, but you cannot go beyond that point.

Ufffff guys... This is soooo over me and my knowledge. I belive that I need to outsource somebody for this work...
In my head "little devil" told me: " you can do it, you just need two secure points, how hard it can be?"
Well...now I know :)))
So...if there is anyone willing to do complete code for me...I am sure that we will find some way to compesate that amount of work

@littlerock: You should probably try to find some help close to where you live. At some point you will have to debug and fine tune the firmware, which would require modifying the code and testing on the real hardware. If the person writing the code and the person doing the test are megameters apart, that won't be easy...

It is quite difficult to say any thing without the actual code, but if you are reading the position of the cam regularly you can implement a "if/else" condition. Some thing like this:
if(position==A)
reverse();
else
continue;

(this is very crude and undefined and there are many ways  to improve it)
Here position is assumed to be the position of the cam and A is the maximum that can be traversed to. A same condition can be applied in case of the other end as well. (also reverse() is a function that reverses the direction of motion. In addition to this, you can replace reverse() by some thing like stop() and after that check "position" is greater than A call the reverse function till the condition is met.
Hope this helped.


text:
How to pass AT commands to LoRa from ESP32 UART?
I have connected a Reyax RYLR998 LoRa module to an ESP32's UART2, but AT commands passed through Hardware serial are not working.
#define RXD2 16
#define TXD2 17

void setup() {
    Serial.begin(115200);
    Serial2.begin(115200, SERIAL_8N1, RXD2, TXD2);

    Serial.print("\nSetting Lora Module \n");

    Serial2.print("AT+BAND=865000000\r\n");
    if (Serial2.available())
        Serial.println(Serial2.read());
    delay(1000);

    Serial2.print("AT+ADDRESS=1\r\n");
    if (Serial2.available())
        Serial.println(Serial2.read());
    delay(1000);

    Serial2.print((String)"AT+NETWORKID=5\r\n");
    if (Serial2.available())
        Serial.println(Serial2.read());
    delay(1000);
}

void loop() {
    while (Serial2.available()) {
        Serial.print(char(Serial2.read()));
    }
}

I tried
Serial2.print((String)"AT+NETWORKID=5\n");
Serial2.println((String)"AT+NETWORKID=5\r");
Serial2.print((String)"AT+NETWORKID=5\r");

Nothing worked, no response from AT command. Please help me I have been working on this problem for 2 days.

[![Here all AT commands works well][2]][2]

Add a wiring diagram to your question and a link to the documentation for your Lora module. You appear to have set the baud rate of the Lora module's UART to 9600 but Serial2 of the ESP32 is still at 115200. These have to match. The 9600 is stored in the Lora flash for subsequent connections.

It is a good idea to try using an FTDI device to connect between the LORA module and the PC so you can issue commands through the serial console to LORA as your second picture shows. However,  you appear to connected TX and RX incorrectly. These must be crossed over. TX on one device to RX on the other etc. Experiment with the baud rate on the serial console say 9600 or 115200.

Sorry, i connected it correct, wrong in image, i taken it from other place, i connected tx to rx and rx to tx

The documentation is here: https://reyax.com/products/RYLR998 . Try using the FTDI device connected to the Lora module with the USB cable connected to your PC. Ignore the ESP32 for the moment. Simply issue the command "AT" then  on the serial console and it should give a response "+OK". Start with a baud rate of 115200 on the serial console. If that fails, try down to 9600. The FTDI may not be able to supply enough power for the transmit function but should be enough for the "AT" test.

Yes, it works perfectly when connected to USB and give AT command. How long to wait and how to wait after i give AT command to lora module through ESP32 SoftwareSerial?

I would try issuing the AT command, waiting 1 second for the result to be available then do the following while (Serial2.available())  Serial.print(Serial2.read()); . Try with just the simple "AT" to start with. What baud rate did you use in the serial monitor for your successful tests with the FTDI adapter ?

Please either correct or delete the image in your question with the incorrect FTDI wiring of TX/RX. If you get a successful connection between the LORA and the ESP32 modules, please add an answer to your question with the code that you used. It may help someone else.

I literally gave-up, code is working with Node MCU, i think ESP32 need some setup etc. Thank you all.

I am new to Lora module and ESP32 and only playing around for a week.
I have successfully sent AT commands to RYLR998 module via ESP32 and received messages via other RYLR998 connected to another computer via USB UART serial.  You need use trim() before you send your string to Serial2.(ryltr998)
trim()
[StringObject Function]
Description
Get a version of the String with any leading and trailing whitespace removed. The trim() function modifies the String in place rather than returning a new one.

Syntax
myString.trim()


text:
Example code and documentation on using Firmata communication in native Java
I have been trying for some time to get documentation on using Java and a Firmata client library for the communication between a PC and an Arduino. Please note I want to use Java only, i.e., not Processing.
Up to now I used the excellent Haskell library hArduino for Firmata communication with Arduino boards.
Now I am teaching a Java course at the university as a PhD student. Therefore I need to use Java. However, compared to Haskell there are no centralized libraries, packages, documentation as with Haskell.
So I used Google to find more information on using Firmata client libraries for Java. Unfortunately, the search results are polluted with irrelevant results about Processing and Javascript. Therefore I ask here.
According to the Firmata client library page, there are two Java client libraries. However, only 4ntoine seems to be up to date, while the Javarduino project seems abandoned.
So I guess the standard way is to use the "4ntoine" Java client library. Or are there other options?
(I am not interested in Processing or Javascript.)
Question: Where do I find up-to-date documentation and example code on using Firmata client libraries for Java?

Can someone create the firmata and java tags?

Maybe this can work for you.
Some months ago i used RXTXcomm library [1] to send Arduino data to a Program i made in java and store in in a file, it works fine with some issues:

I made the Java programm in linux but just works in java 6, so in the windows pc of the client i installed that version, i don't know if works with java7 or java8 in windows.
Java programm reads data from Arduino sketch with Serial.print() function, Arduino continously is using this function, i lose some data, so i had to put a short delay to java programm get all data send by Arduino.

[1] http://rxtx.qbang.org/wiki/index.php/Main_Page

Maybe JArduino can give you some useful information.
Check the native code in jardunio.core.

Link only answers are frowned upon because they don't add much value. Please expand your answer with information on why it is useful or make a comment instead.


text:
Need help rewriting a program
I can't use this program on my Arduino Uno since the max is 16 bits. I need my water pump to run for 5 min, then wait for 60 min.
int motorPin = A0;
int blinkPin = 13;

int watertime = 300000; // how long to water in miliseconds
int waittime = 3600000; // how long to wait between watering

void setup() {
    pinMode(motorPin, OUTPUT);
    pinMode(blinkPin, OUTPUT);
}

void loop() {
    digitalWrite(motorPin, HIGH);
    digitalWrite(blinkPin, HIGH);
    delay(watertime);
    digitalWrite(motorPin, LOW);
    digitalWrite(blinkPin, LOW);
    delay(waittime);
}

Changed int to:
#define watertime 300000
#define waittime 3600000

But it does not work.

Use the long type instead
long watertime = 300000; // how long to water in miliseconds
long waittime = 3600000; // how long to wait between watering

You might want to use unsigned long instead of long and qualify your literals with UL on the end (eg 3600000UL).

For any delays longer than a few seconds you really need to use a Real-Time Clock chip, like the popular DS1307 from Maxim. The Arduino's delay() function is only very roughly accurate, and even less so when used as you are using it.
If you can't get a DS1307 or something similar (there's plenty to choose from) or you Arduino has too much connected already to allow anything else to be added, you could use the Time library to simulate one.  The Time library is also useful if you do have an RTC attached.

http://playground.arduino.cc/code/time

Eh. The Arduino libraries do actually compensate for the inaccuracies in delay() et alia, but a RTC is a better call regardless.

@IgnacioVazquez-Abrams They try to compensate for the inaccuracies, but when you're running from a ceramic oscillator there's only so much you can do - and any interrupts you have occurring will break that compensation anyway.

If did not misunderstand, you want a longer delay. Why don't you use a for loop in order to obtain such a delay.
for(int i = 0; i < 50; i++) {
    delay(1000);
}

This produces 50 seconds instead of 1 second. You can replace 1000 and 50 according to your needs. This is just an example.

Maybe because delay(50000) is simpler and does the same thing.

I believe it's better to put the Arduino to sleep instead of using the delay function.
You can use a library called Sleep_n0m1 for the purpose.
Modify your code like following.
#include <Sleep_n0m1.h>

int motorPin = A0;
int blinkPin = 13;

unsigned long watertime = 300000UL; // how long to water in miliseconds
unsigned long waittime = 3600000UL; // how long to wait between watering
Sleep sleep;

void setup()
{
    pinMode(motorPin, OUTPUT);
    pinMode(blinkPin, OUTPUT);
}

void loop()
{
    digitalWrite(motorPin, HIGH);
    digitalWrite(blinkPin, HIGH);
    sleep.pwrDownMode();
    sleep.sleepDelay(watertime);
    digitalWrite(motorPin, LOW);
    digitalWrite(blinkPin, LOW);
    sleep.pwrDownMode();
    sleep.sleepDelay(waittime);
}

Hope this would solve the problem.


text:
Unable to configure Ethernet using Arduino Uno R3
I have purchased an Arduino Uno R3 board and a LAN shield from these locations:

Arduino UNO R3
Arduino LAN shield

I am trying to configure Ethernet using this sketch:
#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = {
  0x4,0x2,0x45,0x68,0x5E,0x96,0x56
};

// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  delay(5000);
  // this check is only needed on the Leonardo:
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }
  // start the Ethernet connection:
  Serial.println("trying to configure ethernet...");
  while(Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP, retrying after 5 sec");
    // no point in carrying on, so do nothing forevermore:
    delay(5000);
    Serial.println("trying to configure ethernet...");
  }
  // print your local IP address:
  Serial.print("My IP address: ");
  for (byte thisByte = 0; thisByte < 4; thisByte++) {
    // print the value of each byte of the IP address:
    Serial.print(Ethernet.localIP()[thisByte], DEC);
    Serial.print(".");
  }
  Serial.println();
}

void loop() {
}

It generates this output in the Serial Monitor:
trying to configure ethernet...
Failed to configure Ethernet using DHCP, retrying after 5 sec
trying to configure ethernet...
Failed to configure Ethernet using DHCP, retrying after 5 sec
trying to configure ethernet...
Failed to configure Ethernet using DHCP, retrying after 5 sec
trying to configure ethernet...
Failed to configure Ethernet using DHCP, retrying after 5 sec
trying to configure ethernet...
Failed to configure Ethernet using DHCP, retrying after 5 sec
trying to configure ethernet...
Failed to configure Ethernet using DHCP, retrying after 5 sec
trying to configure ethernet...
Failed to configure Ethernet using DHCP, retrying after 5 sec
trying to configure ethernet...

I have captured the LED indicators on video on YouTube, it shows Tx and Rx LEDs glowing occasionally, see Arduino not detecting the ethernet connection.
It looks like the Arduino is not able to connect to the Ethernet... I am using the Arduino IDE 1.6.5 on Windows 7.
Is there any debug tool for Arduino that can be used to figure out this issue?

What is the Arduino connected to via Ethernet? (I didn't watch the video.)

Might need to set the SD enable pin to output and high.

Is the MAC address correct? Does the Ethernet to which the Arduino is connected have a DHCP capable router (in other words, is there a DHCP server enabled)?

Are you using version 1.0, or above, of the library, as this supports DHCP? see Ethernet.begin(). Earlier versions (v0.x) did not apparently.

Just asking, shouldn't the MAC address have 6 bytes and not 7 like in your code?

I see you have 7 bytes for your Mac address. Most examples I have seen only have 6 bytes. Are you using TCPIP v4 or v6? Strange.

I use more or less the same code to do my networked widgets and it has been quite reliable in my experience. Do you know if you have a DHCP server on the network segment that the Arduino is on? The absence of a server or a configuration that won't respond to the Arduino seem like the most likely explanation for the problem you're seeing.
The way to troubleshoot this would be to get another machine on the same network segment and watch the traffic with tcpdump or Wireshark or a similar tool. If you're running on a "third party" machine (e.g. not the DHCP server) then you'll be able to see the Arduino's side of the DHCP exchange, but I'm not sure if you'll be able to see the server (the Arduino will be broadcasting since it can't know the address of the DHCP server, but I think the server's response is unicast). If you've got a Linux box or some other machine that you can log into where you could run the DHCP server you can watch both sides of the negotiation. But even if you can't get to the server it will help to see if the Arduino is starting the DHCP negotiation.
If you need a fixed IP address on the Arduino, the way to do it is to configure the DHCP server to reserve an address for the Arduino. That way you can have a known address on the Arduino without having to hard code an IP address (which will eventually bite you).

Good answer w.r.t. reserving the IP address on the router/DHCP server

I never used the DHCP feature to assign an IP address for the Ethernet shield, but somewhere in there you have to list the IP of the router that assigns the DHCP.
In everyday use of the shield, you don't want your router to assign an IP address to your device because every time it connects it might get a different IP address. That means if you want to communicate with it, you need to discover the IP address each time. And communicating with it from the WAN side through a port you open in your router would be impossible.
Try one of the fixed IP address sketches, but select a free IP address in your router's IP range that isn't, also, in the router's DHCP IP range (that way the fixed IP address won't interfere with the IP addresses given out automatically).

Good answer w.r.t. using a static address (although it would require reserving on the DHCP server, see diu's answer) and testing the board using the fixed IP address sketches, except that you do not need to specific the DHCP server, or router, address. See Ethernet.begin()


text:
First recieved packet not displayed (Arduino with MRF24j40MA)
I'm trying to make two Arduino cards communicate, one is a sender and the other only receive packet from the first one and then display them.
My problem is that the first recieved packet is not displayed unlike the other packets(displayed normally)
here's the output of my code :

Here's my code of the reciever :
void handle_rx() {

Serial.print("received a packet ");Serial.print(mrf.get_rxinfo()->frame_length, DEC);Serial.println(" bytes long");

if(mrf.get_bufferPHY()){
  Serial.println("Packet data (PHY Payload):");
  for (int i = 0; i < mrf.get_rxinfo()->frame_length; i++) {
      Serial.print(mrf.get_rxbuf()[i]);
  }
}

Serial.println("\r\nASCII data (relevant data):");
for (int i = 0; i < mrf.rx_datalength(); i++) {
    Serial.write(mrf.get_rxinfo()->rx_data[i]);
}

Serial.print("\r\nLQI/RSSI=");
Serial.print(mrf.get_rxinfo()->lqi, DEC);
Serial.print("/");
Serial.println(mrf.get_rxinfo()->rssi, DEC);
}

Here is the complete sketch:
/**
 * Example code for using a microchip mrf24j40 module to send and receive
 * packets using plain 802.15.4
 * Requirements: 3 pins for spi, 3 pins for reset, chip select and interrupt
 * notifications
 * This example file is considered to be in the public domain
 * Originally written by Karl Palsson, karlp@tweak.net.au, March 2011
 */
#include <SPI.h>
#include <mrf24j.h>

const int pin_reset = 6;
const int pin_cs = 7; // default CS pin on ATmega8/168/328
const int pin_interrupt = 2; // default interrupt pin on ATmega8/168/328

Mrf24j mrf(pin_reset, pin_cs, pin_interrupt);

long last_time;
long last_time2;
long tx_interval = 1000;

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

  mrf.reset();
  mrf.init();

  mrf.set_pan(0xcafe);
  // This is _our_ address
  mrf.address16_write(0x4201);

  // uncomment if you want to receive any packet on this channel
  //mrf.set_promiscuous(true);

  // uncomment if you want to enable PA/LNA external control
  //mrf.set_palna(true);

  // uncomment if you want to buffer all PHY Payload
  //mrf.set_bufferPHY(true);

  attachInterrupt(0, interrupt_routine, CHANGE); // interrupt 0 equivalent to pin 2(INT0) on ATmega8/168/328
  last_time = millis();
  interrupts();
}

void interrupt_routine() {
    mrf.interrupt_handler(); // mrf24 object interrupt routine
}

void loop() {
    mrf.check_flags(&handle_rx, &handle_tx);
    unsigned long current_time = millis();
    if (current_time - last_time > tx_interval) {
        last_time = current_time;
        Serial.println("txxxing...");
        mrf.send16(0x4202, "abcd");
    }
}

void handle_rx() {
    Serial.print("received a packet ");Serial.print(mrf.get_rxinfo()->frame_length, DEC);Serial.println(" bytes long");

    if(mrf.get_bufferPHY()){
      Serial.println("Packet data (PHY Payload):");
      for (int i = 0; i < mrf.get_rxinfo()->frame_length; i++) {
          Serial.print(mrf.get_rxbuf()[i]);
      }
    }

    Serial.println("\r\nASCII data (relevant data):");
    for (int i = 0; i < mrf.rx_datalength(); i++) {
        Serial.write(mrf.get_rxinfo()->rx_data[i]);
    }

    Serial.print("\r\nLQI/RSSI=");
    Serial.print(mrf.get_rxinfo()->lqi, DEC);
    Serial.print("/");
    Serial.println(mrf.get_rxinfo()->rssi, DEC);
}

void handle_tx() {
    if (mrf.get_txinfo()->tx_ok) {
        Serial.println("TX went ok, got ack");
    } else {
        Serial.print("TX failed after ");Serial.print(mrf.get_txinfo()->retries);Serial.println(" retries\n");
    }
}

There's something wrong with your code. It looks like there may be some parts missing from it.  Try reading this: http://snippets-r-us.com/


text:
How do I save IR codes from my LG Air Conditioner remote and replay them?
I am currently using the following code

#include <IRremote.h>

int RECV_PIN = 11;
IRrecv irrecv(RECV_PIN);
decode_results results;

void setup()
{
 Serial.begin(9600);
 irrecv.enableIRIn(); // Start the receiver
}

void loop()
{
 if (irrecv.decode(&results))
  {
   Serial.println(results.value, HEX);
   irrecv.resume(); // Receive the next value
  }
 }

The Serial Monitor is always returning "FFFFFFFF" no matter which button I press.
So I am unable to replicate the signal.
Seems that the IR library doesn't support my LG remote.
How do I save and replicate the signal in this case?

Try irrecv.decodeLG(&results)

@Gerben Can you be more specific? Where do I put the line of code?

I tried if (irrecv.decodeLG(&results)) and am getting the following error msg while complilng.

In file included from sketch_aug26c.ino:1:0:
C:\Users\Sravan\Documents\Arduino\libraries\Arduino-IRremote-master/IRremote.h: In function 'void loop()':
C:\Users\Sravan\Documents\Arduino\libraries\Arduino-IRremote-master/IRremote.h:224:10: error: 'bool IRrecv::decodeLG(decode_results*)' is private
bool  decodeLG         (decode_results *results) ;
^
sketch_aug26c:15: error: within this context
within this context

Sorry. That indeed won't work. Add Serial.println(results.decode_type); to get some additional information.

Perhaps it is wired wrongly? Please test with some other device, like your TV, to confirm the hardware part is OK.

@NickGammon No, it is wired correctly. Other remotes including my LG DVD player remote work.

@Gerben I'm getting 11 when I try Serial.println(results.decode_type);

It seems to think it's a SANYO remote. Try looking into recording the raw ir signal. https://gist.github.com/jeje/3027236

@Gerben I'm getting the following text in serial port IR code recorded! Recorded 58 intervals. Sending recorded IR signal! Sending recorded IR signal! Sending recorded IR signal!

You have to modify the code to suit your needs.

@Gerben I am a noob and I don't know what code I have to modify. Sorry. But here is some more info. The remote seems to send not only the power on signal each time it's powered on, but also temperature and other info. I have no idea how to get the raw codes and decode them.

You have to just collect a lot of these signals, then paste them into a text file in hex format, 20-30 collected signals may be enough. Then you start looking for patterns in the collected signals. After you have found the repeating pattern and formatted it so that every repeat is on a new line you should convert the hex into decimal and ascii and see if you can see where is the temperature and other data is. You can also upload it to pastebin and tell us what button did you press with each IR code you received.

@Wally: Did you solve it? I've got the same problem, IRrecvDumpV2 always reads FFFF FFFF from LG air conditioner remote, no matter which key. Also identifies it as Sanyo.


text:
avr-g++ (or avr-gcc) and LiquidCrystal library
I'm trying to run a simple Hello World program from Arduino 1.6.5 from terminal. When I run it in Arduino IDE, it works good. When I'm trying to get it by avr-g++ I have hard way to figure out how to include all libraries - so far I got this script:
avr-g++ -Os -DF_CPU=16000000UL -mmcu=atmega328p -c -o main.o main.cpp
-I"../arduino-1.6.5-r5/libraries/LiquidCrystal/src/"
-I"../arduino-1.6.5-r5/hardware/arduino/avr/cores/arduino/"
avr-g++ -mmcu=atmega328p main.o -o main
avr-objcopy -O ihex -R .eeprom main main.hex
sudo avrdude -F -V -c arduino -p ATMEGA328P -P /dev/ttyACM1 -b 115200 -U flash:w:main.hex

First line (with both -I flags) compiles, but after running second line, I get:
main.o: In function `main':
main.cpp:(.text.startup+0xa): undefined reference to `LiquidCrystal::begin(unsigned char, unsigned char, unsigned char)'
main.cpp:(.text.startup+0x16): undefined reference to `Print::print(char const*)'
main.o: In function `_GLOBAL__sub_I_lcd':
main.cpp:(.text.startup+0x3a): undefined reference to `LiquidCrystal::LiquidCrystal(unsigned char, unsigned char, unsigned char, unsigned char, unsigned char, unsigned char)'
collect2: error: ld returned 1 exit status

How can I also include some libraries? I need the exact bash script.

Have you tried duplicating every nitty little step the IDE goes through.

I don't know how, though.

possible duplicate of not using the IDE and understanding the compilation/linking/upload process

I made a Makefile to compile the Blink program a little while back. It wasn't trivial.
#
# Simple Arduino Makefile
#
# Author: Nick Gammon
# Date: 18th March 2015

# where you installed the Arduino app
ARDUINO_DIR = C:/Documents and Settings/Nick/Desktop/arduino-1.0.6/

# various programs
CC = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-gcc"
CPP = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-g++"
AR = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-ar"
OBJ_COPY = "$(ARDUINO_DIR)hardware/tools/avr/bin/avr-objcopy"

MAIN_SKETCH = Blink.cpp

# compile flags for g++ and gcc

# may need to change these
F_CPU = 16000000
MCU = atmega328p

# compile flags
GENERAL_FLAGS = -c -g -Os -Wall -ffunction-sections -fdata-sections -mmcu=$(MCU) -DF_CPU=$(F_CPU)L -MMD -DUSB_VID=null -DUSB_PID=null -DARDUINO=106
CPP_FLAGS = $(GENERAL_FLAGS) -fno-exceptions
CC_FLAGS  = $(GENERAL_FLAGS)

# location of include files
INCLUDE_FILES = "-I$(ARDUINO_DIR)hardware/arduino/cores/arduino" "-I$(ARDUINO_DIR)hardware/arduino/variants/standard"

# library sources
LIBRARY_DIR = "$(ARDUINO_DIR)hardware/arduino/cores/arduino/"

build:

    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(MAIN_SKETCH) -o $(MAIN_SKETCH).o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/malloc.c -o malloc.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)avr-libc/realloc.c -o realloc.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WInterrupts.c -o WInterrupts.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring.c -o wiring.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_analog.c -o wiring_analog.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_digital.c -o wiring_digital.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_pulse.c -o wiring_pulse.c.o
    $(CC) $(CC_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)wiring_shift.c -o wiring_shift.c.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)CDC.cpp -o CDC.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HardwareSerial.cpp -o HardwareSerial.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)HID.cpp -o HID.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)IPAddress.cpp -o IPAddress.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)main.cpp -o main.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)new.cpp -o new.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Print.cpp -o Print.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Stream.cpp -o Stream.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)Tone.cpp -o Tone.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)USBCore.cpp -o USBCore.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WMath.cpp -o WMath.cpp.o
    $(CPP) $(CPP_FLAGS) $(INCLUDE_FILES) $(LIBRARY_DIR)WString.cpp -o WString.cpp.o
    rm core.a
    $(AR) rcs core.a malloc.c.o
    $(AR) rcs core.a realloc.c.o
    $(AR) rcs core.a WInterrupts.c.o
    $(AR) rcs core.a wiring.c.o
    $(AR) rcs core.a wiring_analog.c.o
    $(AR) rcs core.a wiring_digital.c.o
    $(AR) rcs core.a wiring_pulse.c.o
    $(AR) rcs core.a wiring_shift.c.o
    $(AR) rcs core.a CDC.cpp.o
    $(AR) rcs core.a HardwareSerial.cpp.o
    $(AR) rcs core.a HID.cpp.o
    $(AR) rcs core.a IPAddress.cpp.o
    $(AR) rcs core.a main.cpp.o
    $(AR) rcs core.a new.cpp.o
    $(AR) rcs core.a Print.cpp.o
    $(AR) rcs core.a Stream.cpp.o
    $(AR) rcs core.a Tone.cpp.o
    $(AR) rcs core.a USBCore.cpp.o
    $(AR) rcs core.a WMath.cpp.o
    $(AR) rcs core.a WString.cpp.o
    $(CC) -Os -Wl,--gc-sections -mmcu=$(MCU) -o $(MAIN_SKETCH).elf $(MAIN_SKETCH).o core.a -lm
    $(OBJ_COPY) -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $(MAIN_SKETCH).elf $(MAIN_SKETCH).eep
    $(OBJ_COPY) -O ihex -R .eeprom $(MAIN_SKETCH).elf $(MAIN_SKETCH).hex

I basically did this by observing what the IDE does (as Ignacio Vazquez-Abrams suggested) and replicated it. Now to add libraries you have to add even more steps.

It doesn't work well for me, even if i change everything. Linux can't find malloc.c in files.

You must be able to find them, as Ignacio Vazquez-Abrams suggested. Turn on verbose compiling, do a compile, and see where the IDE finds them.

Ok, I found them. Thanks. I'll post tomorrow results.


text:
Basic communication between Cotek and Arduino UNO
I am trying to get a reading from my Cotek through my Arduino and have it display on an LCD screen. When I run the code, though, nothing shows up. I am EXTREMELY new to using pretty much all this equipment so honestly, I have little to no idea what I'm doing. I am not sure if it is a wiring issue, an issue with the code or both. Any and all help is appreciated.
This is how the cotek is wired to the Arduino. The middle red wire (in the middle of the two resistors) is connected to AUX from the cotek. The two outer red wires are connected to the SDA and SCL of the cotek and their corresponding blue wires are connected to the SDA and SCL of the Arduino (the two resistors are 2KOhm pull-up resistors). The blue wire on the bottom is connected to the GRND of the cotek which is also connected to GRND of the Arduino.

This is my code using the I2C protocol:

#include <LiquidCrystal.h>
#include <Wire.h>

int analogPin = 5;
char address= 0;
int numBytes = 2;
char val = 0;
int debug = 5;
LiquidCrystal lcd(12, 11, 10, 5, 4, 3, 2);

void setup() {
  // put your setup code here, to run once:
  Wire.begin();
  Serial.begin(9600);
  lcd.begin(16, 2);
  lcd.clear();
}

void loop() {
  // put your main code here, to run repeatedly:
  Wire.requestFrom(address, numBytes);
  while(Wire.available())
  {
    val = Wire.read();
    Serial.print(val);
    lcd.setCursor(0,0);
    lcd.print(val);
  }
  //perform function to change val from hexadecimal to decimal number here
  delay(500);

I am pretty sure the LCD is wired correctly to the Arduino as I was able to communicate to it previously without using the Cotek. In any case, it doesn't matter as 'val' doesn't even appear on the serial monitor.
Again, any help would be appreciated. Thanks!

What's a Cotek?

Surely the Cotek does not use address 0? char address= 0; See my I2C page for a small scanner that will tell you the address of any I2C devices. This would also confirm that your wiring is OK.

Hi, thanks for the response. I tried running the code for the scanner and in my Serial monitor, all I got are random symbols that change each time I run it.


text:
How to get the scan duration below 1 sec with Arduino BLE?
I want to scan continuously for other Bluetooth devices with my ESP32 using BLE. The scan method only accepts integers larger than 0, such as scan->start(1, false). However I want the results to be more "responsive" and a 1-second scanning duration is too long. This is my sample code:
#include <Arduino.h>
#include <BLEAdvertisedDevice.h>
#include <BLEDevice.h>
#include <BLEScan.h>
#include <string>
#include <iostream>

const int PIN = 2;
const int CUTOFF = -40;
BLEScan* scan;

#define SERVICE_UUID "f5aeb701-4395-4387-b8d4-e1f542b05151"
#define CHARACTERISTIC_UUID "b2bd617f-6f78-45e7-bfdd-3edf29a5661a"

void setup() {
  pinMode(PIN, OUTPUT);
  BLEDevice::init("ESP32 GrooveBrick");
  Serial.begin(9600);
  BLEServer *pServer = BLEDevice::createServer();
  BLEService *pService = pServer->createService(SERVICE_UUID);
  BLECharacteristic *pCharacteristic = pService->createCharacteristic(
    CHARACTERISTIC_UUID,
    BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_WRITE);
  pService->start();
  BLEAdvertising *pAdvertising = BLEDevice::getAdvertising();
  pAdvertising->addServiceUUID(SERVICE_UUID);
  pAdvertising->setScanResponse(true);
  pAdvertising->setMinPreferred(0x06);  // functions that help with iPhone connections issue
  pAdvertising->setMinPreferred(0x12);
  scan = BLEDevice::getScan();
  scan->setActiveScan(true);
  /*!< Scan interval. This is defined as the time interval from
    when the Controller started its last LE scan until it begins the subsequent LE scan.
    Range: 0x0004 to 0x4000 Default: 0x0010 (10 ms)
    Time = N * 0.625 msec
    Time Range: 2.5 msec to 10.24 seconds*/
  scan->setInterval(100); //interval (how often there is a scan)
  /*!< Scan window. The duration of the LE scan. LE_Scan_Window
    shall be less than or equal to LE_Scan_Interval
    Range: 0x0004 to 0x4000 Default: 0x0010 (10 ms)
    Time = N * 0.625 msec
    Time Range: 2.5 msec to 10240 msec */
  scan->setWindow(99);  // window (how long the scans are) must be <= interval
  BLEDevice::startAdvertising();
}

void loop() {
  BLEScanResults results = scan->start(1, true);
  int best = CUTOFF;

  std::cout << "Scanning!" << "\n";
  for (int i = 0; i < results.getCount(); i++) {
    BLEAdvertisedDevice device = results.getDevice(i);
    std::cout << "Found BT-device: " << device.getName() << " RSSI: " << std::to_string(device.getRSSI()) << "\n";
    int rssi = device.getRSSI();
    if (rssi > best) {
      best = rssi;
    }
  }
  digitalWrite(PIN, best > CUTOFF ? HIGH : LOW);
  scan->clearResults();   // delete results fromBLEScan buffer to release memory
}

Did you ever resolve this issue?

Hi, IIRC I never solved this.. sry

You can't using the callback from that function, but what you can do is add you own callback that will receive every new radio event.
Add this to your init code:
BLEDevice::setCustomGapHandler(custom_handler);

and this before it:
static void it_gap_cb(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param)
{
    switch (event)
    {
        case ESP_GAP_BLE_SCAN_RESULT_EVT:
            if (param->scan_rst.search_evt == ESP_GAP_SEARCH_INQ_RES_EVT)
            {
                // This event is triggered every time a new device is found, and contains the advertised data.
                // We should avoid processing or printing anything here to avoid hardware congestion
                // log_i("ESP_GAP_BLE_SCAN_RESULT_EVT");

                if (param->scan_rst.ble_adv != NULL)
                {
                    //this makes sure that there is data to be processed
                }
            }
            break;
        default:
            // log_i("Event %d unhandled", event);
            break;
    }
}

the simplest solution is this:
add this line:
BLEDevice::getScan()->stop();

Example:
#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEScan.h>
#include <Arduino.h>

class MyAdvertisedDeviceCallbacks : public BLEAdvertisedDeviceCallbacks {
  void onResult(BLEAdvertisedDevice advertisedDevice) {
    // Hole die Service-Daten vom beworbenen Gerät
    //std::string serviceData = advertisedDevice.getServiceData();
    std::string deviceName = advertisedDevice.getName();
    if (!deviceName.empty() && deviceName.find("Drone_") != std::string::npos) { // Verwende .empty() anstelle von !
    Serial.println("Scan-Ergebnis gefunden:");

    // Ausgabe des Gerätetyps und der RSSI-Signalstärke
    Serial.print("Gerätename: ");
    Serial.println(advertisedDevice.getName().c_str());
    Serial.print("Signalstärke (RSSI): ");
    Serial.println(advertisedDevice.getRSSI());
    }

    BLEDevice::getScan()->stop();
  }
};

void setup() {
  Serial.begin(115200);
  delay(3000); // 1 Sekunde warten
  Serial.println("Startet kontinuierlichen BLE-Scan...");

  // BLE initialisieren
  BLEDevice::init("");

  // BLE-Scan konfigurieren
  BLEScan* pBLEScan = BLEDevice::getScan();
  pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
  pBLEScan->setActiveScan(true); // Aktives Scannen für genauere RSSI-Werte
  pBLEScan->setInterval(32);    // Scan-Intervall in 0.625ms-Einheiten
  pBLEScan->setWindow(32);       // Scan-Fenster in 0.625ms-Einheiten

}

void loop() {
  // Starte den Scan ohne zeitliche Begrenzung und bereinige die Ergebnisse direkt danach
  BLEDevice::getScan()->start(0.1, true); // kurzer Scan, um wiederholte Ergebnisse zu ermöglichen

  //int deviceCount = BLEDevice::getScan()->getResults().getCount();
  //Serial.print("Anzahl gefundener Geräte: ");
  //Serial.println(deviceCount);

  BLEDevice::getScan()->clearResults();    // Bereinige die Ergebnisse sofort für den nächsten Scan
}


text:
How to share a library on Arduino Playground?
I have written an ISR-based timer library for Arduino Uno and I would like to share it on the website and get it reviewed.
But I am stuck on how to post it to playground.

The Arduino Playground library list is a wiki page (like everything on the playground). That means anyone can log in to edit it and add links to their own libraries. The "Log In" and "Sign Up" links are at the top right of the Arduino site. When you first go to edit a Playground page you'll be taken to a "Password required" page but don't worry, this is only to prevent spam and the password is pre-filled. You only need to click the "I'm not a robot" checkbox, wait for the green checkmark to appear, then click "Submit".
There are a couple of important things to note though. Firstly, the Playground library list isn't there for getting your work reviewed. It's a place to post things that are functional and ready to be used by other people. If you need someone to help with your project then you can maybe post on the Arduino forums. Alternatively, if you have specific questions, you can post here on Arduino SE.
If you're ready to post your library online, you also have to be aware that the Playground itself won't host your code. You can put a link there and maybe some documentation. However, you'll need to host your code somewhere else, such as Github.


text:
How to get serial data in Arduino from a barcode scanner?
I want to interface my barcode scanner with an Arduino using RS232. I have connected 2 (RX), 3 (TX) and 5 (GND) of the RS232 with the corresponding pins of MAX232. I am taking TTL outputs on Arduino pins 6 and 7.
This is the code of the Arduino program:
#include <SoftwareSerial.h>

SoftwareSerial mySerial(6, 7); // RX, TX

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

void loop() {
  // run over and over
  if (mySerial.available()) {
    byte x = mySerial.read();
    Serial.println(x);
  }
}

I am not getting any output on the serial monitor when I scan a product.

Please edit your question and include your schematic.

@Ahnet : Yes at that time we had some other issues too, as mentioned in the comment so didn't put a check then.  Thanks for reminding.

Assuming your Arduino has only one hardware serial connection (it's something like an Uno rather than a Mega) you're quite right in using software serial, the Arduino will already be using pins 2 and 3 to communicate via USB to the Serial monitor so you can't use them to communicate with the scanner.
However carefully look at your first line of code, you've asked software serial to use pins 6 & 7 yet hooked the barcode scanner to pins 2 & 3. Move those pins over to the one's you've specified.
Secondly in your setup function you've begun communication with hardware Serial but not software serial. You'll need to add something like mySerial.begin(XXX) where XXX is the baud rate for the scanner.
Finally you haven't told the Arduino what pinMode to use for 6 and 7. You'll want pinMode(6, INPUT) and pinMode(7, OUTPUT) in there too.

After adding mySerial.begin(XXXX) the code did work properly.. Whenever i move the RS232 pins slightly, i get digits printed on the screen. But not when I scan.

Are you certain you've got them the right way round?

I tried this as well, for some reason it is NOT WORKING on pins 6 and 7, but it works perfectly using pins 10 and 11 instead. Of course, you still need to add the mySerial.begin().

RS 232 works on different voltage levels than Arduino, I believe the values you are getting on the screen will have no meaning whatsoever, If the scanner output is TTL then yes it would work, but in my own experience that logic is inverted and you have to add a 1 to software serial:
SoftwareSerial mySerial(6, 7, 1); // RX, TX
The first step is checking what voltage level is given by your scanner output.