texts:
I've redone a previous Arduino sketch I posted in which I was having trouble capturing encoder counts within critical statements, having no luck properly attaching and detaching interrupts.  I've studied various ISR sketches but haven't been able to produce anything that caters to my needs.
I now have a switch case in which a DC motor with CPR encoder correctly rotates back and forth between specified boundaries if it alone is in the void loop.  However, once enclosed within a critical statement (I want this action to occur only if a button is pressed), the DC motor continues to rotate only one direction.
I need assistance in where to properly attach and detach these interrupts and how to correctly pass the encoder value to the next action.  Below is what I've done so far and any help would greatly be appreciated.
#define enA 9
#define in1 6
#define in2 7

const int button1Pin = 8;

int button1State = 0;

volatile long temp, counter = 0;

long local_counter=counter;

enum {IdleState, ForwardState, BackwardState} State;

void setup() {

  Serial.begin(9600);

  pinMode(enA, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);

  Serial.begin (9600);
  pinMode(2, INPUT_PULLUP);
  pinMode(3, INPUT_PULLUP);

  attachInterrupt(0, ai0, RISING);
  attachInterrupt(1, ai1, RISING);

  pinMode(button1Pin, INPUT);

  State = IdleState;
}

void loop() {

  button1State = digitalRead(button1Pin);

   if( counter != temp ){
   Serial.print("counter = ");
   Serial.print (counter);
   Serial.print("     local counter = ");
   Serial.println(local_counter);
   temp = counter;
   }

   //if (button1State == HIGH) {

          switch (State) {

              case IdleState:
                halt ();

              if (counter<2000)
                State = ForwardState;
              break;

              case ForwardState:
                clockwise();

              if (counter>=2000)
                State = BackwardState;
              break;

              case BackwardState:
                counterclockwise();

              if (counter <=0)
                State = ForwardState;
              break;

          } // end switch
   //  }

}

void ai0() {
  if(digitalRead(3)==LOW) {
  counter++;
  }else{
  counter--;
  }
  }

void ai1() {
  if(digitalRead(2)==LOW) {
  counter--;
  }else{
  counter++;
  }
  }

void clockwise (){
    analogWrite(enA, 255);
    digitalWrite(in1, HIGH);
    digitalWrite(in2, LOW);
  }

void counterclockwise () {
    analogWrite(enA, 255);
    digitalWrite(in1, LOW);
    digitalWrite(in2, HIGH);
  }

void halt () {
    digitalWrite(in1, LOW);
    digitalWrite(in2, HIGH);
}

An explanation of my setup is as follows:
My button is a tactile button on breadboard (connected to pin 8 of an Arduino Uno),  with 5V supply from Arduino. Pins 6 of the Arduino is connected input 1 of the L298N motor driver, pin 7 of Arduino connected to input 2 of the motor driver, and pin 9 of the Adruino connected to the enable of the motor driver.  Them motor driver is being supplied by an external 12V supply which is also power the 12V DC geared motor with encoder.  The encoder outputs are connected to pin 2 and 3 of the Arduino.


texts: Problem with Software Serial: no response

texts:
I am using an Arduino Uno board with IDE 1.6.7.

I have tried to implement a tweaked version of the basic example (SoftwareSerial example) from the Software Serial library. The code is attached.

It should blink the light and print the message on the serial monitor. But I am not getting anything.

In fact, I also tried the example as it is. It did not work either.

#include <SoftwareSerial.h>

SoftwareSerial mySerial(8, 9); // RX, TX

void setup() {
    pinMode(13,OUTPUT);
    // Open serial communications and wait for port to open:
    Serial.begin(9600);
    while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
    }
    Serial.println("Goodnight moon!");
    // set the data rate for the SoftwareSerial port
    mySerial.begin(9600);
    delay(1000);
}

void loop() { // run over and over
    mySerial.println("hell");
    if (mySerial.available() > 0) {
        digitalWrite(13,HIGH);
        Serial.write("working..");
        delay(3000);
        digitalWrite(13,LOW);
        delay(2000);
    }
}


texts: NRF24L01+ (TMRH20 library): Receiver gets blank data

texts:
I am working on sample Arduino project for communication over NRF24L01+ (TMRH20 library), everything is working fine with my example except one issue my Receiver gets message but that message is blank. Now i am not sure how do i debug as per serial monitor data is getting transmitted, as per receiver serial monitor it receives data but its blank.

Transmitter code -

// SimpleTx - the master or the transmitter

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

#define CE_PIN   9
#define CSN_PIN 10

const byte slaveAddress[5] = {'R','x','A','A','A'};

RF24 radio(CE_PIN, CSN_PIN); // Create a Radio

char dataToSend[12] = "Msg AKSHAY";
//int dataToSend = 1;
char txNum = '0';

unsigned long currentMillis;
unsigned long prevMillis;
unsigned long txIntervalMillis = 1000; // send once per second

void setup() {

    Serial.begin(9600);

    Serial.println("SimpleTx Starting");

    radio.begin();
    radio.setDataRate( RF24_250KBPS );
    radio.setRetries(3,5); // delay, count
    radio.openWritingPipe(slaveAddress);
}

//====================

void loop() {
    currentMillis = millis();
    if (currentMillis - prevMillis >= txIntervalMillis) {
        send();
        prevMillis = millis();
    }
}

//====================

void send() {

    bool rslt;
    rslt = radio.write( &dataToSend, sizeof(dataToSend) );
        // Always use sizeof() as it gives the size as the number of bytes.
        // For example if dataToSend was an int sizeof() would correctly return 2

    Serial.print("Data Sent ");
    Serial.print(dataToSend);
    if (rslt) {
        Serial.println("  Acknowledge received");
        updateMessage();
    }
    else {
        Serial.println("  Tx failed");
    }
}

//================

void updateMessage() {
        // so you can see that new data is being sent
    txNum += 1;
    if (txNum > '9') {
        txNum = '0';
    }
    dataToSend[10] = txNum;
}

Receiver code -

// SimpleRx - the slave or the receiver

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

#define CE_PIN   9
#define CSN_PIN 10

const byte thisSlaveAddress[5] = {'R','x','A','A','A'};

RF24 radio(CE_PIN, CSN_PIN);

char dataReceived[10]; // this must match dataToSend in the TX
bool newData = false;

//===========

void setup() {

    Serial.begin(9600);

    Serial.println("SimpleRx Starting");
    radio.begin();
    radio.setDataRate( RF24_250KBPS );
    radio.openReadingPipe(1, thisSlaveAddress);
    radio.startListening();
}

//=============

void loop() {
    getData();
    showData();
}

//==============

void getData() {
  if ( radio.available() ) {

       radio.read( &dataReceived, sizeof(dataReceived) );
      Serial.println(dataReceived);
       newData = true;
   } else {
       Serial.println("No radio available");
   }
   delay(100);
}

void showData() {
    if (newData == true) {
        Serial.print("Data received ");
        Serial.println(dataReceived);
        newData = false;
    }
}

Below is the output TX1 (Transmitter ) and RX1 is Receiver. You can see that Transmitter even gets acknowledgment also..

Both of my devices are arduino nano and below is wiring diagram between arduino and nrf24l01.

I also saw few post where people suggested using 100uf capacitor in NRF24L01 (GND & VCC), this helped me with accuracy in connection but data is still missing.


texts: Where I can do search libraries on WEB, that similar search in IDE? I did not find search page on arduino.cc


texts: Doing several things at the same time with functions, objects or interrupts?

texts:
First of all, thank you for taking the time to read this. I am a newbie, so apologies (done examples on arduino website, basic C++).
I'm trying to get an idea of what the best way to structure a sketch is, which needs to do several things at the same time. For example, reading an IMU sensor and using it to control the mouse, reading a button for on/off and let's say flashing an LED. I have repetitive injury so this is the project I'm trying to complete, but the principle should be scalable for more complex projects.
I've come across some great resources and my understanding is you can use:

functions (e.g. blink without delay)

objects (cooperative multitasking)

interrupts

something like a RTOS

Where my limits lie is understanding the benefits/limitations of these options and picking which one to focus on for my project. For example, if using functions is sufficient, why do people bother with interrupts and installing a RTOS?
I would appreciate any guidance for what an effective approach should look like.
Thanks again.


texts:
I'm using ESP8266Ping lib inside my iot lib which hanldes Wifi connectivity and MQTT messages. Since it create its own instance called Ping when calling #include <ESP8266Ping.h>- it had to be place in iot.cpp.
I writing another library, IPmonitor which checks clients on the network (using pings), I wanted to use ESP8266Ping again.
My sketch file, create an instance of iot and IPmonitor for check/ log errors on monitored clients.
But I get error of using the same library twice.
I guess that since ESP8366Ping.h library is defined it creates an instance of the class ( see mark below ):
class PingClass {
  public:
    PingClass();

    bool ping(IPAddress dest,   byte count = 5);
    bool ping(const char* host, byte count = 5);

    int averageTime();

  protected:
    static void _ping_sent_cb(void *opt, void *pdata);
    static void _ping_recv_cb(void *opt, void *pdata);

    IPAddress _dest;
    ping_option _options;

    static byte _expected_count, _errors, _success;
    static int _avg_time;
};

#include "ESP8266Ping.impl.h"
PingClass Ping;                     // <----- This

#endif

How can it be solved ?


texts: How to connect more than 10 sensors to Arduino uno r3

texts: How I can connect more than 10 sensors to Arduino Uno R3? I calculated it and I can connect just 4 fire flame sensors (sensors which can find a fire (a candle, for example)) and maybe 1 ultrasonic sensor. I need more for my project. I need an IR Sensor, a fire flame sensor on every side, and 1 ultrasonic sensor in front. Additionally, I need to connect 2 DC motors, 1 fan, and 1 servo-motor for ultrasonic sensor. How can I solve this? I must buy Arduino Mega?


texts: How to make a pairing and mode button on a remote control receiver

texts:
I'm working on a remote control project and have come across many different RF receiver/transmitter modules. Many have a pairing/mode button on the receiver that serves to pair the receiver and transmitter and to choose which mode the transmitter is in, momentary, latching, toggle, etc.

How can I replicate this feature using Arduino and those cheap RF transmitter/receiver combos on Ebay? Specific code would be nice, but just a general idea as to how it would be done in theory will work too. I've watched several tutorials that explain the use of the Radiohead library with the cheap RF combos, but none demonstrate how to set up a feature such as this. Thanks.


texts:
I need to reproduce with a digital pin of an Arduino such a key in the form of a sequence of 1's and 0's, where a one takes 2 ms high and 2 ms low, and a zero takes 1 ms high and 1 ms low.

  int key = 0b101100001111;

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

void loop()
{
  for (int n = 0; n < 12; n++)
  {
    if (bitRead(key, n) == 1) //execute if bit value == 1
    {
      sendSignal(2000);
    }

    else //execute if bit value == 0
    {
      sendSignal(1000);
    }
  }
}

void sendSignal(int duration)
{
  digitalWrite(13, HIGH);
  delayMicroseconds(duration);
  digitalWrite(13, LOW);
  delayMicroseconds(duration);
}

This sketch really works! I figured out what my problem is: I actually need a longer key (64 bits). I am using long type: long key = 0b1000011110001101111100011111001010110001101101111011011100110100; but long only allows 32 bits. What do you recommend to do? Maybe you need to arrange it as an array? I think you can make it easier somehow. thank you


texts:
i clearly understand jp2 is the extra leftover pins of atmega16u2 . but how to access it ? i find my arduino has less pins and jp2 are the only ones left . but if it is not accessable , why do they have it ?
and also , if it requires seperate programing of the atmega16u2 , i'd like to know how . i completely dunno a thing about atmega16u2 . only thing i understand is that it makes the arduino more compatible with the usb input ...
thanks alot !


texts: Upload a .hex file, using a standalone ISP, without overwriting bootloader

texts:
Is it possible to flash a .hex file on an AVR MCU, which already contains the Arduino bootloader, using an AVRISP mkII, without overwriting the bootloader?

In my concrete situation, I have an Arduino Uno that I would like to program sometimes over an AVRISP mkII, and sometimes using the built-in programmer (i.e. by just connecting the Uno via USB to a computer).

For reference, given a compiled .hex file, this is what I use to upload it using the built-in programmer:

avrdude -c arduino -p atmega328p -P/dev/ttyACM0 -b115200 -D -Uflash:w:_build/image.hex:i

By default, this works as expected. I  can also use avrdude to upload it using the AVRISP:

avrdude -c avrisp2 -p atmega328p -U flash:w:_build/image.hex:i

This gets my image on the board as well; however, it also seems to overwrite the bootloader, i.e. after this, I can only use the AVRISP, and not the built-in one, to upload images. The only way back, at this point, is to re-flash the bootloader (via the AVRISP) on the Uno.

If I try to instruct avrdude to upload via the AVRISP without overwriting the bootloader:

avrdude -c avrisp2 -p atmega328p -D -U flash:w:_build/image.hex:i

then it fails in the verification phase:

avrdude: verification error; content mismatch

Based on @ChrisStratton's answer, I understand this means my problem actually starts before I even try to upload it, by the compiler emitting code which has addresses that should belong to the bootloader.

Here is the command I use to compile and link (I am not using the Arduino IDE at all)

avr-g++ -c -g -O3 -w -std=c++11 -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -I.. -mmcu=atmega328p -DF_CPU=16000000L blinkPB5.cpp -o _build/blinkPB5.cpp.o -MMD -MF _build/blinkPB5.cpp.m
avr-g++ -Os -Wl,--gc-sections -mmcu=atmega328p -o _build/image.elf _build/blinkPB5.cpp.o
avr-objdump -S _build/image.elf
avr-objcopy -Oihex -R.eeprom _build/image.elf _build/image.hex

As explained above, I can use the same resulting .hex file both via the bootloader (by just uploading it via serial) and the AVRISP (by overwriting the bootloader).


texts:
I've been doing fine with my LCD1602 I2C configuration but I discovered that command and data functions are the same even though I change the RS command/data bit, but the result is the same.

This is really strange, I really can't do anything about it??!

#define E   2   // E  bit
#define RW  1   // RW bit
#define RS  0   // RS bit

#define LCDadd_WR  0x4E
#define LCDadd_RD  0x4F

uint8_t bitmask = 0x08;
uint8_t i, arr[]={0x48,0x65,0x6c,0x6c,0x6f ,0x10 ,0x3a,0x29 ,0x10 ,0x48,0x6f,0x77,0x10
,0x61,0x72,0x65,0x10,0x79,0x6f,0x75,0x65,0x76,0x65,0x72,0x79,0x10,0x6f,0x6e,0x65};

// LCD prototypes
void LCD_Init(void);
void sendCMD(uint8_t CMD);
void sendData(uint8_t data);
void LCD_string(uint8_t arr1[]);
void move_cursor (uint8_t row, uint8_t col);

// I2C prototypes
void I2C_init(void);
void I2C_start(uint8_t address);
void I2C_stop(void);
void I2C_tx(uint8_t data);
void I2C_TWSR_Check(void);

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

void loop() {
//sendData(0x0E); /* I commented this line because it has the same effect as sendCMD(0x0F); in sendCMD function */
}

///////////////////////////////////////////////////
///////////////////////////////////////////////////
void LCD_Init(void)
{
  sendCMD(0x33);
  sendCMD(0x32);
  sendCMD(0x28);
  sendCMD(0x0F);
  sendCMD(0x01);
}

void sendCMD(uint8_t CMD)
{
  bitmask = 0x08;
  I2C_start(LCDadd_WR);
  I2C_tx(bitmask &= ~(1<<RS));
  Serial.println("CMD");
  Serial.println(bitmask, HEX);
  I2C_tx(bitmask &= ~(1<<RW));
  I2C_tx(bitmask = CMD & 0xF0 | 0x08);
  _delay_ms(5);
  I2C_tx(bitmask |= (1<<E));
  _delay_ms(1);
  I2C_tx(bitmask &= ~(1<<E));
  _delay_ms(1);
  I2C_tx(bitmask = (CMD<<4) & 0xF0 | 0x08);
  I2C_tx(bitmask |= (1<<E));
  _delay_ms(1);
  I2C_tx(bitmask &= ~(1<<E));
  I2C_stop();
}

void sendData(uint8_t data)
{
  bitmask = 0x08;
  I2C_start(LCDadd_WR);
  I2C_tx(bitmask |= (1<<RS));
  Serial.println("data");
  Serial.println(bitmask, HEX);
  I2C_tx(bitmask &= ~(1<<RW));
  I2C_tx(bitmask = data & 0xF0 | 0x08);
  _delay_ms(5);
  I2C_tx(bitmask |= (1<<E));
  _delay_ms(1);
  I2C_tx(bitmask &= ~(1<<E));
  _delay_ms(1);
  I2C_tx(bitmask = (data<<4) & 0xF0 | 0x08);
  I2C_tx(bitmask |= (1<<E));
  _delay_ms(1);
  I2C_tx(bitmask &= ~(1<<E));
  I2C_stop();
}

uint8_t BF(void)
{
  I2C_start(LCDadd_WR);
  I2C_tx(bitmask &= ~(1<<RS));
  I2C_tx(bitmask |= (1<<RW));
  I2C_stop();
  I2C_start(LCDadd_RD);
  I2C_rx();
  while (!(TWDR == (bitmask & (bitmask<<3))));
  I2C_stop();
  I2C_start(LCDadd_WR);
  I2C_tx(bitmask |= (1<<RS));
  _delay_ms(500);
  I2C_tx(bitmask &= ~(1<<RS));
  _delay_ms(500);
  I2C_stop();
}

void move_cursor (uint8_t row, uint8_t col)
{
  if (row==1)
  sendCMD(0x80+col);
  if (row==2)
  sendCMD(0xC0+col);
}

void LCD_string(uint8_t arr1[])
{
uint8_t cnt=0;
  for (i=0;i<29;i++)
  {
    sendData(arr1[i]);
    _delay_ms(500);
    cnt++;
    if (cnt==16)
    sendCMD(0xC0);
  }
  sendData(0x10);
}

///////////////////////////////////////////////////
///////////////////////////////////////////////////

void I2C_init(void)
{
  //set SCL to 100kHz
  TWSR = 0x00;
  TWBR = 0x48;
  //enable TWI
  TWCR = (1<<TWEN);
}

void I2C_start(uint8_t address)
{
  TWCR = (1<<TWINT)|(1<<TWSTA)|(1<<TWEN);
  while (!(TWCR & (1<<TWINT)));
  TWDR = address;
  TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
  while (!(TWCR & (1<<TWINT)));
}

void I2C_stop(void)
{
  TWCR = (1<<TWINT)|(1<<TWSTO)|(1<<TWEN);
}

void I2C_tx(uint8_t data)
{
  TWDR = data;
  TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
  while (!(TWCR & (1<<TWINT)));
}

uint8_t I2C_rx(void)
{
  TWCR = (1<<TWINT)|(1<<TWEN)|(1<<TWEA);
  while (!(TWCR & (1<<TWINT)));
  return TWDR;
}


texts: Listen for USB "TX signal received" response on RX

texts:
Is there a usb signal I can send on TX that will generate a response from the computer on the RX only if the computer is active/not a wall usb power supply? I'm trying to use the Remote library when a button is pressed and sometimes it won't work because the computer is off/asleep/etc and in those instances I would like the arduino to behave differently but because I have no way of knowing if the USB power is coming from the wall or passively from a computer that's off or actively from a computer that's on, I can't know what behavior to take.

To be clear about the application in mind: Right now I have a device that sends keyboard signals to my computer using a modified version of Stefan Jones' modified USBAPI.h and HID.cpp files. It works fine but if you restart the computer you have to manually unplug and replug in the arduino to get it to work again. This is necessary every restart, is rather annoying, and adds unnecessary wear to the connector. This is also necessary if the arduino is connected before the OS has loaded. Additionally there are some LEDs on the device (not talking about the diagnostic lights on the arduino itself) that stay lit up at night even when the computer is off. If I could detect when the computer is off/unconnected it would be trivial to fix this.


texts: Use the stepper motor library with the A4988 driver?

texts:
I want to use this library: https://www.arduino.cc/en/Reference/Stepper
#include <Stepper.h>

The wiring for my driver is shown here:

https://www.pololu.com/product/1182
From the library, I'm stuck at the motor pins:
#define motorSteps 200
#define motorPin1 2    // STEP pin
#define motorPin2 3    // DIR pin

Stepper myStepper(motorSteps, motorPin1, motorPin2);

Is this library not compatible with this stepper motor driver? Or what needs to be defined for it to work?
More details on the library are here: http://www.tigoe.com/pcomp/code/circuits/motors/stepper-motors
The basic section of my code that works without the library is this:
digitalWrite(stepPin, HIGH);
delay(wait);
digitalWrite(stepPin, LOW);
delay(wait);

Yet, the two-wire circuit part of the library uses motorPin1 and motorPin2 in a way I don't understand:
switch (thisStep) {
  case 0:  // 01
    digitalWrite(motor_pin_1, LOW);
    digitalWrite(motor_pin_2, HIGH);
  break;
  case 1:  // 11
    digitalWrite(motor_pin_1, HIGH);
    digitalWrite(motor_pin_2, HIGH);
  break;
  case 2:  // 10
    digitalWrite(motor_pin_1, HIGH);
    digitalWrite(motor_pin_2, LOW);
  break;
  case 3:  // 00
    digitalWrite(motor_pin_1, LOW);
    digitalWrite(motor_pin_2, LOW);
  break;
}

https://github.com/arduino-libraries/Stepper/blob/master/src/Stepper.cpp
How should motorPin1 and motorPin2 be defined?


texts: Arduino clone with ch340G and correct w7 x64 driver cannot connect to IDE

texts:
I have an Uno R3 with CH340G which works perfectly at my home w7 x64 notebook.
It worked properly right away with the CH341s64.sys driver. I tried revs from 2009, 2011 and 2014 and it is working with either one.
On my w7 x64 desktop though the drivers somehow do not communicate properly.
If I plug in the device, windows recognized it and a new port (port 8 in my case) shows up in device manager.

When I try to transfer a sketch to the device it fails with error message
avrdude: stk500_recv(): programmer is not responding.
I have tried CH341s64.sys rev 3.3.2011.11  and 3.4.2014.8 without success.
I have no clue how I can troubleshoot this as windows shows the port properly and there are no signs of error on the driver. There are no entries in the event logs.
Is there possibly a log file from the IDE which could shine a light?
I already tried with firewall disabled but no change.
My IDE is the latest 1.6.6 on both systems.


texts: Using the Logging library, sometimes doesn't exit setup()

texts:
This has been a hard problem to diagnose, so I hope I'm giving enough info here.  I'm trying to write a program for the Arduino (a lighting controller) using a bit of OO.  There are several classes in my library, and some extend others.  I'm a long-time programmer (mostly Java) but this is my first big Arduino project.

I'm using the Logging library at various points in the main program, as well as the objects, and that's where it get complicated.  Depending on where I put calls to the logging library, or even Serial.print(), it either all works, or what gets sent to the serial port is a bit garbled, and the board never enters loop() (I'm not sure if that means that it's crashing in setup() or not).  This library hasn't been touched in 4 years and there are pending merge requests, so I don't think I'll get answers from the developer.

I have a sneaking suspicion that the root of the problem is that Logging.h ends with instantiating the logger ("Logging Log = Logging();") so multiple instances of the logger may be created and the serial port is being reset several times, possibly at different port speeds.  I thought it was bad form to initialize object, or even have any running code, in a .h file.  Is this a possibility, and do I have any options to fix this?

Are there any good alternatives for printing outputs at different debug levels?

I would hate to have to pass the logger instance in as a parameter to my classes, or have to write setLogger() methods for all my classes.

Thanks.


texts: KY-022 IR receiver, LED always on, no output

texts:
I've been trying to use a KY-022 to read IR signals. However no output is being produced and the LED on the board is constantly on.

Board: Arduino Uno R3

I followed the procedure found here.

The code:

#include <IRremote.h>

int RECV_PIN = 11;

IRrecv irrecv(RECV_PIN);

decode_results results;

void setup() {
  Serial.begin(9600);
  // In case the interrupt driver crashes on setup, give a clue
  // to the user what's going on.
  Serial.println("Enabling IRin");
  irrecv.enableIRIn(); // Start the receiver
  Serial.println("Enabled IRin");
}

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

The output:

Enabling IRin
Enabled IRin

The LED is constantly on, it should come on when there's a signal received. However this is not shown in the output. :/ I don't know what to do.

Pictures:


texts: How to connect two LED strips (APA102/SK9822) to Arduino UNO?

texts:
So what I am trying to do is to connect two SK9822 LED strips to Arduino UNO.

I am a bit confused about how to properly set this up so I can individualy control any led. So obviously 5V should go to 5V and GND to GND, but what about the CLOCK and the DATA pin.

According to the tutorials and stuff I found here, CLOCK pin needs to be connected to pin 13 and DATA to pin 10, but they only use one strip... so what I am trying to ask is can LED strips share pins? Can they be connected to the same CLOCK pin and different DATA pins or how can i set this up to use the minimum amount of pins?

I was planning on using FastLED library, where it looks like you can specify which pin is DATA and which is CLOCK,

FastLED.addLeds<APA102, DATA_PIN, CLOCK_PIN>(leds, NUM_LEDS);

Is this because different boards have different CLK and MOSI pins or can i use any pin and set it as CLOCK or DATA? This is probably obvious but I am new to this and this is my first project.


texts: Strange discrete errors when reading HC-SR04 sonar sensor

texts:
I'm experimenting with an HC-SR04 sonar sensor. Basically I'm measuring the distance to a cardboard box twice a second with these lines of code running on an ESP32:

unsigned long sonarMeasure() {
    digitalWrite(TRIGGER, HIGH);
    delayMicroseconds(10);
    digitalWrite(TRIGGER, LOW);
    return pulseIn(ECHO, HIGH);
}

double distance = duration * 0.03455;

The results are a bit strange. I know, that I can't expect millimeter accuracy. But why are there rather discrete jumps of about 4 mm? And when looking closer, there is another frequent jump of <1mm:

(As far as I can tell, the jumps increase at larger distances.)

Is this an issue of how I read the sensor on the ESP32, or is it something happening internally on the HC-SR04?

I'd love to understand the reason for this effect to be able to improve the accuracy of my measurements.


texts: Low byte fuse programming of atmega328 of arduino uno

texts: I want to use the atmega328 of my arduino uno board to clock TDC 1000, using the clkout bit of atmega328, but this requires fuse programming of the low byte, Can any one tell me how to do it ??


texts: How can i do something like multi threathing in arduino?

texts:
I am checking for ways to implement multi threathing in Arduino, I have also tried using the library TimerOne but it doesn't seem to work, what I'm trying to make is an Arduino application then, every time a certain amount of time passes, it pops an item from the stack, and between these times, the application allows me to add items to the stack, both processes working in parallel of course.

The items popped and pushed are numbers.

I have already tried some other questions, but their solutions don't work, especially one that seems very useful, but for some reason doesn't work, I'm speaking about the one of the TimerOne library.

Any suggestion to fix the problem some other way would be cool.

Here is the code:

#include <TimerOne.h>
#include <QueueList.h>
#include <StackList.h>

const uint16_t  NOTE_B0     =   31;
const uint16_t  NOTE_C1     =   33;
const uint16_t  NOTE_CS1    =   35;
const uint16_t  NOTE_D1     =   37;
const uint16_t  NOTE_DS1    =   39;
const uint16_t  NOTE_E1     =   41;
const uint16_t  NOTE_F1     =   44;
const uint16_t  NOTE_FS1    =   46;
const uint16_t  NOTE_G1     =   49;
. . . ETC . . .
const uint16_t  NOTE_DS8    = 4978;

uint16_t Notas[] =
{
      NOTE_B0
    , NOTE_C1
    . . . ETC . . .
    , NOTE_C8
    , NOTE_CS8
    , NOTE_D8
    , NOTE_DS8
};

QueueList<int> KeyNotesNode = QueueList<int>();
StackList<int> StackNote = StackList<int>();

char receivedChar1 = '<';
char receivedChar2 = '<';

char receivedChar[] = {receivedChar1, receivedChar2};

int TempInt = 0;
bool newData = false;

bool itPopUp = false;

int modality = 0;

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

  if(modality == 0){
    Serial.println("Ingrese el tipo de funcionalidad deseada");
    Serial.println("1.- Constructor de canciones en tonos");
    Serial.println("2.- Juego de imposicion musical");
  }

  Timer1.initialize(150000);
  Timer1.attachInterrupt( setForPop );
}

void loop() {
  //Checa y controla la recepcion de los char a traves de la consola de arduino

  if (Serial.available())
  {
    receiveChar();
    showReceivedChar();
  }

//   . . .  Here is some code to process the reception of data from serialData  . . .

// From somewhere here start the loop

// . . . LOOPED . . .

    //Here is used the data
    if(modality == 1){
       //This option doesn't matter
    }
    else if(modality == 2){
      StackNote.push( (((int)(receivedChar[0]-'0'))*10)+((int)receivedChar[1]-'0') );
      Serial.println("Agregado receivedChar exitosamente a la Pila");
      Serial.print("Tamano Total Lista: ");
      Serial.println(StackNote.count());
      Serial.print("Dato:");
      Serial.println( (((int)(receivedChar[0]-'0'))*10)+((int)receivedChar[1]-'0') );
      Serial.print("Dato(get):");
      receivedChar[0] = '<';
      receivedChar[1] = '<';
    }
}

    //Run and show the data on the stack
     if(modality == 1)
     {
           //This option doesn't matter
      }
      else if(modality == 2)
      {

        if(itPopUp){   //With this variable i want to control when it is show, this code is inside loop()
          Serial.print("Reproducido con exito la nota: "); //se escribe 'éxito' pero la consola no acepta tildes, que se arrepienta :P
          TempInt = StackNote.pop();
          Serial.println(TempInt);
          tone(9,Notas[((int)TempInt)],500);
          delay(500);
        }
      }

  } //Here the loop() end

//This function i want to run it asyncronously
 void setForPop(){
    if(itPopUp){
      itPopUp = !itPopUp;
    }
    else{
      itPopUp = !itPopUp;
    }
 }


texts: ESP8266 WiFiClient connection always returns 0

texts:
I am trying to use a NodeMCU as a station to connect to a webserver, however, the WiFiClient connect function always returns 0 for no reason. I am able to connect the NodeMCU to my home WiFi, but it just cannot connect to any server (either with IP address or with URL).

If anyone is interested, the following is the testing code (I did not include the libraries intentionally for the clearness of the code).

int status = WL_IDLE_STATUS;
IPAddress server(74,125,115,105);  // Google

// Initialize the client library
WiFiClient client;

void setup() {
  Serial.begin(9600);
  WiFi.mode(WIFI_STA);
  Serial.println("Connecting to AP specified during programming");
  WiFi.begin("mySSID", "myPassword");
  while (WiFi.status() != WL_CONNECTED) {delay(500); Serial.print("."); }
  Serial.print("\r\nWiFi connected IP address: ");
  Serial.println(WiFi.localIP());
  Serial.println();
}

void loop() {
  Serial.println(client.connect(server,80));
}


texts: Store data in flash/EEPROM and process it in parallel

texts:
I want to store incoming data in flash or EEPROM and then apply FFT or some other method to detect frequency and intensity.

I am taking sound through microphone amplifying it with an LM741 and giving this amplified signal as input to an Arduino and then processing it at the same time.

But the problem is that the time taken in running the code is interfering with the sampling rate. I want to store say 50 inputs in flash and then process these 50 numbers, while at the same time the next set of 50 numbers is being stored, so that I can have data stored at a constant sampling rate.

Also how can I store data continuously? Because if I do this in loop() won't it again have time lag due to rest of the code?

I am new to Arduino, so please give details or some link to help me understand.

Thanks.


texts: Unintended reaction: Sketch makes LEDs turn on and of randomly/LEDs don't react

texts:
Update: This piece of code does not do the same as the one in the right answer, it also reacts when one lets go of the button.

int button_prev = 0;
int button = 0;

void loop(){

    button_prev = button;

    button = digitalRead(12);

    if (button_prev != button) {

      digitalWrite(act_pin[j], HIGH);

      j = (j+1) % 5;

    }
}

I printed out j and it seems like, instead of counting up +1 everytime the button is pressed once, it turns +1 and then +1 again which makes two LEDs at a time turn on.
But I don't see where the behavior of j comes from...

[Update: There was a mistake in the code which caused the random behavior, but now, nothing happens when I push the button.]

[I wrote a sketch which is supposed to make the Arduino turn one of five LEDs on one after another every time I press the switch.

But instead of turning one LED on after another, directly after upload it just makes them turn on and of at random. I don't push the button.
Serial.println as well just spits out one character, similiar looking to a d.]

Can anyone point out my mistake to me?

This is the circuit

and this is the old code of the sketch

int act_pin[6] = {A0, A1, A2, A3, A4};

int j = 0;

void setup(){

  Serial.begin(9600);

  for (int k = 0; k < 5; k++) {

     pinMode(act_pin[k], OUTPUT); //sets analog pins A0 - A4 as output

     digitalWrite(act_pin[k], LOW); //turns LEDs connected to A0 - A4 off

     pinMode(12, INPUT); //sets pin connected to button as input

}

}

void loop(){

  char button = {digitalRead(12)}; //stores if the button was pressed

  Serial.println(button);

  if(button == HIGH){

    digitalWrite(act_pin[j], HIGH); //turns LEDs on A0 - A4 on one after one with every button press

    j = (j+1) % 5; //makes digitalWrite jump to the next LED next time the button is pressed and limits it to 4

    button = LOW; //turns the button's pin low again, so nothing will happen until the button is pressed again
}

}


texts: How to print a line with a variable in it?

texts:
I want to know if there is a way to write like in C programming:

  printf("the num is %d",num);

I know that to print a line or a variable the command will be Serial.println
when I write:

 Serial.println("the num is %d",num);

It's not working.

Is there a way to write it in just one line?


texts:
I've designed this system which is supposed to turn on the LEDs when the temperature of a particular probe exceeds 32 degrees. From what I can tell, this should be functional but the analog sensor is always reading 0 when calling analogRead() on the pin.

Here is an image of my circuit:

and my code:

int length = 5;
float airTemp = 32;

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

void loop()
{
  // loads current temperature into array
  int reading;
  float voltage;
  float temp[length];
  for (int i = 0; i < length; i++)
  {
    reading = analogRead(i);
    Serial.print(reading);
    voltage = reading * 5.0;
    voltage /= 1024;
    temp[i] = (voltage - 0.5) * 100;
  }

  // turns on/off fans based on current temperature
  for (int i = 0; i < length; i++)
  {
    pinMode(i, OUTPUT);
    if (temp[i] > airTemp)
    {
      digitalWrite(i + 8, HIGH);
    }
    else if(temp[i] <= airTemp)
    {
      digitalWrite(i + 8, LOW);
    }
  }
  delay(1000);
}

I learned how to read the temperature from here. It's probably a dumb mistake, but I just started working with Arduino yesterday and I couldn't find information anywhere so thanks in advance.


texts: How to organize my Arduino projects' structure for easy source control?

texts:
It's been a long time I've been looking for a good answer to this question.

Typically, any Arduino project but the simplest one will include:

The main source code file MyProject.ino
Libraries specific to the project (MyProjectLibrary1.h, MyProjectLibrary1.cpp...)
Third-party libraries (generally free open source, added manually to Arduino libraries directory)
Schematics, PCB diagrams
Documentation
...

All this makes it hard to keep the whole code and doc of one project under Source Code Management (e.g. on Subversion, Git or GitHub).

Managing source control of your project means managing the version of all files used by the project including 3rd-party libraries.

Now for a single project, I need to define a directory structure that:

Includes all project files as described above
I can entirely commit to a Source Code Management tool (including 3rd-party dependencies)
I can checkout anywhere on my hard drive and build the project from there (does it have to be a single location as imposed by Arduino IDE)
I can zip into a self-contained archive that I can send to a friend for him to build as easily as possible (no extra manual download)

What I find particularly tricky with Arduino projects is the management of external libraries dependencies. Java projects developers have maven repositories for that and that helps a lot in managing all external deps. But we don't have an equivalent system for Arduino libraries.

I would be interested to know how other Arduino project makers deal with these aspects in their own projects.

Also note that I am open to changing my development process, including my IDE (currently I use Eclipse with the Arduino plugin most of the time, and then I ensure my projects can also work directly with the Arduino IDE).


texts: Arduino IDE doesn't pick up serial ports

texts:
I am fairly new to Arduinos and I recently bought a nodeMCU Amica esp2866 for this tutorial. I have my board connected to my MacBook Air (10.14.5 with Mojave) and only the "/dev/cu.Bluetooth-Incoming-Port" is the only one that shows up.

I am using a basic USB cord to connect the board to my MacBook and I know the cable isn't broken because I have used it in the recent past. If anyone knows how to fix this problem or has run into this problem in the past, please let me know. Let me know if you'd like anymore information. Thank you!


texts: Two flow sensors, one ESP32, LCD and/or Arduino

texts:
I want to build a flow meter but the Gal/Min rating of something like this flow meter is too low. I am thinking of strapping two side by side with suitable plenums for In and Out.

I have found some sketches like this but wondering how to use the two inputs to aggregate the results to GPM and Gallons total for display on an LCD screen. I am unsure what happens if two Hall-results arrive at or about the same time but on different Data Pins.

I have priced some single sensors with a higher flow rate for the pipe size but they run to several hundred dollars. Gallons are not critical as long as I can be within about 5% error over ten minutes, our average tank fill time.

Can someone please point me at some code to get me started for an ESP32 and LCD. I'd even consider adding a Nano if that makes things easier. I imagine that would certainly prevent collision issues. Basically I need to be able to handle the flow rate to a single LCD.

Thanks


texts: Converting Arduino LCD Programs to Serial I2C LCD code

texts: I just got a Serial LCD and wanted to test it out with a game. I found this site with game conversions and wanted to use this game.  However since my serial LCD use the LiquidCrystalic2 library the code in its current state won't work. Is there a simple method of converting or porting liquidcrystal to LiquidCrystalic2? Or if someone knows of a simple game in regards to hardware that uses a serial lcd and could direct me to a link that would be great.


texts:
I am trying to publish JSON data to mqtt with following code snippet

#include <Arduino_JSON.h>
JSONVar data;
data["temperature"] = temperature;
data["humidity"] = humidity;
data["pressure"] = pressure;
data["chipId"] = chipId;

String jsonString = JSON.stringify(data);
client.publish("esp32/data", jsonString);

But getting following error

/home/ubuntu/Arduino/libraries/PubSubClient/src/PubSubClient.h:144:12: note:   candidate expects 4 arguments, 2 provided
Multiple libraries were found for "PubSubClient.h"
 Used: /home/ubuntu/Arduino/libraries/PubSubClient
Multiple libraries were found for "Wire.h"
 Used: /home/ubuntu/.arduino15/packages/esp32/hardware/esp32/1.0.4/libraries/Wire
Multiple libraries were found for "Adafruit_BME280.h"
 Used: /home/ubuntu/Arduino/libraries/Adafruit_BME280_Library
Multiple libraries were found for "Adafruit_Sensor.h"
 Used: /home/ubuntu/Arduino/libraries/Adafruit_Unified_Sensor
Multiple libraries were found for "SPI.h"
 Used: /home/ubuntu/.arduino15/packages/esp32/hardware/esp32/1.0.4/libraries/SPI
Multiple libraries were found for "Arduino_JSON.h"
 Used: /home/ubuntu/Arduino/libraries/Arduino_JSON
Multiple libraries were found for "WiFi.h"
 Used: /home/ubuntu/.arduino15/packages/esp32/hardware/esp32/1.0.4/libraries/WiFi
 Not used: /opt/arduino-1.8.10/libraries/WiFi
exit status 1
no matching function for call to 'PubSubClient::publish(const char [11], String&)'

Whats is wrong here ?


texts:
The central arduino

The 1st node

The 2nd node

I want the central to send to the first node the rgb code like a string on the loop

  "rgb: 255000255"

but when it detects something to PIR to send a string to central.
In addition every some seconds the 2nd node to send a string to the central the temperature.

As i mentioned in my previous questions i have some problems when it comes to the bi-directional comunication. I have tried a lot of code. Can someone show me how to achieve what i want to do if not with code, with steps. Please help me!!


texts: Issues uploading to atmega324pb w/ adruino as ISP

texts:
I've been having some issues programming a new atmega324pb I have on a custom board. I set up an old adruino UNO as an ISP by uploading the ArduinoISP sketch, setting the programmer to "Arduino as ISP" and then using the "Upload using programmer" option but to no avail. Here is the verbose error message that the console logs:

System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"

     Using Port                    : COM5
     Using Programmer              : stk500v1
     Overriding Baud Rate          : 19200
     AVR Part                      : ATmega32U4
     Chip Erase delay              : 9000 us
     PAGEL                         : PD7
     BS2                           : PA0
     RESET disposition             : dedicated
     RETRY pulse                   : SCK
     serial program mode           : yes
     parallel program mode         : yes
     Timeout                       : 200
     StabDelay                     : 100
     CmdexeDelay                   : 25
     SyncLoops                     : 32
     ByteDelay                     : 0
     PollIndex                     : 3
     PollValue                     : 0x53
     Memory Detail                 :

                              Block Poll               Page                       Polled
       Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
       ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
       eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
       flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
       lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
       signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

     Programmer Type : STK500
     Description     : Atmel STK500 Version 1.x firmware
     Hardware Version: 2
     Firmware Version: 1.18
     Topcard         : Unknown
     Vtarget         : 0.0 V
     Varef           : 0.0 V
     Oscillator      : Off
     SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.03s

avrdude: Device signature = 0x000000 (retrying)

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000 (retrying)

I think it might be an issue with Arduino possibly targeting a chip other than atmega324pb that I'm using, but I'm not sure. I don't know of any official arduino boards that utilize the 324pb. The main issue that I see is that avrdude can't find the device signature. I've see others mention it might be faulty wiring, but I made sure all connections are intact.


texts: collecting & visualizing sensor data - best approach?

texts:
I'm working on a kite-related project where I'm using Arduino + accelerometer to track data while a kite is in the air. I am struggling a little with the best approach - help on the following questions / issues would be a huge help:

-- how best to grab data only while the kite is in the air? just detect with numbers, use a switch? other ideas?
-- how best to collect the data and transfer to computer for visualization (likely with processing but looking at other options). i'm using this project in workshops with kids in low-income neighborhoods in brazil, so will have limited resources. a laptop will be available -but use of mobile also ideal.

Thank you!
Claudia


texts: Arduino Mega - Enabling CTC mode disables timer

texts:
I'm trying to use timer3 on an Arduino Mega 2560 in CTC mode. However, enabling CTC disables the code entirely.

Here is the function I call in setup() to setup the times.

void SetupInterrerupt() {
  cli(); // Disable interrupts

  // Setup timer
  TCCR3A = 0;     // set entire TCCR3A register to 0
  TCCR3B = 0;     // same for TCCR3B

  // Setup compare match register
  OCR3B =  CMP_FAST; // CMP_FAST = 40

  // turn on CTC mode:
  TCCR3B |= (1 << WGM32); // Commenting out this line makes the code work
  // Set CS10 and CS12 bits for 1024 prescaler:
  TCCR3B |= (1 << CS30) | (1 << CS32);
  // enable timer compare interrupt:
  TIMSK3 |= (1 << OCIE3B);

  sei(); // Enable interrupts

  Serial.println("Timers enabled");
}

And the interrupt vector.

// Timer 3 Interrupt
ISR(TIMER3_COMPB_vect){//timer1 interrupt 1Hz toggles pin 13 (LED)
  // do stuff...
}

As is, the interrupt doesn't execute at all. As noted in the code, commenting out "TCCR3B |= (1 << WGM32);" actually executes the interrupt, except the frequency is more like 1Hz instead of 720.

I'm using the arduino-lmic library, as well as some other data structure libraries. I don't think they use any timers, but since lmic is designed for Uno's, I figured that using timers 3 and up would be fine.

I'm a little rusty on my timers unfortunately. Is anyone able to spot my mistake?

Thanks.


texts: Motor Shield with 4 DC motors + small servo, which battery is suitable?

texts:
I am building my first 4wd vehicle with Adafruit motor shield with one Ultrasonic sensor and one small servo to move sensor.

I am facing some problems.

Bought 4 motors (2 GM9 and 2 GM3), found the difference when start running and GM9 were running double the speed of GM3. Tried to slow down th eGM9 with speed in code but now one of the motor stop many times while other run.
Running spearate power for Arduino (now USB) and 9v batteries for motorshield. Should I remove the jumper on motor shield as found that after removing 9v battery, its getting some volts from Arduino and motors running very slowly.
Servo motor is not running at all. While its pins are according to the circuit.
Should 9v batteries will be OK to run 4 GM9/GM3 motors + 1 small Servo? if not please recommend any other.
When running I feel small smell from boards, nothing is hot, is it a problem?

Too many questions but tried to put in one place.

Thanks


texts: I’m very new to Arduino and have been doing a lot of research on how to connect my Arduino Uno to my Xbox One as a wired controller, unfortunately I haven’t been able to find much help.  I found UnoJoy but it seems to only work with PlayStation.  I know that it is possible because the Uno has HID.  I’m sorry if this has been answered before, but how do I code the Uno so the Xbox will recognize it so I can assign (push buttons, toggle switches, rotary encoders) to certain functions in game?


texts: Arduino Mega and other modules power consumption

texts:
I have an Arduino Mega 2560 to which I have connected:

Arduino GSM Shield 2
Waveshare 10 DOF IMU sensor
Waveshare NEO-7M-C (B) GPS module
HC-05 ZS040 Bluetooth module

I am feeding my Arduino a 12V current via the VIN pin, yet both the GSM shield and the GPS module are misbehaving due to low power working conditions. All the modules work perfectly fine individually, or in any combination that does not have both the GSM and the GPS module, as they consume the most power.

My question is how high a voltage would be necessary in order for all of the modules to function correctly and how this voltage should be connected to the Arduino.


texts: stop running a certain function when sensor picks up something and return to where it stops?

texts:
i have a question on how to program a certain sequence for my robot.

lets say if i would to program to make it run from position a to b, i have a sensor attach to it that should it detect x, it would perform an action called y at the position where it detect x, where action y doesnt change its position.

i would like the robot to continue from where it left after performing action y to go towards b. however i do not know how to pause sequence from a to b and continue from where it left off after performing action y. i am controlling only the motor of the wheels so i can only set the speed of the wheels.

is there a pause function in general( not sleep) in c++ and to continue running its lines of code from where it paused?


texts: Atmega2560V, trying to burn bootloaders of MegaCore

texts:
I am trying to burn MegaCore bootloaders to it, I have setup my custom PCB  with Atmega2560V-8AU and 8Mhz Crystal + Load Caps all assembled on using PCBA process.
I am trying to burn MegaCore bootlaoders to it, I am using Arduino UNO as ISP Programmer. My connections are all correct, It shows different Device Signatures (see below) whenever I hit Burn Bootloaders....

  0x0000ff
  0x00003f
  0x0000ff
  0x00ff00
  0x001000
  0xff0000
  0xfc0000
  0x00fe00

This is complete output with different Device Signatures

  Arduino: 1.8.3 (Windows 10), Board: "ATmega2560, Arduino MEGA pinout,
  2.7v, Disabled (default), 8 MHz external"

  C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude
  -CC:\Users\mudas\OneDrive\Documents\Arduino\hardware\MegaCore-avr-100-pin\avr/avrdude.conf
  -v -patmega2560 -cstk500v1 -PCOM4 -b19200 -e -Ulock:w:0x3f:m -Uefuse:w:0xfd:m -Uhfuse:w:0xd6:m -Ulfuse:w:0xf7:m

  avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
           Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
           Copyright (c) 2007-2014 Joerg Wunsch

     System wide configuration file is "C:\Users\mudas\OneDrive\Documents\Arduino\hardware\MegaCore-avr-100-pin\avr/avrdude.conf"

     Using Port                    : COM4
     Using Programmer              : stk500v1
     Overriding Baud Rate          : 19200
     AVR Part                      : ATmega2560
     Chip Erase delay              : 9000 us
     PAGEL                         : PD7
     BS2                           : PA0
     RESET disposition             : dedicated
     RETRY pulse                   : SCK
     serial program mode           : yes
     parallel program mode         : yes
     Timeout                       : 200
     StabDelay                     : 100
     CmdexeDelay                   : 25
     SyncLoops                     : 32
     ByteDelay                     : 0
     PollIndex                     : 3
     PollValue                     : 0x53
     Memory Detail                 :

                              Block Poll               Page                       Polled
       Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
       ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
       eeprom        65    10     8    0 no       4096    8      0  9000  9000 0x00 0x00
       flash         65    10   256    0 yes    262144  256   1024  4500  4500 0x00 0x00
       lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
       signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

     Programmer Type : STK500
     Description     : Atmel STK500 Version 1.x firmware
     Hardware Version: 2
     Firmware Version: 1.18
     Topcard         : Unknown
     Vtarget         : 0.0 V
     Varef           : 0.0 V
     Oscillator      : Off
     SCK period      : 0.1 us

  avrdude: AVR device initialized and ready to accept instructions

  Error while burning bootloader. Reading |

  ############################################ | 100% 0.02s

  avrdude: Device signature = 0x00fe00 avrdude: Expected signature for
  ATmega2560 is 1E 98 01
           Double check chip, or use -F to override this check.

  avrdude done.  Thank you.

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.
What should be the problem.??? How to solve this.?


texts: Arduino Resetting in Automotive Application

texts:
I have a complicated problem with my Arduino circuit being reset/crashing, I will try to describe the best I can.

The Setup:
Basically I have a Arduino 328P circuit that is monitoring some temperatures in an automotive environment.  Several one wire temperature sensors connect to the PCB with various distances from 2-10 ft. Each is on a seperate pin.  I have also tried analog LM35 sensors.  The system works outside the car just fine.

The Problem:
When the car is shut off (not the PCB) the Arduino is being reset despite power still being connected.  There is no power spike or loss to the PCB. The car is not actually running, I am just turning the key on and off.

What I have learned:
-When I disconnect the temperature sensors from the PCB, problem goes away.
-It makes no difference if the wires to the sensors are shielded.
-It makes no difference if I use one wire digital or analog sensors.
-It makes no difference if I connect the PCB directly to the battery
-The problem goes away if I run the PCB on a battery not connected to the car. (fully isolated)
-The problem comes back if I ground the PCB to the chassis, but still leave the +12V isolated.
-The chance of a reset changes when the sensors are moved or the length of wire is changed.
-It only resets when the key is turned off, never when turned on.

I tried to explain the best I can without writing a novel.  I think I might need to isolate the ground to my PCB somehow.  The problem is in the ground or the long wires to the sensors.


texts: Arduino running at 8MHz with external crystal

texts: I want to use my Atmega328P in 8MHz, but I noticed that the internal clock is not as accurate and cause problems in my application. To add an external crystal 8MHz I do like the image below or 22pF capacitors are only necessary when I use a 16MHz crystal?


texts: Using LDR and RGB Led to get R,G,B values

texts:
Has anyone tried using a setup of RGB LED directed to cuvette and the LDR on the opposite side? using arduino to and get the RGB values..

Currently having problems with calibration... I was able to get R,G,B values of colored papers... however with colored liquids inside a cuvette I'm not getting any good results (i.e the Red/Blue/Green values goes way up like 5000++)

Used white and black paper for callibration..

No idea for liquid...


texts: Arduino Text Scrolling on 16x02 I2c on NodeMcu (ESP8266-12)

texts:
I have managed to get my 1602 I2C LCD working on a NodeMCU devkit. I can display text parsed from the web but I am not sure how to set it to autroscroll if message is greater than 16 characters. I tried the lcd.ScrollDisplayLeft() but it doesn't work. I figured I would have to do it manually and it is a matter of getting string length and then looping the characters.

This is what I have so far:

#include <ESP8266WiFi.h>
#include <Wire.h>  // This library is already built in to the Arduino IDE
#include <LiquidCrystal_I2C.h> //This library you can add via Include Library > Manage Library >

LiquidCrystal_I2C lcd(0x3F, 16, 2);

const char* ssid = "ssid";
const char* password = "pass";
const char* host = "api.thingspeak.com";

int find_text(String needle, String haystack, int from) {
  int foundpos = -1;
  if (haystack.length() < needle.length())
    return foundpos;
  for (int i = from; (i < haystack.length() - needle.length()); i++) {
    if (haystack.substring(i, needle.length() + i) == needle) {
      foundpos = i;
      return foundpos;
    }
  }
  return foundpos;
}

void setup() {
  Serial.begin(115200);
  delay(100);
  lcd.init();   // initializing the LCD
  lcd.backlight(); // Enable or Turn On the backlight
  delay(200);

  // We start by connecting to a WiFi network
  Serial.println();
  Serial.println();
  Serial.println(ssid);

  WiFi.begin(ssid, password);
  lcd.setCursor(0, 0);
  Serial.print("Connecting to ");
  lcd.print("Connecting");
  lcd.setCursor(1, 1);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
    lcd.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Connected!!");
  delay(1000);
}
int value = 0;

void loop() {

  Serial.print("connecting to ");
  Serial.println(host);

  // Use WiFiClient class to create TCP connections
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");

  }

  // We now create a URI for the request
  String url = "/apps/thinghttp/send_request?api_key=345345345345345";
  Serial.print("Requesting URL: ");
  Serial.println(url);
  // This will send the request to the server
  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "Connection: close\r\n\r\n");
  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Fetching Data..");
  delay(10000);

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

    int start_loc = find_text("<b>", line, 0);
    int end_loc = find_text("</b>", line, 0);
    if (start_loc > 0 && end_loc > 0)
    {
      lcd.clear();
      Serial.println("data:  ");
      lcd.print("data: ");
      lcd.setCursor(1, 1);
      for (int i = start_loc + 3; i < end_loc; i++)
      {
        Serial.print(line[i]);
        lcd.print(line[i]);
     }

  Serial.println();
  Serial.println("closing connection");
  delay(2000);

}
  }
}


texts: How to serial read from a TM-88 printer for status

texts:
I am working off of my own fork of the TM-88 printer library by signalwerk It can be found here ( https://github.com/docwisdom/thermalprinter )

With this I am trying to get a printer status before I attempt to print to it. I added the check status function within the library and am hoping to read back the binary or hex value returned. I am expecting 03 or 00000011 in the printers current state. What I am getting back is 255 or -1. I am not sure if I am running into an issue with how I am handling the return data or what. Any thoughts?

TM88.getStatus();
Serial.println(TM88.read());

Here is the library code if it helps to troubleshoot

thermalprinter.cpp:

void Epson::getStatus(){
  this->write(0x1D);
  this->write(0x72);
  this->write(1);
}

byte Epson::read(){
    byte result;
    result = this->_printer->read();
    return result;
}

Thermalprinter.h:

byte read();
void getStatus();

I have tried using int char and byte variables for the read return


texts:
so I am communicating with a 4d systems screen and when an event is triggered on the screen i go into my handler
I am having an issue with the following line:
int caughtScreen = int(Event.reportObject.index);

not sure why but I am sure this is where things go off the rails.
the object Event.reportObject.index is of a type uint8_t
and comes from the GitHub repo at arduino 4d Repo
I've inserted other testing points in the code and I am sure this is where things go off
here is some of the wrapping code to give you an idea (and yes the keyboard event works fine):
void myDisplayEventHandler(void)
{
    int caughtScreen =6;
    genieFrame Event;
    myDisplay.DequeueEvent(&Event); // Remove the next queued event from the buffer, and process it below
    //If the cmd received is from a Reported Event (Events triggered from the Events tab of Workshop4 objects)

    if (Event.reportObject.cmd == GENIE_REPORT_EVENT)
    {

        if (Event.reportObject.object == GENIE_OBJ_KEYBOARD)                // If the Reported Message was from a Keyboard
        {
            if (Event.reportObject.index == 0)                              // If Keyboard (Index = 0)
            {

                CatchgKeyboard(myHMIValues.CurrentScreen, char(myDisplay.GetEventData(&Event)));                      // Receive the event data from the keyboard
            }
            if (Event.reportObject.index == 1)                              // If Keyboard (Index = 1)
            {
                PasswordCatcher.nextChar(char(myDisplay.GetEventData(&Event)));                      // Receive the event data from the keyboard
            }

        }
        else if (Event.reportObject.object == GENIE_OBJ_WINBUTTON)
        {
            serial.print("got here");
            caughtScreen = int(Event.reportObject.index);
            serial.print("never gets here");
            switch (caughtScreen)
            {
            case 3: // Logout
                foo();
                break;
            default: //Most Screens
                bar();
                break;
            }

        }

     }

    //Event.reportObject.cmd is used to determine the command of that event, such as an reported event
    //Event.reportObject.object is used to determine the object type, such as a Slider
    //Event.reportObject.index is used to determine the index of the object, such as Slider0
    //genie.GetEventData(&Event) us used to save the data from the Event, into a variable.
}


texts: Sending data to UART using Atmel Studio with Attiny84

texts: I want to send data to TFDI. It can be hello world or any value of variable. But I can't do. I haven't found example code on the internet. Some examples doesn't work. I am using Atmel Studio.


texts: NodeMCU is not working. Only a little orange LED is turning on

texts: Some time ago, i powered a NodeMCU with a 9 volt battery, it worked but the next time i tried to use the board, only a little orange led near the usb connector and reset button turned on. I can't interact with it so i think that i applied too much voltage. Please help me if you know what happened and if i can solve it.


texts:
I have a Parallax 27800 2-Axis Joystick wired up to a AVR 14 Pin 20MHz 8K 12A/D - ATtiny84. The joy stick sends out a x y analog signal. I have programmed the Attiny84 to read the signals and set one of the attiny84 pins (high or low) depending on the direction of the joystick. In this example, each pin is wired up to a LED. The problem I am having is there is about a 1 second delay for the LED to light. The Attiny84 has a built in 8MHz clock. Would connecting an external 20MHz crystal fix this issue?

int UD = 0;
int LR = 0;

int DWN = 0;
int UP = 1;
int LEFT = 4;
int RT = 5;

int LRMID = 0;
int UPMID = 0;
void setup(){

  pinMode(DWN, OUTPUT);
  pinMode(UP, OUTPUT);
  pinMode(LEFT, OUTPUT);
  pinMode(RT, OUTPUT);

  digitalWrite(DWN, LOW);
  digitalWrite(UP, LOW);
  digitalWrite(LEFT, LOW);
  digitalWrite(RT, LOW);

  //calabrate center
  LRMID = analogRead(3);
  UPMID = analogRead(2);
}

void loop(){

  UD = analogRead(2);
  LR = analogRead(3);
  // UP-DOWN
  if(UD < UPMID - 5){
   digitalWrite(DWN, HIGH);
  }else{
   digitalWrite(DWN, LOW);
  }

  if(UD > UPMID + 5){
   digitalWrite(UP, HIGH);
  }else{
   digitalWrite(UP, LOW);
  }
  // LEFT-RIGHT
  if(LR < LRMID-5){
   digitalWrite(LEFT, HIGH);
  }else{
   digitalWrite(LEFT, LOW);
  }

  if(LR > LRMID +5){
   digitalWrite(RT, HIGH);
  }else{
   digitalWrite(RT, LOW);
  }

  delay(100);

}


texts: How can I sense very high temperatures with Arduino?

texts: I've seen many temperature sensors, but the highest temperature they go up to is 125 degrees C (257 degrees F). I want to reach higher temperatures than that. I'm thinking about rigging up a closed loop sensor for my soldering iron (for a convenient LCD display), but I can't find out how to sense the temperature of the tip due to the higher operating temperature than most sensors.


texts:
I use simple LED blinking code on an Arduino MEGA 2560. I simulate it in Proteus. But pin number 9 doesn't power up. What is the problem?

My code:

// Set up the DATA direction
void setup()
{
  for(int i = 1; i<9; i++)
    pinMode (i, OUTPUT);
}

// The main program
void loop()
{
  for(int j=2; j<=10; j++)
  {
    digitalWrite(j, HIGH);
    delay(100);
    digitalWrite(j, LOW);
  }

  for(int j=9; j>=2; j--)
  {
    digitalWrite(j, HIGH);
    delay(100);
    digitalWrite(j, LOW);
  }
}

And the circuit is:


texts: How to program Arduino manually via STK500?

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

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


texts:
I am currently working an automatic home gardening system. There are two moisture sensors and two solenoid valves to allow water to plant two different zones. Preferably, I want to water the plants for x amount of time. I started programming this and I noticed that with my code below, if one solenoid valve goes off, the entire program will delay until one of the solenoid valves closes and thus the other solenoid valve will not open until the other one is closed.

However, I want to prevent this from happening and I want the program to continue reading the moisture readings while one of the solenoid valves is open so that the other solenoid valve can open whenever the zone needs water as well.

int solenoidPin1 = 1; //connected to Digital 1
int solenoidPin2 = 2; //connected to Digital 2
void setup(){
  pinMode(solenoidPin1, OUTPUT);
  pinMode(solenoidPin2, OUTPUT);
}
void loop(){
  int moisture1 = analogRead(moisturePin1);
  int moisture2 = analogRead(moisturePin2);
  if (moisture1 <= 250){ //if moisture is less than reading 250
  digitalWrite(solenoidPin1, HIGH); //switch solenoid ON
  delay(300000); //water for five minutes
  digitalWrite(solenoidPin1, LOW); //switch solenoid OFF
  }
  else {
  digitalWrite(solenoidPin1, LOW); //switch solenoid OFF
  }

  if (moisture2 <= 250){ //if moisture is less than reading 250
  digitalWrite(solenoidPin2, HIGH); //switch solenoid ON
  delay(300000); //water for five minutes
  digitalWrite(solenoidPin2, LOW); //switch solenoid OFF
  }
  else {
  digitalWrite(solenoidPin2, LOW); //switch solenoid OFF
  }
}

I was thinking that I should do the following for the conditioning part. Will this work instead for what I'm trying to do?

  if (moisture1 <= 250){ //if moisture is less than reading 250
  digitalWrite(solenoidPin1, HIGH); //switch solenoid ON
  }
  else if (moisture1 >= 550){
  digitalWrite(solenoidPin1, LOW); //switch solenoid OFF
  }

  if (moisture2 <= 250){ //if moisture is less than reading 250
  digitalWrite(solenoidPin2, HIGH); //switch solenoid ON
  }
  else if (moisture2 >= 550){
  digitalWrite(solenoidPin2, LOW); //switch solenoid OFF
  }

Note: I'm using a capacitive moisture sensor, so the output voltage/reading is higher the drier the dirt is.


texts:
I want to create a sketch that counts the days from the moment the "project" start and send and osc message every two days (or more) for 3 weeks. So:

day zero : osc message -> 0
day two. : osc message -> 1
day four : osc message -> 2

etc.
I'm trying to create a state machine to send the messages when the millis reaches a certain time it should print message and so on for the other times.
I'm giving a small example:
I went with @jsotola's suggestion and tried out the BlinkWithoutDelay approach. It seemingly works because I get serial prints around the correct millis() they are printed in 4fold or 3fold the messages.
EDITED CODE:
int daytwo = 25920; // for testing purposes other numbers then the actual millis()
int dayfour = 44400;

void loop() {
  unsigned long currentMillis = millis();   // store current time

  if (currentMillis == daytwo) {
    Serial.println("daytwo");
  }

  if (currentMillis == dayfour) {
    Serial.println("dayfour");
  }
}

Serial output:

    11:04:39.889 -> daytwo
    11:04:39.889 -> daytwo
    11:04:39.889 -> daytwo
    11:04:39.889 -> daytwo
    11:04:39.889 -> daytwo
    11:04:39.889 -> daytwo
    11:04:39.889 -> daytwo
    11:04:39.889 -> daytwo
    11:04:39.926 -> daytwo
    11:04:58.366 -> dayfour
    11:04:58.366 -> dayfour
    11:04:58.366 -> dayfour
    11:04:58.366 -> dayfour


texts: Is the ShiftOut tutorial on the official Arduino website really wrong regarding the capacitor?

texts:
I'm talking about this tutorial "Serial to Parallel Shifting-Out with a 74HC595" from the official Arduino website. It provides the following schematic:

I've read a couple of times now, that the placement of the capacitor is wrong:

  This is a well known shit tutorial which for some unknown reason they refuse to fix.
  That capacitor should be connected between the Vcc pin and ground, NOT the latch pin.

Source: forum.arduino cc/index.php?topic=408135.0

They recommend this placement:

Who's right? Please explain where to place the capacitor. Can the arduino even be damaged?


texts:
I would like to read an analog value using analogRead, save this value and compare it to an analogRead value 5 ms later. How would this code look? Because giving a variable the value of analogRead(A0); would mean it is constantly changing, making it impossible to compare two values.

thanks in advance


texts:
I succeeded in programming a system of thermoregulation using Arduino.  This system holds the temperature of a plate at 37°C. I used a PID corrector to realize this.

What I want to do now is make a graphic interface that can communicate with the Arduino, allowing me to see a graph of the temperature.

I would like an explanation of how to send temperature data to a graphic interface using Arduino Uno.


texts: Why is function mentioned in global declaration?

texts:
I came accross this code for writing data into EEPROM in arduino. Why is void printTemp();, void clearEEPROM(); and void writeTemp(); functions are mentioned in global declaration? How will this help?
#include <EEPROM.h>

#define SAMPLE_TIME 2000  //The time between each EEPROM write function call in ms

int tempPin = 0;      //the ADC pin
int printPin = 2;     //the print button pin
int erasePin = 4;    //the erase button pin

int address = 0;      //EEPROM address counter

unsigned long timer;

float conv_coeff = 0.0;   //coefficient for converting from 0-1024 to 0-5 range

void printTemp();
void clearEEPROM();
void writeTemp();

void setup(){
  Serial.begin(115200);     //start the serial connection as always
  conv_coeff = 5.0/1024.0;  //find the coefficient to do the conversion
  timer = millis();         //millis() returns the time since program start in ms
}

void loop(){
  if(millis()-timer > SAMPLE_TIME)  //check if it's time to do a temp sensor sample
  {
    writeTemp();
    timer = millis();
  }

  if(!digitalRead(printPin))  //check if print button is pressed
  {
    printTemp();
    delay(500);
  }

  if(!digitalRead(erasePin)) //check if erase button is pressed
  {
    clearEEPROM();
    delay(500);
  }

  delay(1);
}

void printTemp()
{
  for (int i = 0 ; i < EEPROM.length() ; i++) {
    byte value = EEPROM.read(i);                //read EEPROM data at address i
    if(value != 0)                              //skip "empty" addresses
    {
      float temp = value*conv_coeff;            //convert ADC values to temperature
      temp = (temp - 0.5)*100;                  //take care of the offset

      Serial.println(temp);
    }
  }
}

void clearEEPROM()
{
  for (int i = 0 ; i < EEPROM.length() ; i++) {
    if(EEPROM.read(i) != 0)                     //skip already "empty" addresses
    {
      EEPROM.write(i, 0);                       //write 0 to address i
    }
  }
  Serial.println("EEPROM erased");
  address = 0;                                  //reset address counter
}

void writeTemp()
{
  byte value = analogRead(tempPin);     //read sensor value

  EEPROM.write(address, value);         //write value to current address counter address

  Serial.print("Sensor value stored at address ");
  Serial.println(address);

  address++;                      //increment address counter
  if(address == EEPROM.length())  //check if address counter has reached the end of EEPROM
  {
    address = 0;              //if yes: reset address counter
  }
}


texts:
Because I wanted to support both ESP32 and AVR based boards, I had to change from the things like std::string to an alternate method. I wanted to avoid the String class because I've heard that's a bit of a mess memory wise.
I decided to use char arrays and null terminated strings, and make sure to free them all myself.
From my app, over Bluetooth, I recieve data in the format <id>:<data>, where id is a two digit number (i.e. 01).
Once I receive data, I pass it on to this function, which does some processing:
void CDataUtils::process(char *data) {
    char *split = strtok(data, ":");
    m_id = static_cast<ActionID>(atoi(split));

    uint16_t len = strlen(data) - (strlen(split) + 1);
    char *d = new char[len + 1];

    strcpy(d, split + strlen(split) + 1);

    delete[] split;
    //......
    delete[] d;
}

I split the string with strtok, and use both side so I store that in a variable called split. I take the first section which is the id and cast it to an enum but that is irrelevant for this. I then calculate the length of the data after the colon and create a char array of that size (plus 1).
I then copy the data that comes after the colon into d. Once that is done, because I no longer need split, I free it with delete[]. This causes my ESP to crash though
CORRUPT HEAP: Bad tail at 0x3ffdc795. Expected 0xbaad5678 got 0xbaad5600
abort() was called at PC 0x40081d91 on core 1

ELF file SHA256: 0000000000000000

Backtrace: 0x4008e254:0x3ffc71f0 0x4008e4d1:0x3ffc7210 0x40081d91:0x3ffc7230 0x40081ebd:0x3ffc7260 0x400dd653:0x3ffc7280 0x400d8c65:0x3ffc7540 0x400d8bf4:0x3ffc7590 0x400931b5:0x3ffc75c0 0x400817f6:0x3ffc75e0 0x40081cd5:0x3ffc7600 0x4000bec7:0x3ffc7620 0x40104059:0x3ffc7640 0x400d1fa7:0x3ffc7660 0x400d1e9c:0x3ffc7680 0x400d1b0e:0x3ffc76a0 0x400d32e5:0x3ffc76c0 0x4008ffda:0x3ffc76e0

According to the first link when googling for CORRUPT HEAP: Bad tail, this is usually a sign of writing data outside of a buffer. Surely if that was the case here, the error would occur at the strcpy line, not at the delete line?
What confuses me is I have this little utility function that deletes and reallocates a new array:
char *_realloc_and_null_array(char *arr, uint16_t size)
{
    delete[] arr;         //Free array
    arr = new char[size]; //Create new one of specified length

    memset(arr, 0x00, size); //Fill with null

    return arr;
}

I used to use this in the process function above, and I did not get any errors with it even though I am freeing an array with delete[].
What have I done wrong?
EDIT: I'll reply to the comments here because there's a lot. I appreciate the info on strtok and how I don't need to work out the length of the data, or copy the data to any buffer.
The reason I was trying to delete the pointer to the split was because I didn't realise it was a pointer. I'm not sure how I thought it could be a string but I did/
In terms on the _realloc_and_null_array function it was purely to remove duplicate code. I got the snippet from an SO post but I can't remember the one. When I create a program (in any language) I don't like to just create variables all willy-nilly. In this instance, if I have an array d, I can use that for something, free it, create a new one and fill it with different data. This saves having another unnecessary array.
I re-use arrays a fair bit so it allows me to just create a new array with a different length and get rid of the old one (I don't do it a stupid amount as to where the program is hard to understand. I'll use the function at max once in some functions).
Maybe it's a dumb thing to do but it worked for me so I stuck with it.


texts: How come the console prints error `avrdude: usbdev_open(): did not find any USB device "usb"`?

texts:
How come when I try to push a sketch to my Arduino I see this error on the console? The subsequent sketch does not work.

  avrdude: usbdev_open(): did not find any USB device "usb"

I've already added myself to the dialout group,

  sudo usermod -aG dialout $USER

And, I did that after I confirmed the dialout group owns the device (in my case /dev/ttyACM0:

$ ls /dev/ttyACM0 -l
crw-rw---- 1 root dialout 166, 0 Oct 12 03:15 /dev/ttyACM0


texts: Why does command line BOSSA not recognize Arduino Due?

texts:
Running Ubuntu 12.04.4 LTS (64 bit) I try to upload my code to the Arduino Due through the Native port. I have tried both the bossac that ships with the Arduino IDE (which is a modified version of BOSSA), and the master BOSSA branch.

Running this command:

sudo ./bossac -p /dev/ttyACM0

I get this error:

No device found on /dev/ttyACM0

However, it works perfectly inside the Arduino IDE.

What can the problem be?


texts: Testing Arduino with Visual Studio Community 2013 raise LNK error

texts:
I have two projects in my Visual Studio Community 2013 solution.

I created a project for Arduino, and create another project for Test. When I run the project tests without adding the Arduino project reference, it run ok, but when I add the Arduino project reference I get it error:

LNK1561: entry point must be defined D:\VisualStudioArduino\PrinterProject\LINK PrinterProject

What is the entry point for Arduino project?

It does not generate any file like a dll or main file?

What can I do to solve this error?

UPDATE I

I also tried this configuration in the Arduino Project but I get the same error:

Properties -> Linker -> System -> SubSystem to "Windows (/SUBSYSTEM:WINDOWS)"

UPDATE II

I am using Visual Micro extension. But the problems is when I try to compile the Test project. Then I recreate this scenario with a C++ console application and create a simple class, and create a test project and added the console application reference to test project and it worked. Then my doubts is about to how do I configure a Test Project to test my Arduino project.


texts: How to use Aiduino module to connect to computer network?

texts: I have 4 usb Hard Drives and I just want to connect them to computer network directly without a traditional computer. Is there an any module with 4 usb ports and one RJ45 port. The module should able to connect drives to network as NAS (Network Area Storage) or other mounting possibility.


texts: Error compiling for Arduino Nano 33 BLE with LiquidCrystal library

texts:
I recently started coding in the Arduino IDE for the Arduino Nano 33 BLE I bought.
When I choose the Nano 33 BLE as my board, I get the following Error:

Arduino: 1.8.11 (Windows 10), Board: "Arduino Nano 33 BLE"

In file included from C:\Users\Niels\Documents\Arduino\libraries\LiquidCrystal\src\LiquidCrystal.cpp:1:0:

C:\Users\Niels\Documents\Arduino\libraries\LiquidCrystal\src\LiquidCrystal.h:45:36: error: expected class-name before '{' token

 class LiquidCrystal : public Print {

                                    ^

C:\Users\Niels\Documents\Arduino\libraries\LiquidCrystal\src\LiquidCrystal.h:86:9: error: 'Print' has not been declared

   using Print::write;

         ^~~~~

exit status 1
Error compiling for board Arduino Nano 33 BLE.

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

I do not get this error when compiling for a normal Arduino nano board.
This is my code:

#include <Arduino_LSM9DS1.h>
#include <LiquidCrystal.h>
LiquidCrystal lcd(12,11,5,4,3,2);

//pins:
const int measurePin = 13, calibratePin = 14, xHighPin = 15, xLowPin = 16, yHighPin = 17, yLowPin = 18;

//constants:
const int interval = 10;
const float delta = 10;

//variables:
boolean measureSts = LOW, calibrateSts = LOW, xyOK = true;
int count = 0, timer = 0;
float measurements[100], current, x, y, z, xZero, yZero, zZero;

//programm:
void setup() {
  lcd.begin(16,2);

  pinMode(measurePin, INPUT);
  pinMode(calibratePin, INPUT);
  pinMode(xHighPin, OUTPUT);
  pinMode(xLowPin, OUTPUT);
  pinMode(yHighPin, OUTPUT);
  pinMode(yLowPin, OUTPUT);
}

void loop() {
  if ( IMU.accelerationAvailable() ) {
    IMU.readAcceleration(x, y, z);
    calibrate();
    checkXY();
    measure();
    current = z - zZero;
    printValues();
  }
  else lcd.print("--geen  sensor--");
}

void checkXY() {
  xyOK = true;
  if ( x < xZero - delta ) {
    xyOK = false;
    digitalWrite(xLowPin, HIGH);
    digitalWrite(xHighPin, LOW);
  }
  else if ( x > xZero + delta ) {
    xyOK = false;
    digitalWrite(xLowPin, LOW);
    digitalWrite(xHighPin, HIGH);
  }
  if ( y < yZero - delta ) {
    xyOK = false;
    digitalWrite(yLowPin, HIGH);
    digitalWrite(yHighPin, LOW);
  }
  else if ( y > yZero + delta ) {
    xyOK = false;
    digitalWrite(yLowPin, LOW);
    digitalWrite(yHighPin, HIGH);
  }
}

void measure(){
  if ( digitalRead(measurePin) == LOW && measureSts == HIGH && xyOK ) {
    measurements[count] = z - zZero;
    zZero = z;
    timer = interval;
    count++;
  }
  measureSts = digitalRead(measurePin);
}

void printValues() {
  if ( timer >= interval ) {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Meting: " + String(measurements[count]) + (char)223);
    lcd.setCursor(0,1);
    lcd.print("Huidig: " + String(current) + (char)223);
    timer = 0;
  }
  timer++;
}

void calibrate() {
  if ( digitalRead(calibratePin) == LOW && calibrateSts == true ) {
    xZero = x;
    yZero = y;
    lcd.setCursor(0,3);
    lcd.print("kalibreren");
    lcd.setCursor(1,4);
    lcd.print("voltooid");
    digitalWrite(xHighPin, HIGH);
    digitalWrite(xLowPin, HIGH);
    digitalWrite(yHighPin, HIGH);
    digitalWrite(yLowPin, HIGH);
    delay(100);
    lcd.clear();
    digitalWrite(xHighPin, LOW);
    digitalWrite(xLowPin, LOW);
    digitalWrite(yHighPin, LOW);
    digitalWrite(yLowPin, LOW);
  }
  calibrateSts = digitalRead(calibratePin);
}

For context: I am trying to create an angle-measuring device using the built-in accelerometer and a 2x16 LCD.

I hope someone can help me fixing this.
Thanks in advance.

-Niels


texts:
I am learning Arduino from "Arduino cookbook by Michael Margolis", i was reading about bitwise operations and extracting low and high bytes from int. He said that there is no function in Arduino to extract high and low bytes from long at the time of his writing. He stated an alternative to the problem by adding two line of code.

#define highWord(w) ((w) >> 16)
#define lowWord(w) ((w) & 0xffff)

The first line i clearly understood like this, please make corrections if i am wrong.

32bit binary of 16909060 is 0000 0001 0000 0010 0000 0011 0000 0100

by right shifting last 16 bits we will arrive at

32bit binary of 16909060 after right shifting 16bits is 0000 0000 0000 0000 0000 0001 0000 0010

I am not able to interpret the second line.

#define lowWord(w) ((w) & 0xffff)

I would be very grateful if some body explain how the above line of code works?
Thanks.


texts: How can I send and receive data from an Arduino MEGA 2560 and Python?

texts:
Hello community I am relatively new to the Arduino world and I am facing some issues trying to establish serial communication between the MEGA 2560 and Python using my PC, the desired result is to print the variable 'cnt' after in the code below in Arduino after communicating with Python, below are the codes I am using for the Arduino and in Python. [Note: I am using a PIR sensor(pin 4) that does trigger when an object is nearby and print the first statement on the serial monitor, so the issue is not there.]
Arduino:
int pin = 4; //Output pin of sensor
int cnt = 0; //Count variable after processing in Python
int dat = 0; //Variable to ensure data is being transmitted from Python to Arduino

void setup() {
  Serial.begin(9600);
  pinMode(pin, INPUT);
  pinMode(LED_BUILTIN, OUTPUT); //This output is here to ensure the code runs to the dat if statement and the data is received
}

void loop() {
    int pirsensor = digitalRead(pin);

    if (pirsensor == 1){
      Serial.println("Hello, there's data here in Arduino"); //String as an example bt you want to send the data of the ArduCAM using the serial port
         if (Serial.available()>0){
              dat = Serial.read() - '0';

              if (dat == '1'){
                    cnt = cnt + 1;
                    Serial.print("Count is equal to: ");
                    Serial.print(cnt);
                    digitalWrite(LED_BUILTIN, HIGH); //Turn on LED
                    }
              }

          }
}

Python code:
import serial

dat = serial.Serial('COM5',9600,timeout=1) #Serial object for communication
if (dat.in_waiting>0): #Conditional to verify if there is data in the serial port
    print('Hello')
    dat.write(1)
    print('Works')


texts: Motor running slowly when connected to digital pins, but fine with 5V pins

texts:
I am trying to connect a Dagu DG01D motor to my Arduino Uno. First I tried connecting the black wire to GND and the red wire to digital pin 7. My code:

void setup() {
  pinMode(7, OUTPUT);
  digitalWrite(7, HIGH);
}

void loop() {
}

When I connected the motor, it wouldn't turn, but would rotate a little when turned in one direction. However, when I connected the red wire to 3.3V or 5V, the motor turned quickly as expected. Why didn't writing HIGH to pin 7 work?

I already verified that I can connect and run code on the Arduino by turning on the LED by replacing pin 7 with 13. I also tried running the same code on a SparkFun RedBoard, with similar results.


texts:
I have a text file with an IR raw code that I need to read from the SD in order to send it and I don't know how to do it. I tried to use the read file function from the specific SD library but it didn't work.

irsend.sendRaw(irSignal, sizeof(irSignal) / sizeof(irSignal[0]), khz);

I want to save the code from the SD in the irSignal so I can sent it. Any ideas?

The code I've tried

#include <SPI.h>
#include <SD.h>

#include <IRremote.h>

IRsend irsend;

File myFile;

int k=0;
unsigned int irSignal[227];

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

  Serial.print("Initializing SD card...");

  if (!SD.begin(53)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");

  myFile = SD.open("sc_17.txt");
  if (myFile) {
    while (myFile.available()) {
      int val = myFile.parseInt();
      Serial.println(val);
      irSignal[k]={val};
      k++;
    }
    myFile.close();
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening dc_17.txt");
  }
}

void loop()
{
  int khz = 38;
  irsend.sendRaw(irSignal, sizeof(irSignal) / sizeof(irSignal[0]), khz); //Note the approach used to automatically calculate the size of the array.
  sendSignal();
  delay(2000); //In this example, the signal will be repeated every 5 seconds, approximately.
}

The problem is when I try to implement it in a separate function, because I need to call it for more files, it doesn't work.


texts: Serial.write and Serial.println return different values? Cannot use correct ones

texts:
I have a text file on an SD card, and I am trying to print the lines to the serial monitor.

This Code Works:

#include <SPI.h>
#include <SD.h>

File myFile;

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

  Serial.print("Initializing SD card...");

  pinMode(10, OUTPUT);

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");

  myFile = SD.open("c.txt");
  if (myFile) {
    Serial.println("c.txt:");

    while (myFile.available()) {
      Serial.write(myFile.read());  //THIS LINE RIGHT HERE
    }
    myFile.close();
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening c.txt");
  }
}

void loop()
{
}

However, if I replace the line Serial.write(myFile.read()); with Serial.println(myFile.read());, then the code doesn't return the correct lines.

It should return numbers similar to this (albeit 3000 of them):

564
564
564
564
564
564
564
464
564
664
564

If I use Serial.println it returns numbers like this (and it doesn't stop at 3000 lines):

13
10
54
54
52
13
10
53
54
52

And if I try to do int(myFile.read()) then the integer becomes the wrong numbers (returned by println), not the right ones (returned by write).\

How do I get a number returned by Serial.write(myFile.read()); to be an integer?


texts: Initialize and read from a PROGMEM array of pointers to PROGMEM arrays

texts:
I'm working on a project for the arduino uno for which I need multiple constant arrays of bytes. Such an array is initialized like so:

const byte charR[] PROGMEM = {
  B01111111,//top half
  B01111111,
  B01000100,
  B01000110,
  B01101111,
  B00111001,
  B00000000,
  B01111000,//bottom half
  B01111000,
  B00000000,
  B00000000,
  B01111000,
  B01111000,
  B00000000
};

This array represents the capital letter R. I read the nth byte of this array like so:

nth_byte = pgm_read_word(charR+n);

This is all fine and good so far, but now I need to take it a step further. I need to create the array message[]. I need to use message[] to read byte arrays in a certain sequence. For instance:

message[] = {
  charR,
  chare,
  charp,
  charl,
  chary,
  charspace,
  charp,
  charl,
  chare,
  chara,
  chars,
  chare
};

Each entry in message[] refers to a byte array that represents a character. Notice how multiples appear. This is kind of like a 2-D array, but I want to save progmem by only defining each character once.

How do I properly initialize message[]? Will I need to use pointers for this? How do I properly get the array size or yth byte of the xth entry in message[]?


texts: ESP8266 not working with MPU 6050 over wire library and I2C

texts:
I'm trying to use this version of ESP8266 to access MPU 6050. However, it's not working.

https://www.amazon.com/gp/product/B07HF44GBT/ref=ppx_yo_dt_b_asin_title_o07_s00?ie=UTF8&psc=1 i.e. NodeMCU CP2102 ESP-12E

The code worked with nano very fine. However, when I tried to scan the I2C device, it's said I2C device not found.

I have tried

  Wire.begin(D2, D1);

and

  Wire.begin(4, 5);

i.e. to change the pin to GIOP 4 5 in case if the default was not working.
I have also tried to put a large capacitor between the power lines, still not working.

Why ESP8266 does not work with MPU 6050?(Serial and wire together)

Updates:
Sometimes it does say device found, but after two updates, it turned to be not found again.

Updates 2:
I watched the video and did what G6EJD suggested, i.e. restarted the IDE and everything. Now it's reading data. However, the data reading was somehow incorrect by a large factor.
For example, at flat the device is reading

42.63/-38.37/7.82

for angle x,angle y,and angular speed z with complementary filter applied and steady at flat surface. It worked for nano but not for ESP 8266.

Also, I tried to adjust the circuit like the spectrum dandavis suggested. I tried resistor range from 4.7 k to 10, even directly connect to the power source. The attempts also included 100 $\mu$F capacitor and power board to stabilize the noise. Both pull up and pull down has been attempted as well as changing boards. However, none of those were working and the issue persisted. The pull up resistor did not seem to be response to what the device was reading.

Update 3:
The power consumption has been ruled out and a pair of 100k resistor was also attempted. Not working.


texts: Open video file if sensor reaches certain threshold value

texts: I am an ABSOLUTE beginner at Arduino and my first project I've proposed to my teacher is as follows: an Mq-2 smoke sensor will sense smoke and if the level of smoke reaches a certain value (only because I want the smoke to accumulate for aesthetics purposes) then a video file in whatever directory opens and plays. It seemed plausible at first, but as I search for pertinent info., I am faced with content and hobbyists whose instructions and "knowledge" are way out of my depth. Can anyone help me with this? If anyone knows a good website/tutorial videos/documents/books that a beginner like me should take to improve his programming and physical computing(?) skills, please let me know!


texts: What is the use of decoupling capacitor?

texts: I dont understand what does the word "decoupling" mean? Where and Why it is used? Can anyone give me a brief idea>?