texts:
I found a really nice 24 bit I2C adc which was fairly cheap as well (ADS1219) but as far as I could tell there are no libraries for it so I decided to make my own. I have managed to write functions and get everything working on the arduino itself but I've been having massive issues with converting it into a library.
So I tried a very basic sketch to see if I can do something as simple as printing hello world using the library.
Here is my ADS1219.h file:

#ifndef ADS1219
#define ADS1219

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

class ADS1219{
public:
 ADS1219();
 void begin();
 void printHello();
};

#endif

And the ADS1219.cpp:

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

#include

ADS1219::ADS1219{
 Serial.println("New object created!");
}

void ADS1219::begin(){
 Serial.begin(9600);
}

void ADS1219::printHello(){
 Serial.println("Hello World");
}

and my main sketch:

#include

ads = new ADS1219;

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

void loop() {
  ads.printHello();
  delay(2000);
}

but I get this really long error which basically says I've failed with creating the ads object.
I tried ADS1219 ads; as well but same error ... not sure what's wrong tbh.

Arduino: 1.8.8 (Windows 10), Board: "Arduino Nano, ATmega328P (Old Bootloader)"

In file included from sketchADS1219.cpp:7:0:

ADS1219.h:14:11: error: expected unqualified-id before ')' token

   ADS1219();

           ^

ADS1219.h:12:14: error: an anonymous struct cannot have function members

 class ADS1219{

              ^

ADS1219.h:18:1: error: abstract declarator '' used as declaration

 };

 ^

ADS1219.cpp:9:17: error: expected id-expression before '{' token

 ADS1219::ADS1219{

                 ^

ADS1219.cpp:13:21: error: explicit qualification in declaration of 'void begin()'

 void ADS1219::begin(){

                     ^

ADS1219.cpp:17:26: error: explicit qualification in declaration of 'void printHello()'

 void ADS1219::printHello(){

                          ^

In file included from C:UsersOM222ODesktopadslibadslib.ino:1:0:

ADS1219.h:14:11: error: expected unqualified-id before ')' token

   ADS1219();

           ^

ADS1219.h:12:14: error: an anonymous struct cannot have function members

 class ADS1219{

              ^

ADS1219.h:18:1: error: abstract declarator '' used as declaration

 };

 ^

adslib:3:1: error: 'ads' does not name a type

 ads = new ADS1219;

 ^

C:UsersOM222ODesktopadslibadslib.ino: In function 'void setup()':

adslib:7:3: error: 'ads' was not declared in this scope

   ads.begin();

   ^

C:UsersOM222ODesktopadslibadslib.ino: In function 'void loop()':

adslib:11:3: error: 'ads' was not declared in this scope

   ads.printHello();

   ^

exit status 1
expected unqualified-id before ')' token

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


texts:
I am creating a simple shield with two i2c MCP23017 chips. Each MCP23017 has two interrupt pins, but the Arduino Uno only has two interrupt pins (pin 2 and pin 3).

The way I understand it, interrupts are there to tell the Arduino something has changed, so it can then poll the MCP23017 for the latest pin reads.

How can I connect the 4 interrupt pins to my Arduinos 2 pins?


texts: How to change baudrate of ESP8266 (12e) permanently?

texts:
IMPORTANT: DO NOT USE AT+IPR=9600! (see update)

I have an ESP8266 12E module that communicates at 115,200 bauds. Since I use it with an Arduino Nano with SoftwareSerial things get messy. So I found that I should reduce the baud rate of the ESP module.

I found this link on how to do it.

I am wondering

Is this a permanent change or do you need to do this every time after the module is powered?
Can I achieve the same by sending the command from the Arduino over SoftSerial? Well, I guess not since I tried and I always get an error on AT+CIOBAUD=9600 or AT+IPR=9600.
I read somewhere that in newer firmware versions of the ESP8266, the baud rate defaults to 9,600. Can anyone confirm this and if so, is it better to flash this newer firmware?

The module's vendor:

Ai-Thinker Technology Co.,Ltd.

I think the current version of the firmware is 0.3.0. If I send  AT+GMR I get:

sending AT+GMR

response: ?AT¥TJÕ¨H(Q�²•ÉÍ¥½¹é‚r¢‚r‚r‚BÕ��Â’‚ŠªŠ¢Ò¢ªÒªÂJm
 SDK versioo:0.3.0
 Ai�½½
 ‚Šj

Again some garbage because of the baud rate which is too high.

Other info on the module:

sending AT+RST
response: ?AT+RST
OK
WRT
"%M
<99CT
 ets Jan  8 2013,rst catse:2, boot lode:(3,7)
load 0x40100000ntail 4
chksum 0x89
ld tail 4
chm3 tail 8 r 0 aM
 ón't use rtc mem dat`
sl��oÌÿ
Ai-Thinker Technology Co.,Ltd.

UPDATE

(*) I used an FTDI232 module to send AT+IPR=9600 to my ESP8266-12E module and I bricked it!

DO NOT USE AT+IPR=9600 ON AN ESP8266(-12E).

I did not manage to recover it so far! I tried re-flashing it but I get Invalid head exceptions.

On a new module I sent the AT+CIOBAUD=9600 command and it worked. Permanently!

My module specs:

AT+GMR
AT version:0.40.0.0(Aug  8 2015 14:45:58)
SDK version:1.3.0
Ai-Thinker Technology Co.,Ltd.
Build:1.3.0.2 Sep 11 2015 11:48:04
OK


texts: Erratic behavior from 'randomly' generated values in array

texts:
Currently working on a data collection algorithm on the Arduino MEGA (ATMega1280) and I've run into a problem with some of the code I've written. I feel my problems may be stemming from the way in which I'm storing the sample points I've generated in arrays ats1 and ats2 or in the ways that I'm generating said sample points in generate_tspairs. Any insight would be appreciated.

I've defined a struct in an external file structs.h

struct tspair{
  int t;
  int s;
};

I have a function defined in generate_tspairs.h

    void generate_tspairs(tspair ats1[], tspair ats2[], int N, int reps1, int reps2, int reps3){

        int alpha = log(N)/log(2); //equivalent to log2(N)

        for(int j =  0 ; j < reps1 ; j++){
            double randomDecimal = (double) random(1000)/1000;
            int r = (int) pow(2,alpha-1)*randomDecimal + 1;
            int s = 2*r - 1; //s is a random odd integer on the interval [1,N-1]

                for(int n = 0 ; n < reps2 ; n++){
                    double randomDecimal = (double) random(1000)/1000;
                    int t =  (int) N*randomDecimal;
                    tspair temp = {t,s};
                    ats1[(j*reps2)+n] = temp;
                }

                for(int n = 0 ; n < reps3 ; n++){
                    double randomDecimal = (double) random(1000)/1000;
                    int r = (int) pow(2,alpha-1)*randomDecimal + 1;
                    int s = 2*r - 1; //s is a random odd integer on the interval [1,N-1]

                    randomDecimal = (double) random(1000)/1000;
                    int t =  (int) N*randomDecimal;
                    tspair temp = {0,s};
                    ats2[(j*reps3)+n] = temp;
                }
        }
    return;
    }

After initializing and setting my two arrays of tspair structs, I am printing the values of the first array ats1 using the following in driver.ino

  int reps1 = 3;
  int reps2 = 5;
  int reps3 = 5;

  tspair ats1[reps1*reps2];
  tspair ats2[reps1*reps3];

  generate_tspairs(ats1, ats2, N, reps1, reps2, reps3);

  for(int i = 0 ; i < reps1*reps2 ; i++){
    Serial.print("t: ");
    Serial.print(ats1[i].t);
    Serial.print(" s: ");
    Serial.println(ats1[i].s);
  }

However, oftentimes I will receive the exact same values across multiple runs of generate_tspairs or when printing the values it will not stop at the end of my ats1 but rather it will continue to print the same line ad infinitum. E.g.

t: 815 s: 523
t: 975 s: 523
t: 244 s: 523
t: 8689 s: -26051
t: 31001 s: 29184
t: -25856 s: 6939
t: -2057 s: 6939
t: -2057 s: 6939
t: -2057 s: 6939
t: -2057 s: 6939
t: -2057 s: 6939
t: -2057 s: 6939
t: -2057 s: 6939
t: -2057 s: 6939
t: -2057 s: 6939
t: -2057 s: 6939
t: -2057 s: 6939
t: -2057 s: 6939
...
...
...
t: -2057 s: 6939


texts:
I'm building an audio cable tester/soldering station.  XLR cables have 3 pins and they can be wired in a few ways depending on what you want to do.  The basic cable is connected 1 for 1 and I want to make a system to verify if each pin is connected to the good ones on the other connector.

Picture the male and female connectors side by side.  The 3 pins on the male connectors will be connected to 3 digital outputs and the 3 pins on the female connector will be connected to 3 digital inputs.  That way, I can turn one of the outputs High and check my 3 inputs to see where that pin on the male connector is wired on the female connector.  Then I can walk the remaining outputs and find out how the rest of the cable is wired.

That part is all good, I can output the wiring via the Serial.print() command and the result is good.  The thing is that I would like to show the result with LEDs.  It brings me up to 9 LEDs in a 3x3 matrix.  I can use 9 outputs to show the result, but it seem like there could be a much better way.

The two solutions I see are the following:

Buying addressable LEDs and interface them with my Uno
Use 6 outputs, one for each row and one for each column.  Each row represents one pin on the male connector, each row represents one pin on the female connector.  So while I walk my 3 pins I can turn on the corresponding row and columns, then turn off that row and go to the next one, turn on the corresponding columns, etc.  I feel like this would work, but I'm wondering if the LEDs will flicker or if the refresh will be fast enough not to be noticeable.

What would you suggest?  Am I on the wrong track with solution #2?  Is there another way that does not require that many outputs?  I'm already up to 12 IO pins taken with #2 and 15 with #1.  It seem like a lot for such a simple build...


texts: Arduino mega PinChangeInterrupt with 16 bit timer

texts:
With reference to this question ::I have written a program by using 16-bit timer,
The program is as follows .
volatile uint32_t ovfCount = 0;

struct Pulse {
  uint32_t last_toggle;
  uint32_t width;
  bool stateHigh;
  uint32_t get_width() {
    noInterrupts();
    uint32_t width_copy = width;
    interrupts();
    return width_copy;
  }
};

Pulse ch1, ch2, ch3, ch4, ch5, ch6;

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

  pinMode(13, OUTPUT);

  /*
     Pin Change Interupt for
     measuring the pulse width
     from the receiver

  */

  DDRK = 0; // A8:A15 -> direction as Input
  PORTK = B00111111; // A8:A15 -> pullupResistor

  PCIFR = 0; // resetting the flags
  PCIFR  = _BV(PCIF2);
  PCMSK2 = B00111111; // activating from A8:21 :: 6
  PCICR = B00000100; // activating 2 nd PCINT

  /*
     16 bit timer setup for counting
     timer 3 is used
  */
  TCCR3B = 0x00;
  TCCR3A = 0x00; // wave generation is normal:: all zeros
  TCNT3 = 0x00;
  TIFR3 = 0x00; // resetting all flags
  TIMSK3 = 0x01; //timer overflow enable
  TCCR3B = 0x01; // no prescaling

}

ISR(TIMER3_OVF_vect) {
  ovfCount++;
}

ISR(PCINT2_vect) {
  uint8_t tcnt3 = TCNT3;
  uint32_t ovf_count = ovfCount;

  if ( bit_is_set(TIFR3, TOV3) && tcnt3 < 32768 ) {
    ovf_count ++;
  }

  uint32_t time = ovf_count << 16 | tcnt3;

  pinChangeFunction(&ch1, time, PK0);

}

void pinChangeFunction(Pulse *channel, uint32_t time, uint8_t pin) {
  bool input_is_high = bit_is_set(PINK, pin);
  if (input_is_high && !channel->stateHigh) {
    channel->stateHigh = true;
  } else if (! input_is_high && channel->stateHigh) {
    channel->width = time - channel->last_toggle;
    channel->stateHigh = false;
  }
  channel->last_toggle = time;
}

void loop() {
  digitalWrite(13, HIGH);
  delay(1000);
  digitalWrite(13, LOW);
  delay(200);

  Serial.println(ch1.get_width() / 16e3, 5);

}

The output for the same is attached below,
999.42663
999.43060
999.42645
999.42614
999.42730
999.42889
1003.52416
999.41473
999.42681
999.42211
999.42077
999.42718
999.42016
1003.52447
999.41802
999.42480
999.42541
999.43603
999.42767
1003.52075
999.42199
999.42767
999.41876
999.42816
999.41143
999.41998
1003.52429
999.42730
999.42950
999.41149
999.42028
999.42700
1003.50775
999.43743
999.42858
999.42584
999.41381
999.42852
999.43347
1003.52490
999.41925
999.41540
999.42510
999.42895
999.42980
999.42883
1003.52526
999.43658
999.43707
999.42889
999.41284
999.42401
1003.52343
999.42901
999.42950
999.42822
999.43481
999.42718
999.41986
1003.52398
999.42303
999.41442
999.42498
999.42950
999.42547
1003.51074

When I observed the output , I am seeing 999 millis almost instead of 1000 as expected and  in-between  1003 is coming instead either of 999/1003.
Also if we look carefully it can be observed that ,999 is coming 6 times then one 1003 is coming and is going 2 times like that then 5 times 999 then 1003
so I want to know what mistake I am making in my program , and what is the reason behind these kind of behaviour .


texts:
I have a simple question to ask you about SDA and SCL pins.
I have a gyro and I use these 2 pins to make it work; how can I use an accelerometer combined to a Gyro if these 2 pins are used? I should need another 2 SDA and SCL pins for the accelerometer... Tell me that I don't need to buy an IMU :D

EDIT: I'm using Gyro LG3D20H from Adafruit, reading gyro values each 10 ms.


texts:
I am using an MG946R Servo.

When I use the power directly from the Arduino (Uno) and do a sweep, it works as expected.

However, when I replace the Arduino power with external power, the Servo either doesn't move or it moves randomly.

I've tried this with both a multi voltage power adaptor, setting the power to both 4.5V and 6V, as well as with a 4 x AA battery pack.

When I use a multi meter set at 6V and check the pins going into the Servo (when it's moving randomly) the voltage keeps moving to anywhere between  5.20V and 5.70V.

It seems that the Servo doesn't move when using battery pack, even though the voltage on the pins reads 5.75V.

Is there something that I am missing here?


texts: Bit mask first 2 bits of 16 bits for accelerometer

texts:
The datasheet for the accelerometer states that:

Here is the data output from the accelerometer:

I have tried to mask the first two bits using a bitwise AND command with B0011111111111111.

I tried to use this code, but unfortunately the first 2 bits are still "11" so the value has not changed:

int bresult=0b0011111111111111&result;
Serial.print(bresult,BIN);

How would I bits mask the first two bits and will arduino automatically know how to convert to twos compliment?

The variable result is of data type "long"

According to an answer, I tried:

int bresult= result<<2;
Serial.print(bresult,BIN);

I got this result which is great but is it possible to remove the last two zeros because this is making my value larger?
The image below shows result then bresult.


texts: How to run multiple DC motors in different patterns?

texts:
I am a complete novice in programming and I hope someone could guide me here. I am doing a haptic research project, where 8 DC coin vibrating motors would be fitted on the fingers of subjects (excluding thumbs), and the subject has to respond the number of fingers they feel the vibrations on.
Every trial has to have a different pattern of outputs, say: in first trial, 4 motors are activated-motor 1, motor5, motor8 and motor 3. In a single trial, the motors have to have a common delay of 150 ms and 4 seconds break after next one starts.
My question is, that in 8 motors, there are 255 different activation patterns possible. How do I define all these 255 patterns and randomise their sequence?
I am using the mega board and connecting each motor to a PWM pin and all having a common ground.
Here is a sample code with 3 such combinations (only seven motors are connected here):
#define viboutpin 2
#define viboutpin1 3
#define viboutpin2 4
#define viboutpin3 5
#define viboutpin4 6
#define viboutpin5 7
#define viboutpin6 8

void setup() {
     pinMode(viboutpin,OUTPUT);// define a pin as output
     pinMode(viboutpin1,OUTPUT);
     pinMode(viboutpin2,OUTPUT);
     pinMode(viboutpin3,OUTPUT);
     pinMode(viboutpin4,OUTPUT);// define a pin as output
     pinMode(viboutpin5,OUTPUT);
     pinMode(viboutpin6,OUTPUT);
}

void loop() {
    digitalWrite(viboutpin,HIGH);
    digitalWrite(viboutpin1,HIGH);
    digitalWrite(viboutpin2,HIGH);
    digitalWrite(viboutpin3,HIGH);
    digitalWrite(viboutpin4,HIGH);
    digitalWrite(viboutpin5,HIGH);
    digitalWrite(viboutpin6,HIGH);
    delay(150);
    digitalWrite(viboutpin, LOW);
    digitalWrite(viboutpin1,LOW);
    digitalWrite(viboutpin2,LOW);
    digitalWrite(viboutpin3,LOW);
    digitalWrite(viboutpin4,LOW);
    digitalWrite(viboutpin5,LOW);
    digitalWrite(viboutpin6,LOW);
    delay(2000);

    digitalWrite(viboutpin2,HIGH);
    digitalWrite(viboutpin6,HIGH);
    delay(150);
    digitalWrite(viboutpin2,LOW);
    digitalWrite(viboutpin6,LOW);
    delay(2000);

    digitalWrite(viboutpin4,HIGH);
    delay(150);
    digitalWrite(viboutpin4,LOW);
    delay(2000);
}


texts: Why SD.exists() only looks for inside media/realroot on Intel's Galileo?

texts: I'm following a tutorial which says SD.exists() only look for files inside media/realroot on Intel's Galileo board. I just confirmed this using SSH to create e remove files during a loop which was looking for some specific named file. Where's information about this? I searched for cpp files inside SD library and found nothing.


texts: Help in "An error occurred while uploading the sketch"

texts:
Trying to test THIS. Got following error:

esptool v0.4.13 - (c) 2014 Ch. Klippel <ck@atelier-klippel.de>
    setting board to nodemcu
    setting baudrate from 115200 to 9600
    setting port from COM1 to COM3
    setting address from 0x00000000 to 0x00000000
    espcomm_upload_file
    espcomm_upload_mem
    setting serial port timeouts to 1000 ms
opening bootloader
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
Uploading 356000 bytes from C:\Users\PRAMIT~1\AppData\Local\Temp\arduino_build_521093/testPersWiFiManager.ino.bin to flash at 0x00000000
    erasing flash
    size: 056ea0 address: 000000
    first_sector_index: 0
    total_sector_count: 87
    head_sector_count: 16
    adjusted_sector_count: 71
    erase_size: 047000
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    setting serial port timeouts to 15000 ms
    setting serial port timeouts to 1000 ms
    espcomm_send_command: receiving 2 bytes of data
    writing flash
................................................................................ [ 22% ]
................................................................................ [ 45% ]
................................................................................ [ 68% ]
.......................An error occurred while uploading the sketch

All libraries are included, no compile error.
Steps followed:
1st uploaded the data using Tools>ESP8266 Sketch data upload.
Then Sketch>upload

After failing this, I tried a basic example similar to THIS. This uploaded successfully. The same configuration is used for both scenarios.

What am I missing? I am getting no clue.

Settings:


texts:
I have an Arduino GSM shield and I plan to purchase an Adafruit GPS shield. The GPS module uses Pin 7 & 8 for Rx and Tx, but the GSM shield uses Pin 7 for Modem Reset.

Will the overlap on pin 7 affect it in any way? If it does cause issues, how can the problem be avoided?


texts: GET data from influxdb database on LED matrix via NodeMCU

texts: I can find tons of tutorials of how to POST data to an influxdb database from a sensor connected to a ESP8266 for example. But I would like to find out how to build it the other way around, for example I would like to see the LAST value of a certain measurement from an influxdb database printed on an LED matrix connected to a NodeMCU ESP8266. Any good tutorials, hints or sources to find out how to do this? Thx!


texts: Using a library of sleeping with a combination of the WD and a physical INTERRUPT

texts:
I would like to use one of the nice libraries like :

JEELIB
ENERLIB
SLEEP_N0M1
NARCOLEPTIC
ADAFRUITSLEEPY_DOG
LOW_POWER_MASTER

But to use a X second interval of sleeping and in the same time to enable the option of an Interrupt on pin2 that will get me out of all this sleepy mode vector if there will be interrupt ! which library is better and easier for this situation?
when I want more then 8 second , what is the mining of doing 2x8s when they wrote it in some of those libraries -what should it mean to do ?
Is there an option to enable the interrupt for a wake up from the sleep not only by a LOW_mode but also by a CHANGE_mode of the pin2 ??

Thank you very much in advanced @!


texts: How to flash/blink I2C LCD backlight without delay function?

texts:
Since I am an using I2C LCD backpack, I'm unable to call in for pinmode to set variables like #define BACKLIGHT_PIN 13. I know lcd.setBacklight(HIGH); and lcd.setBacklight(LOW); controls the I2C LCD backlight, but if I use delay in the loop it slows down the whole loop.

How do I flicker the LCD backlight without using delay? I tried for example to blink without delay, but I don't know how to assign a global variable to lcd.setbacklight so as to control it.

I want to use an if statement to warn the user that so and so has happened, eg:

#include <Ticker.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

//Ticker flashBacklight(toggleBacklight, 100);
// when I use ticker here am getting not declared in scope
const int buttonPin = 3;
int buttonState = 0;
// pls declare flashBacklight, long flashBacklight = 100; ??
// pls declare toggleBacklight

void toggleBacklight() {
  // lcd.setBacklight(!lcd.getBacklight());
  // !lcd.getbacklight() spelling mistake ? or it is setbacklight?
}

void setup() {
  lcd.begin(20, 4);
  lcd.setBacklight(HIGH);
  pinMode(buttonPin, INPUT);
 }

void loop() {
  buttonState = digitalRead(buttonPin);
  if (buttonState == HIGH) {
    // if button goes high the back light must keep on flashing until it's released
    flashBacklight.start();
    //flash the lcd backlight
  } else {
    flashBacklight.stop(); // Stop flashing the backlight
  }
  flashBlacklight.update();
}

But delay slows down the whole loop, so how do I flash the backlight without it? Thank you.


texts:
Sorry for any grammar mistakes. It's my second language.

I had a little test with my Arduino Uno R3 I connected 2 buttons to power , GND using 10k resistors and pins 2 and 4.
I connected piezo to power and ground.

When you pressed a button1 then you should hear 'c' tone,
but when I pressed the second button nothing happend and I don't understand why?

Here is my code below:

const int buttonPin2 = 4;
const int buttonPin1 = 2;
const int piezopin =  6;

int buttonState1 = 0;
int buttonState2 = 0;

void setup() {

  pinMode(piezopin, OUTPUT);
  pinMode(buttonPin2,INPUT);
  pinMode(buttonPin1, INPUT);
}

void loop() {

  buttonState1 = digitalRead(buttonPin1);
  buttonState2 = digitalRead(buttonPin2);

  if (buttonState1 == HIGH) {
    tone(6,261.63,500);

  } else {

  }
  if (buttonState2 == HIGH) {
    tone(6,392.00,500);
  } else {

  }


texts: I am using the RX LED pin as CS for my SPI connection and experiencing problems while debugging and communicating via SPI. Is it possible somehow to disable the RX blinking while using the serial monitor?


texts:
I have made a button with an LED using an arduino micro. It's connected to my pc and when I hit the button, the LED activates and a recording on Reaper (digital audio workstation) is started. When I hit the button again, the LED turns off and the recording stops and is saved.

I want the LED to flash at the BPM rate of the project in Reaper. So it needs to read the amount of Beats per minute the project is set to.

Is there any way the arduino can read this value?
Without the flashing LED, the program works fine. Here's the code:

#include <Keyboard.h>

boolean toggle = false;
int inPin = 2;
int outPin = 3;

int state = HIGH;
int ledOn;
int reading;
int previous = LOW;

long time = 0;
long debounce = 200;

void setup() {
  // make pin 2 an input and turn on the
  // pullup resistor so it goes high unless
  // connected to ground:
  pinMode(inPin, INPUT_PULLUP);
  pinMode(outPin, OUTPUT);
  Keyboard.begin();
}

void loop()
{
  reading = digitalRead(inPin);
  ledOn = digitalRead(outPin);

  // if the input just went from LOW and HIGH and we've waited long enough
  // to ignore any noise on the circuit, toggle the output pin and remember
  // the time
  if ((reading == LOW) and (ledOn == LOW)) {
    state = HIGH;
    Keyboard.press((char) 128);
    Keyboard.press('r');
    delay(50);
    Keyboard.releaseAll();
    delay(300);
  }

  if ((reading == LOW) and (ledOn == HIGH)) {
    state = LOW;
    Keyboard.press((char) 32);
    delay(10);
    Keyboard.releaseAll();
    delay(100);
    Keyboard.press((char) 177);
    delay(10);
    Keyboard.releaseAll();
    delay(300);

    time = millis();
  }

  digitalWrite(outPin, state);

  previous = reading;
}


texts: Controlling a sliding tray - beginners project

texts:
I have a small light metal platform about 30 cm square mounted on horizontal rails. It is well lubricated and slides easily from side to side. I would like to build a device to connect to the underside of the platform that will allow me to programatically move the platform left or right by a defined distance at the touch of a button.

While I've never used an Arduino, I've been aware of its existence for a while and felt this might be a good project to begin experimenting with it. For context, I'm a computer programmer by trade, but have limited exposure to electronics in general.

Where would be a good place to start?  Are there books that are considered the "bible" of Arduino development? Are there existing projects that  basically do what I'm hoping to achieve? Am I barking up the wrong tree and shouldn't be attempting to find a solution for this with an Arduino? Any input would be greatly appreciated.


texts:
I need help in my Arduino project. I am trying to add the current time in Serial Monitor but i couldnt make it happen... I was also trying to do something like this...

Here is my current code right now...

// Purpose: To monitor the room temperature
// Programmer: Emmanuel Quiambao Sr.
// Date: Nov. 26, 2019

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

// set the current time
// Set temperature parameter
const int hot = 85;
const int cold = 70;
const int motorPin = 7;
int switchState = 0;

void setup () {

  pinMode(A0, INPUT); // Temp sensor
  pinMode(10, OUTPUT); // Green Led
  pinMode(9, OUTPUT); // Yellow Led
  pinMode(8, OUTPUT); // Red Led
  pinMode(motorPin, OUTPUT); // Fan
  lcd.begin(16, 2);
  lcd.clear();
  lcd.setCursor(0, 0);
  Serial.begin(9600); // opens serial port
  Serial.println("Time Voltage Temperature");

 }

void loop(){

  int sensor = analogRead(A0);
  float voltage = (sensor / 1024.0) * 5.0;
  float tempC = (voltage - .5) * 100;
  float tempF = (tempC * 1.8) + 32;
  int reading = analogRead(A0);
  unsigned long curMillis = millis( );  // get current time

  Serial.print(" ");
  Serial.print(voltage);
  Serial.print(" \volts");
  Serial.print(tempF);
  Serial.print(" \F");

  Serial.print(curMillis);
  Serial.println( );
  delay(100);

  if (tempF < cold)            // Too cold
  {
  digitalWrite(10, HIGH);
  digitalWrite(9, LOW);
  digitalWrite(8, LOW);
  lcd.setCursor(1,0);
  lcd.print(" Too Cold "); // print results to lcd
  lcd.setCursor(1,1);
  lcd.print(tempF,1);
  lcd.print("F");           // print results to lcd
  }

  else if (tempF >= hot)      // Too hot
  {
  digitalWrite(10, LOW);
  digitalWrite(9, LOW);
  digitalWrite(8, HIGH);
  lcd.setCursor(1, 0);
  lcd.print(" It's Hot "); // print results to lcd
  lcd.setCursor(1,1);
  lcd.print(tempF,1);
  lcd.print("F");           // print results to lcd
  }

  else                        // Desired temperature
  {
  digitalWrite(10, LOW);
  digitalWrite(9, HIGH);
  digitalWrite(8, LOW);
  lcd.setCursor(1, 0);
  lcd.print(" It's Fine "); // print results to lcd
  lcd.setCursor(1,1);
  lcd.print(tempF,1);
  lcd.print("F");           // print results to lcd

   switchState = digitalRead(9);
  if (switchState == HIGH) {
    digitalWrite(motorPin, HIGH);
  }
  }

  delay(5000);
}


texts:
I am interested in storing accelerometer data to an SD card. Since power consumption is the main consideration of my project, it is important to do as few writes to the SD as possible, because the SD requires much current, and also takes long to be written, keeping my MCU from sleeping.

The data to be stored are about 50 bits of data at 10Hz, so I need to store 500c bits per second, or around 63 bytes per second. The arduino uno EEPROM is 1024 bytes, which could give me around 16 seconds of data stored before having to access my SD card. However I have seen that the EEPROM has limited write cycles (100000). So each byte can be written 100000 times, which gives us a total of 1000*100000=100000000 bytes to be written.As a result, with writing there 63 bytes per second, that would give me 1587301 seconds=441hours=18days of EEPROM lifetime, which is unacceptable. Is this correct?
If (1) is correct and using internal eeprom is not a possible solution, what other recommendations do you have? Is there an alternative to SD storage, that requires less power and less writing time, so that it is cheaper power-wise? The total storage should be around 200MB.


texts: Arduino Due - creating an 8Mhz clock signal

texts:
I am attempting to interface a OV7670 camera to an arduino Due. (I am fairly new to this although have been programming for many years).

I need to generate a clock signal for the camera at a minimum of 8Mhz - I realise using the pre-scalers I can only get an approximation but I am cool with that.

I finally got a nice steady 3mhz signal from the sketch below (note that the irq routine for TC6 is not used and will be removed very soon (as soon as I get home).

I think I have a conceptial problem with the timers because as I am initialising RA and RC to 1 and telling via TC_Configure to toggle the line, and because I am using CLOCK1 (42 Mhz), I believe with those values of RA and RC I should be getting a 21'ish MHZ signal.

Ie RA starts at zero. First CLOCK1 tick. (at second/48,000,000) interval. RA Goes to 1 COmpares to RC Because they are equal, resets RA to 0 and toggles TIOA6 Next Clock1 tick occurs.....

As I said I am only getting a 3Mhz signal.

void TC6_Handler()
{
        TC_GetStatus(TC2, 0);

}

void startTimer(Tc *tc, uint32_t channel, IRQn_Type irq) {
        pmc_set_writeprotect(false);
        pmc_enable_periph_clk((uint32_t)irq);

        TC_Configure(tc, channel,
               TC_CMR_WAVE |
               TC_CMR_WAVSEL_UP_RC |
               TC_CMR_TCCLKS_TIMER_CLOCK1|
               TC_CMR_ACPA_TOGGLE );  // RC compare TOGGLES TIOA);

        TC_SetRA(tc, channel, 1); //50% high, 50% low
        TC_SetRC(tc, channel, 1);

        PIO_Configure(PIOC,
                   PIO_PERIPH_B,
                   PIO_PC25B_TIOA6,
                   PIO_DEFAULT);

       TC_Start(tc, channel);

}

void setup(){

        startTimer(TC2, 0, TC6_IRQn);
}

void loop(){
}


texts: Serial, Numbers sent as Floating Point and Characters are different at 1e-8 level

texts:
I have some code that generates random numbers on the Arduino, it then sends these random numbers firstly, using Serial.print(float data,int lenght) and as a floating point number using the following function

void send_float (float arg)
{
  // get access to the float as a byte-array:
  byte * data = (byte *) &arg;

  // write the data to the serial
  Serial.write (data, sizeof (arg));
  Serial.println();
}

I then receive this data using python, take the absolute difference of the two values, discard any differences less than the length with which I send the string and output the rest to the screen.

I observe two things, a) Fluctuations of the order with which I send the data (ie. if I send to 6 decimal places then I see fluctuations of ~1e-6), this is reasonable and b) I see fluctuations of absolute value 1e-8 or lower independent of what accuracy I send the string.

Even if I send the string to 11 decimal places, when I compare against the float I see fluctuations up to but not above 1e-8.

Why? This doesn't make any sense. My full code is actually the answer to an old unanswered stack exchange question


texts: Reliably measuring the energy consumption of arduino running sketch

texts:
I would like to know if there is a programmatic way of measuring the energy consumption of a sketch or at least if this is possible via external devices.

My aim is to compare the energy consumption of two devices, connected to usb, running slightly modified versions of the same sketch e.g., one using crypto and one without using crypto.


texts: I know that MP3 is the most popular audio format out there, but I need to be able to convert them to wav files for bother project I'm working on. It can be done with a PC but I would like to know if there is a way of decoding a MP3 file and turning it into a pcm wav file on an Arduino. I don't want to use an extra chip, as I do not plan on playing the MP3s, just converting them.


texts:
I want to install several Arduino controlled relays which are use to turn on/off some lights, a fog machine and some door locks in a building.  What do I need to do to insure that the power relays don't violate building code?

Do components need to be put in a box or can they be mounted to a 2x4?
Are there requirements regarding the points were the bear wire is screwed into the relay?

I am assuming that if anyone as ever wired an Arduino into a garage door opener, these questions may have come up.


texts: Need Help with Switch Case commands/receiver and lcd screen project?

texts:
I am doing a project with a receiver and transmitter and i am trying to get a message to print onto the screen. If anybody has any experience with this could you please help! I am trying to use a switch case command and it's not working.
Edit:

`

#include <LiquidCrystal.h>
#include <VirtualWire.h>
LiquidCrystal lcd(12, 8, 5, 4, 3, 2);
byte message[VW_MAX_MESSAGE_LEN]; // a buffer to store the incoming messages
byte messageLength = VW_MAX_MESSAGE_LEN; // the size of the message
void setup()
{
  Serial.begin(9600);
  Serial.println("Device is ready");

  // Initialize the IO and ISR
  vw_setup(2000); // Bits per sec
  vw_rx_start(); // Start the receiver
  lcd.begin(16, 2);

  // Print a message to the LCD.
}

void loop()
{
  if (vw_get_message(message, &messageLength)) // Non-blocking
  {
    switch(message[1])
    {
    case 0:
      lcd.setCursor(0, 1);
      lcd.print("O.O");
      break;
    case 1 :
      lcd.setCursor(0, 1);
      lcd.print("Hi! :)");
      break;
    }
    {
      Serial.print("Received: ");
      for (int i = 0; i < messageLength; i++)
      {
        Serial.write(message[i]);
      }
      Serial.println();
    }
  }
}


texts: I am currently working on a project that requires bluetooth module and pic. I need to get the ID or address of the connected device.Any idea how can i do it. I only know that this is done using AT commands.


texts: Reuse Makerbot SMD-2.3 Stepper Driver with Arduino

texts:
I'm building a small 2-axis CNC machine. For this purpose I want to use parts from an old Makerbot 3D printer. I've taken out the stepper motors and they're working perfectly with an Arduino and an external driver.

However I want to reuse the drivers that come with the makerbot to run the stepper motor. As you can see in the picture there's a socket for power, one for the Stepper connection and the wires coming out are what connect with the motherboard of the printer. I want to use these to connect with the Arduino instead somehow. Any idea how I should go about this?


texts:
I am trying to build a gateway for ESP-NOW (https://github.com/HarringayMakerSpace/ESP-Now) and I would like to get help with connecting two esp8266 (nodemcu + esp01) with serial link (for use as gateway).

What I done so far:

ESP01 ... NODEMCU
-----------------
3V3   ...  3v3
GND   ...  GND
CH_PD ...  3v3
TX    ...  RX
RX    ...  TX

The problem is that with this setup NodeMCU (and I think ESP01 too) is not booting (probably because TX is connected?). What's the correct way to connect two ESP8266 as described in ESP-NOW project?

NodeMCU is running this code:

https://github.com/HarringayMakerSpace/ESP-Now/tree/master/EspNowFromSerialGateway

ESP-01 is running this code:

https://github.com/HarringayMakerSpace/ESP-Now/tree/master/EspNowToSerial


texts: MPU9250 with Arduino Nano and Arduino Nano 33 BLE

texts:
I am trying to read sensor data from two MPU9250s with both one Arduino Nano and a Arduino Nano 33 BLE using SPI. As for the Arduino nano, I was successful to acquire the sensor data and output it in the serial monitor. However, unlike the old Nano device, the new Nano 33 BLE does not output any sensor readings in its serial monitor. Sometimes and very rarely though, I do receive a couple of readings (usually not more than 1-2 readings), after which no readings are received. Apparently, at least the sensor initialization seems to be always working on the 33 BLE device as my code runs past the Sensor OK messages in the setup routine.

I have been using bolderflight's MPU9250 library for talking to the sensors.

I've also tried reading only one sensor at a time, but that didn't really help, as I still didn't receive sensor readings. I didn't try I2C so far, mainly due to a lack of time.

Any ideas of what to try or why things might have gone wrong are appreciated.

Here's my code:

#include "MPU9250.h"

MPU9250 SENSOR1(SPI, 9);
MPU9250 SENSOR2(SPI, 10);
int status1, status2;

void setup() {
  // serial to display data
  Serial.begin(115200);
  while(!Serial) {}

  // start communication with IMU
  status1 = SENSOR1.begin();
  if (status1 < 0) {
    Serial.println("Sensor 1 error!");
    Serial.println(status1);
    while(1) {}
  }
  Serial.println("Sensor 1 OK");

  status2 = SENSOR2.begin();
  if (status2 < 0) {
    Serial.println("Sensor 2 error!");
    Serial.println(status2);
    while(1) {}
  }
  Serial.println("Sensor 2 OK");
}

void loop() {
  // read the sensor
  SENSOR1.readSensor();
  SENSOR2.readSensor();
  // display the data
  Serial.print("X: ");
  Serial.print(SENSOR1.getAccelX_mss(),6);
  Serial.print(" ");
  Serial.println(SENSOR2.getAccelX_mss(),6);
  Serial.print("Y: ");
  Serial.print(SENSOR1.getAccelY_mss(),6);
  Serial.print(" ");
  Serial.println(SENSOR2.getAccelY_mss(),6);
  Serial.print("Z: ");
  Serial.print(SENSOR1.getAccelZ_mss(),6);
  Serial.print(" ");
  Serial.println(SENSOR2.getAccelZ_mss(),6);
  delay(100);
}


texts:
I am getting an error on

AT+CSTT="TATA.DOCOMO.INTERNET","",""

What am I missing here?

Code

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ;
  }
  Serial.println("Goodnight moon!");
  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);
  mySerial.println("Hello, world?");
  delay(3000);
  Serial.println("AT+CGATT=1");
  delay(500);
  Serial.println("AT+CGDCONT=1,\"IP\",\"TATA.DOCOMO.INTERNET\"");
  delay(500);
  Serial.println("AT+CDNSCFG=\"4.4.4.4\",\"8.8.8.8\"");
  delay(1000);
  Serial.println("AT+CSTT=\"TATA.DOCOMO.INTERNET\",\"\",\"\"");
  delay(2000);
  Serial.println("AT+CIICR");
  delay(5000);
  Serial.println("AT+CIFSR");
  delay(500);
  Serial.println("AT+CIPSTATUS");
  delay(500);
  Serial.println("AT+CDNSORIP=1");
  delay(500);
  Serial.println("AT+CIPSTART=\"TCP\",\"www.google.com\",\"80\"");
  delay(500);
  Serial.println("AT+CIPSEND");
  delay(500);
  Serial.println("AT");
}

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

Result

AT+CGATT=1

OK
AT+CGDCONT=1,"IP","TATA.DOCOMO.INTERNET"

OK
AT+CDNSCFG="4.4.4.4","8.8.8.8"

OK
AT+CSTT="TATA.DOCOMO.INTERNET","",""

ERROR
AT+CIICR

ERROR
AT+CIFSR

ERROR
AT+CIPSTATUS

OK

STATE: IP IND
AT+CDNSORIP=1

OK
AT+CIPSTART="TCP","www.google.com","80"

ERROR
AT+CIPSEND

ERROR
AT

OK

Edit

SoftwareSerial mySerial(10, 11); // RX, TX


texts:
So I am sending a web request to a server, but for some reason the result is the number: 728484804749464932504848327975131083101114118101114583213106897116101583284117101443250483268101993250484954325049585054585249327177841310671111101161011101164584121112101583211610112011647104116109108131067111110116101110116457610111010311

Any ideas?

#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C Lcd(0x27, 16, 6);

#include <SPI.h>
#include <WiFi.h>

char ssid[] = "AESRO2-2.4G";
char password[] = "EA8TDKNFGE";

int status = WL_IDLE_STATUS;

WiFiClient client;

String serverReturn;

String page[]
{
  "Flashlight",
  "Message",
  "S.O.S"
};
void displayPage(int pageNumber)
{
  Lcd.clear();
  Lcd.print(page[pageNumber]);

  Lcd.setCursor(0,1);
  Lcd.print("[Open]");
  Lcd.setCursor(10, 1);
  Lcd.print("[Next]");
}
int currentPage = 0;
int lastPage = 1;

void setup()
{
  Serial.begin(9600);
  pinMode(6, OUTPUT);
  pinMode(8,OUTPUT);

  Lcd.begin();

  Lcd.print("BrickOS V5.0.0");
  digitalWrite(6, HIGH);
  delay(300);
  digitalWrite(6, LOW);

  delay(1000);

  if(WiFi.status() == WL_NO_SHIELD)
  {
    Lcd.clear();
    Lcd.print("No wifi shield");

    while(true);
  }

  String fv = WiFi.firmwareVersion();
  if(fv != "1.1.0")
  {
    String secline = fv += "->1.1.0";
    Lcd.clear();
    Lcd.print("Firmware update");
    Lcd.setCursor(0,1);
    Lcd.print(secline);

    while(true);
  }

  while(status != WL_CONNECTED)
  {
    Lcd.clear();
    Lcd.print("Connecting to");
    Lcd.setCursor(0, 1);
    Lcd.print("network...");

    status = WiFi.begin(ssid, password);

    delay(3000);
  }

  Lcd.clear();
  Lcd.print("Connected to:");
  Lcd.setCursor(0, 1);
  Lcd.print(ssid);
  delay(1000);
}

void loop()
{
  if(lastPage != currentPage)
  {
    if(currentPage > sizeof(page))
    {
      currentPage = 0;
    }
    displayPage(currentPage);
  }
  lastPage = currentPage;

  serverReturn = "";
  while(client.available()) {
    serverReturn += client.read();
  }
  client.stop();
  if(client.connect("www.nightfall.huskyclick.info", 80))
  {
    client.println("GET /msg.php?action=check&ID=1 HTTP/1.1");
    client.println("Host: nightfall.huskyclick.info");
    client.println();
  }
  else
  {
    Lcd.clear();
    Lcd.print("Failed to check");
    Lcd.setCursor(0, 1);
    Lcd.print("for messages");
  }

  Serial.println(serverReturn);

  if(serverReturn != "false" && serverReturn != "")
  {
    digitalWrite(8, HIGH);

    Lcd.clear();
    Lcd.print("Message received!");

    digitalWrite(6, HIGH);
    delay(500);
    digitalWrite(6, LOW);

    delay(1000);

    Lcd.clear();
    Lcd.print(serverReturn);

    delay(5000);
  }

  delay(5000);
}


texts: How to properly process large arithmetic

texts:
just a question that requires a simple answer. How do I process a large number of arithmetic steps in arduino efficiently and precisely?

For example I have this code function setup:

void calc() {
  batterymoment = input*batterymass;
  totalmoment = 149650+batterymoment;
  buoyancymoment = buoyancymass*centrebuoyancy;
  wheelmoment = totalmoment - buoyancymoment;
  wheelweight = totalmass - buoyancymass;
  cgwheels = wheelmoment/wheelweight;
  maindistance = mainarm - wheelweight;
  nosedistance = wheelweight - nosearm;
  mainmass = (((wheelweight)*(1-((maindistance)/(maindistance+nosedistance))))/2);
  nosemass = (((wheelweight)*(1-((nosedistance)/(nosedistance+maindistance))))/2);
  mainmoment = mainmass*mainarm;
  nosemoment = nosemass*nosearm;
  netmoment = buoyancymoment+mainmoment+nosemoment;
  netcg = netmoment/totalmass;
  staticmargin = adc - netcg;
  answer = staticmargin/meanadc;

}

Now I've properly setup up data types for all of these variables and they are a combination of float, int and long. I don't think it's a problem with the data type. What I'm getting when I print final answer in the serial is the same number regardless the input the user enters.

I'm guessing I need to format the code in such a way that it performs each line step by step and verifies the answer before proceeding to the next arithmetic line. If so would I need a function for each arithmetic step? Or is there a simpler way to process this that I'm missing.

Any guidance is appreciated. Thanks.

Here is the code in its entirety:

unsigned long batterymoment,num1,num2,input,totalmoment;
double buoyancymoment,wheelmoment,cgwheels,mainmass,nosemass,maindistance,nosedistance;
double mainmoment,nosemoment,netmoment,netcg,staticmargin,answer;
double centrebuoyancy = 14.164;
double mainarm = 14.3;
double adc = 11.4;
double meanadc = 22.65;
double nosearm = 1.8;
int totalmass = 12404;
int batterymass = 720;
int buoyancymass = 4401;
int batteryposition,wheelweight;
boolean mySwitch = false;

void calc() {
  batterymoment = input*batterymass;
  totalmoment = 149650+batterymoment;
  buoyancymoment = buoyancymass*centrebuoyancy;
  wheelmoment = totalmoment - buoyancymoment;
  wheelweight = totalmass - buoyancymass;
  cgwheels = wheelmoment/wheelweight;
  maindistance = mainarm - wheelweight;
  nosedistance = wheelweight - nosearm;
  mainmass = (((wheelweight)*(1-((maindistance)/(maindistance+nosedistance))))/2);
  nosemass = (((wheelweight)*(1-((nosedistance)/(nosedistance+maindistance))))/2);
  mainmoment = mainmass*mainarm;
  nosemoment = nosemass*nosearm;
  netmoment = buoyancymoment+mainmoment+nosemoment;
  netcg = netmoment/totalmass;
  staticmargin = adc - netcg;
  answer = staticmargin/meanadc;
 }

void setup() {
  Serial.begin(9600);
  num1=0;
  num2=0;
  Serial.println("Enter battery position");
 }

void loop() {
  while (Serial.available()){
    batteryposition = Serial.read();
    if(batteryposition>47 && batteryposition<58){
      if(!mySwitch){
         num1=(num1*10)+(batteryposition-48);
      }else{
         num2=(num2*10)+(batteryposition-48);
        }
       }

if(batteryposition==61){
  input=num1+num2;
  calc();
  Serial.print("Static margin is: ");
  Serial.println(answer);
  num1=0;
  num1=0;
  mySwitch=false;
  }
 }
}

So depending on the user input, the calculations will change the final output answer. For example if a 5 should be entered the output should be -4.22 based on my calculations in excel.


texts: Possibility of installing custom firmware from Arduino Uno R3?

texts: I've been messing around with installing keyboard firmware onto my Arduino UNO R3 (I used this tutorial) and had an interesting idea: would it be possible to have this install custom firmware, automatically? If so, how would it be done via a DFU programmer?


texts:
I have established a Soft Access point with one of my ESP8266 and a client with another. Now, I'm trying to connect that AP to my home router to be able to access internet and serve some data to clients. However, The httpcode always return -1 error. Is it even possible to do that or there is something wrong with my code.

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>

const char* ssid = "homerouter";
const char* password = "homepass";
String serverName = "http://payond.net/ard/test.php";

WiFiServer server(80);
IPAddress IP(192,168,4,15);
IPAddress mask = (255, 255, 255, 0);

char APssid[] = "Soft AP";                // SSID of your home WiFi
char APpass[] = "11112222";              // password of your home WiFi
//char response[] = "Hi Client. I'm Here\n";              // password of your home WiFi
int ledPin = D3;
String response;

void setup() {
  Serial.begin(115200);
  WiFi.mode(WIFI_AP);
  WiFi.softAP(APssid, APpass);
  WiFi.softAPConfig(IP, IP, mask);
  server.begin();
  Serial.println();
  Serial.println("Soft_AP started.");
  Serial.print("IP: ");     Serial.println(WiFi.softAPIP());
  Serial.print("MAC:");     Serial.println(WiFi.softAPmacAddress());

   WiFi.begin(ssid, password);
  Serial.println("Connecting to Internet");
  while(WiFi.status() != WL_CONNECTED) {    delay(500);    Serial.print(".");  }
  Serial.println("");  Serial.print("Connected to WiFi network with IP Address: ");  Serial.println(WiFi.localIP());
  Serial.println("Reading Every Second.");

}

void loop() {
  WiFiClient client = server.available();
  if (client && client.connected()) {
// Retreivieng Data from WebServer
    if(WiFi.status()== WL_CONNECTED){
      HTTPClient http;

      String serverPath = serverName + "?mobile=hi";

      // Your Domain name with URL path or IP address with path
      http.begin(serverPath.c_str());

      // Send HTTP GET request
      int httpResponseCode = http.GET();

      if (httpResponseCode>0) {
        Serial.print("HTTP Response code: ");        Serial.println(httpResponseCode);        String payload = http.getString();
            StaticJsonDocument<2000> doc;             DeserializationError error = deserializeJson(doc, payload);
            if (error) {              Serial.print(F("deserializeJson() failed: "));              Serial.println(error.c_str());              return;            }

            String response = doc["status"];

              // Communication with Clients
                  String request = client.readStringUntil('\n');
                  Serial.print("Recieved: ");
                  Serial.println(request);
                  client.print(response);
                  Serial.print("Sent: ");
                  Serial.println(response);
                  client.stop();
      }
      else {        Serial.print("Error code: ");        Serial.println(httpResponseCode);      }
      http.end();
    }

  }
}

Here is the monitor output
Connecting to Internet
...........
Connected to WiFi network with IP Address: 192.168.100.104
Reading Every Second.
Error code: -1
Error code: -1
Error code: -1
Error code: -1
Error code: -1
Error code: -1


texts:
Are there any oxygen sensors that measure up to 50%?.

As I understand, there are sensors that measure only in range 0-30%.

Is it possible to increase the threshold of sensitivity of the sensor?


texts:
I am trying to run a clock off of an arduino following this site: http://www.cibomahto.com/2008/03/controlling-a-clock-with-an-arduino/comment-page-1/ and I tried to combine it with this to get it to run accurately. https://contractorwolf.com/arduino-pwm-interrupt-clock/

For the project that I want to do I need to slow down the minute hand by 23.9345 (So that it will run on sidereal time)

Now the bare code of the first link with some mods works perfectly, but the delay does not seem to be accurate:

    const int a1  =  8;     //use digital I/O pin 8
    const int a2  =  9;
    const int tick1 = 1000;
    const int tick2 = 50;

    void setup()
    {
    pinMode(a1,OUTPUT);   //set pin 8 to be an output output
    pinMode(a2,OUTPUT);   //set pin 9 to be an output output
    }

    void loop()
    {
       delay(tick1);          //delay 1000 milliseconds
       digitalWrite(a1,HIGH);   //set pin 8 HIGH, turning on LED
       delay(tick2);          //delay 1000 milliseconds
       digitalWrite(a1,LOW);    //set pin 8 LOW, turning off LED
       delay(tick1);          //delay 1000 milliseconds
       digitalWrite(a2,HIGH);   //set pin 9 HIGH, turning on LED
       delay(tick2);          //delay 1000 milliseconds
       digitalWrite(a2,LOW);    //set pin 9 LOW, turning off LED
    }

For this reason I have tried to merge it with the 1 wire clock project and got

const int a1  =  8;     //use digital I/O pin 8
const int a2  =  9;
const int tick1 = 1000;
const int tick2 = 50;

int cyclesPerSecond = 974;

//pins
int clockInterrupt = 0; //interrupt 0 is pin 2 on UNO
int pwmOut = 6; //pin 6

//timekeeping
int seconds = 0;
int masterClock = 0;//number of square waves

void setup()
{
attachInterrupt(clockInterrupt, clockCounter, RISING);
pinMode(a1,OUTPUT);   //set pin 8 to be an output output
pinMode(a2,OUTPUT);   //set pin 8 to be an output output

Serial.println(pwmOut);
analogWrite(pwmOut, 127); // this starts our PWM 'clock' with a 50% duty cycle//digital pin 10 for analogWrite pwm out
}

void clockCounter() // called by interrupt 0 (pin 2 on the UNO) receiving a rising clock edge PWM
{
masterClock ++; // with each clock rise add 1 to masterclock count
if(masterClock >= cyclesPerSecond*23.9345) // 974hz on pin 6, may be 490Hz if you use pin 9 or 10
{
seconds ++; // after one cycle add 1 second
masterClock = 0; //reset clock counter
}
}

void loop()
{
  if (seconds == 1){
   digitalWrite(a1,HIGH);   //set pin 8 HIGH, turning on LED
   delay(tick1);          //delay 1000 milliseconds
   digitalWrite(a1,LOW);    //set pin 8 LOW, turning off LED
   else if(seconds == 2)
   seconds = 0;
   digitalWrite(a2,HIGH);   //set pin 9 HIGH, turning on LED
   delay(tick1);          //delay 1000 milliseconds
   digitalWrite(a2,LOW);    //set pin 9 LOW, turning off LED
  }
}

However this does not seem to move the second hand properly, so the clock does tick but not strong enough to actually work. Is this a hardware thing or a processor thing? I have no idea why this would not work while the other code does.


texts: Programing AVR 32u4 via ISP with other ISP device connected

texts:
I have a custom PCB with an Atmega 32u4 chip.  I program the chip with AVRDUDE via ISP after it is has been mounted onto the PCB. All is well.

I now want to add wireless capability via the NRF24L01.  The NRF communicates with the 32u4 via ISP.  Can I still program the 32u4 on the PCB after the NRF has been mounted or will there be a problem since they are both connected to the ISP pins?


texts:
I would need a quick help if possible because I have a project with the deadline tomorrow night.
On my Uno (atmega328p in fact), I need to communicate with a SPI flash to transfer music and then, take this music (part by part) to play with the PCM library.
But, both libraries are using pin 11 (MOSI and speakPin) to work.

That's why I tried to change the source code in PCM.c https://github.com/damellis/PCM/blob/master/PCM.c, I just changed the timer 2 in timer 0.
That works but only for one song. With the timer 2 you can use several times the startPlayback() function but with the timer 0 it will work with only song.... I guess it's because timer 2 is asynchronous but not the timer 0.

I found this website : http://www.renar.net/?p=73&lang=en, that's why I hope it's possible with a synchronous timer and several song.

I hope you'll have some clues for me !

Here below my new code in PCM.c :

int speakerPin = 6;
volatile unsigned char *sounddata_data;
int sounddata_length=0;
volatile uint16_t sample;
byte lastSample;
volatile boolean counterReady;

// This is called at 8000 Hz to load the next sample.
ISR(TIMER1_COMPA_vect) {
if (sample >= sounddata_length) {
   if (sample == sounddata_length + lastSample) {
    stopPlayback();
    counterReady = true;
   }
   else {
    // Ramp down to zero to reduce the click at the end of playback.
    OCR0A = sounddata_length + lastSample - sample;
   }
 }
 else {
    OCR0A = pgm_read_byte(&sounddata_data[sample]);
 }

 ++sample;
}

void startPlayback(unsigned char *data, int length)
{
   sounddata_data = data;
   sounddata_length = length;

   pinMode(speakerPin, OUTPUT);

   // Set up Timer 2 to do pulse width modulation on the speaker
   // pin.

  // Use internal clock (datasheet p.160)
  ASSR &= ~(_BV(EXCLK) | _BV(AS2));

  // Set fast PWM mode  (p.157)
   TCCR0A |= _BV(WGM01) | _BV(WGM00);
   TCCR0B &= ~_BV(WGM02);

   // Do non-inverting PWM on pin OC2A (p.155)
   // On the Arduino this is pin 11.
   TCCR0A = (TCCR0A | _BV(COM0A1)) & ~_BV(COM0A0);
   TCCR0A &= ~(_BV(COM0B1) | _BV(COM0B0));

   // No prescaler (p.158)
   TCCR0B = (TCCR0B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

   // Set initial pulse width to the first sample.
   OCR0A = pgm_read_byte(&sounddata_data[0]);

   // Set up Timer 1 to send a sample every interrupt.

   cli();

   // Set CTC mode (Clear Timer on Compare Match) (p.133)
   // Have to set OCR1A *after*, otherwise it gets reset to 0!
   TCCR1B = (TCCR1B & ~_BV(WGM13)) | _BV(WGM12);
   TCCR1A = TCCR1A & ~(_BV(WGM11) | _BV(WGM10));

   // No prescaler (p.134)
   TCCR1B = (TCCR1B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

   // Set the compare register (OCR1A).
   // OCR1A is a 16-bit register, so we have to do this with
   // interrupts disabled to be safe.
   OCR1A = F_CPU / SAMPLE_RATE;    // 16e6 / 8000 = 2000

  // Enable interrupt when TCNT1 == OCR1A (p.136)
  TIMSK1 |= _BV(OCIE1A);

   lastSample = pgm_read_byte(&sounddata_data[sounddata_length-1]);
   sample = 0;
   sei();
}

void stopPlayback()
{
    // Disable playback per-sample interrupt.
    TIMSK1 &= ~_BV(OCIE1A);

   // Disable the per-sample timer completely.
   TCCR1B &= ~_BV(CS10);

   // Disable the PWM timer.
   TCCR0B &= ~_BV(CS10);

   digitalWrite(speakerPin, LOW);
}


texts:
I’m constructing an arduino based sytem that uses a SD card and I’m looking for a way to safely remove the card from the system during operation. One way would probably be to turn of the arduino before removal of the SD card, but that is not acceptable in this context.

The library I’m using:
https://www.arduino.cc/en/Reference/SD

Is it possible to safely remove the SD card during operation? If no, how can I minimize the risk of damage to the SD card while inserting and removing it?


texts: I just uploaded a sketch of a song to my Arduino and it works well.  Could I just take the chip out and hook up speakers to it and a power source to play the song? and just get another chip and put it in the Arduino.


texts:
I'm trying to set up SPI in order to interact with a CMOS flash, the MX25L6405DMI-12G to be exact. As a test I'm trying to read the identifier (RDID) which should return 3 fixed bytes.
Currently the chip seems to respond to my request but the first bytes is 0xC3 instead of 0xC2 and the rest of the bytes are all 0xFF.
Now I haven't got a clue what's going on as my understanding of electronics is still limited.
The sketch:
#include <SPI.h>

void setup()
{
  Serial.begin(9600);
  SPI.begin();
  SPI.beginTransaction(SPISettings(SPI_CLOCK_DIV8, MSBFIRST, SPI_MODE3));
  digitalWrite(10, LOW);
  SPI.transfer(0x9F); // RDID
  Serial.println(SPI.transfer(0));
}

void loop()
{
  Serial.println(SPI.transfer(0));
  Serial.println(SPI.transfer(0));
  Serial.println(SPI.transfer(0));
  delay(1000);
}

My attempt at drawing the circuit, I hope it's clear enough. The level converter is the SparkFun bi-directional LLC which should be able to handle SPI at lower frequencies although not optimal (according to reviews).

Of course I attempted various things like adding delays (10ms) between the transactions to give the CMOS time to respond (or isn't this a thing? Again, my knowledge is limited.) or trying different clock frequencies but that doesn't seem to make any difference in output. I've read the datasheet multiple times and see no obvious thing I'm missing but I don't understand most of it. What am I doing wrong here?
Edit:
I also stumbled upon the SPIMemory library which seems to be able to talk to the MX25L4005 chip which seems similar to the one I have. I've had a peekaboo at the source and attempted to replicate it. They also fetch the manufacturer/device ID's but use a different command. I've annotated my code with the relevant description from the datasheet for convenience.
void setup()
{
  Serial.begin(9600);
  SPI.begin();
  Serial.println("Beginning transfer");
  SPI.beginTransaction(SPISettings(SPI_CLOCK_DIV8, MSBFIRST, SPI_MODE0));

  // The instruction is initiatedby driving the CS# pin low and shift
  // the instruction code "90h" followed by two dummy bytes and one bytes address (A7~A0).
  digitalWrite(10, LOW);
  SPI.transfer(0x90);
  Serial.println(SPI.transfer('R'));
  Serial.println(SPI.transfer('R'));
  Serial.println(SPI.transfer(0));
  // After which, the Manufacturer ID for MXIC (C2h) and the Device ID are shifted out
  // on the falling edge of SCLK with mostsignificant bit (MSB) first as shown in figure 25.
  // The Device ID values are listed in Table of ID Definitions on page 16.
  // If the one-byte address is initially set to 01h, then the device ID will be read first
  // and then followed by the Manufacturer ID.The Manufacturer and Device IDs can be read
  // continuously, alternating from one to the other.
  Serial.println(SPI.transfer('R')); // 195 = C3
  Serial.println(SPI.transfer('R')); // 31 = 1F
  // The instruction is completedby driving CS# high.
  digitalWrite(10, HIGH);
}

I now receive two values (as expected) but the values are still off. The manufacturer ID is still returned as C3 and the device ID is 1F while that should be 0x16 as seen in the table from the datasheet below.


texts: Can't store temperature in variable ( for further processing)

texts:
I am trying to store temperature data in a variable, so that I can use it for making a JSON object, but the problem is, that when I try to store the temperature in a variable, it prints out the wrong value. I'm using a DHT11 temperature/humidity sensor and a library for calculating the temperature.

Serial.print("Temperature (°C): ");
Serial.println((float)DHT11.temperature, DEC);
int temp1 = ((float)DHT11.temperature, DEC);
Serial.println(temp1);

These 4 lines is printing out this:

Temperature (Â°C): 23.0000000000
10

The first one is correct, but the second line should also be saying "23".
I have tried only loading the data in once with the library, as in outcommenting one line, but that does not work.
It's like I have some syntax wrong, but I can't figure out what.


texts:
What is the best way to convert between date, hours, min, seconds to Unix timestamp in milliseconds in Arduino? I need to have this conversion, since I'm using RTC (date, hours, min, secs etc) and communicating Unix timestamp over BLE

I found some snippet of codes online, but have not tested it extensively yet.

  byte second = epoch%60; epoch /= 60;
  byte minute = epoch%60; epoch /= 60;
  byte hour   = epoch%24; epoch /= 24;

  unsigned int years = epoch/(365*4+1)*4; epoch %= 365*4+1;
  unsigned int year;
  for (year=3; year>0; year--)
  {
      if (epoch >= days[year][0])
          break;
  }

  unsigned int month;
  for (month=11; month>0; month--)
  {
      if (epoch >= days[year][month])
          break;
  }

  year  = years+year;
  month = month+1;
  unsigned int day   = epoch - days[year][month]+1;

  unsigned int weekday  = (dayOfMonth += month < 3 ? year-- : year - 2, 23*month/9 + dayOfMonth + 4 + year/4- year/100 + year/400)%7;

And to convert to Unix timestamp:

unsigned long epoch = (((year/4*(365*4+1)+days[year%4][month]+dayOfMonth)*24+hour)*60+minute)*60+second;

Are there any library in Arduino that implement this? I would trade off reliability over size of the program.


texts:
I have code but I don't know how to send SMS from my Mobile
I mean what the message I can send to switch the Led?
To switch On or Off.
I use SIm900
and use this code

#include <SoftwareSerial.h>

 char inchar; // Will hold the incoming character from the GSM shield
 SoftwareSerial SIM900(7, 8);

 int led = 10;

 void setup()
 {
   Serial.begin(19200);
   // set up the digital pins to control
   pinMode(led, OUTPUT);
   digitalWrite(led, LOW);

   // wake up the GSM shield
   SIM900.begin(19200);
   delay(20000); // give time to log on to network.
   SIM900.print("AT+CMGF=1\r"); // set SMS mode to text
   delay(100);
   SIM900.print("AT+CNMI=2,2,0,0,0\r");
   // blurt out contents of new SMS upon receipt to the GSM shield's serial out
   delay(100);
   Serial.println("Ready...");
 }

 void loop()
 {
   //If a character comes in from the cellular module...
   if(SIM900.available() >0)
   {
     inchar=SIM900.read();
     if (inchar=='#')
     {
       delay(10);

       inchar=SIM900.read();
       if (inchar=='a')
       {
         delay(10);
         inchar=SIM900.read();
         if (inchar=='0')
         {
           digitalWrite(led, LOW);
         }
         else if (inchar=='1')
         {
           digitalWrite(led, HIGH);
         }
         delay(10);
         // SIM900.println("AT+CMGD=1,4"); // delete all SMS
       }
     }
   }
 }


texts:
I've got a question concerning the Arduino library "RTClib" by Adafruit and the use of the word "static".

Here you can see an excerpt from the example provided for the pcf8523 real-time clock:

#include "RTClib.h"

RTC_PCF8523 rtc;

void setup () {

  while (!Serial) {
    delay(1);  // for Leonardo/Micro/Zero
  }

  Serial.begin(57600);
  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }

  if (! rtc.initialized()) {
    Serial.println("RTC is NOT running!");
  }
}

void loop () {
    DateTime now = rtc.now();

    Serial.print(now.year(), DEC);
    /*
    do some more stuff
    */
}

In the beginning of loop() they wrote:

DateTime now = rtc.now();

Thus, with every iteration of loop() "new" gets defined anew (on the heap?!), right?
This appears inefficient to me.

I thought about rewriting it this way:

static DateTime now;    // static declaration, executed only once
now = rtc.now();    // assignment to "now" every time loop() starts over

In this case "new" should be allocated on the stack like a global variable, right?

I want to use "static" to increase overall performance by reducing work for the processor and the heap (thereby avoiding heap fragmentation). Does this make sense or will it cause more problems than it solves? Keep in mind that I want to learn both proper programming for Arduino and proper coding in general.

Link to the library:
https://github.com/adafruit/RTClib

Thank you! :-)

EDIT: For some reason I CAN NOT declare DateTime now; in global scope or else the program won't run. Don't know why though. This is why I want to use static in the first place.


texts:
I am trying to switch the TV on using Arduino. Following is my set of code

#include <IRremote.h>

IRrecv receiver(2);
IRsend sender;
decode_results results;

long repeatitions;
long count;
unsigned int durations[100];
void (*reset)(void) = 0;

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

void loop() {
  if (Serial.available()) {
    repeatitions = Serial.parseInt();
    count = Serial.parseInt();
    for (int i =0; i < repeatitions; i++) {
      durations[i] = Serial.parseInt();
    }
    for (int i = 0; i < repeatitions; i++) {
      Serial.println("sending code");
      sender.sendRaw(durations, count, 40);
      delay(50);
    }
    reset();
  }
  if (receiver.decode(&results)) {
    Serial.println(results.value, HEX);
    Serial.print(results.rawlen - 1);
    for (int i =1; i <results.rawlen;i++) {
      unsigned int number = results.rawbuf[i] * USECPERTICK;
      Serial.print(",");
      Serial.print(number);
    }
    Serial.println("");
    receiver.resume();
  }
}

The code receiving part works fine. And it returned me following code:

A90
25,2400,600,1200,600,600,550,1200,600,600,600,1200,600,600,600,550,600,1200,600,600,600,600,550,650,600,600

But when I try to use the same code to switch the TV on after adding durations to the above returned code it doesn't work. I am entering following into the serial monitor

3,25,2400,600,1200,600,600,550,1200,600,600,600,1200,600,600,600,550,600,1200,600,600,600,600,550,650,600,600

I have attached a screenshot to show how I have installed the IR Transmitter LED.

I have two IR Transmitters. I have tried installing both in same manner 1 by 1. But unfortunately no success.

I am using IRRemote library by Shirriff https://github.com/z3t0/Arduino-IRremote


texts: How do I power my Arduino Micro directly?

texts:
I just need some confirmation, before I break something. So far I have been powering my project from USB, no I would like to power it from a battery. The official spec claims I should use a voltage anywhere from 7-12V, so I got myself a 9V block battery and would connect the positive lead to the VIN pin and the negative lead to the ground pin right next to it, based on this schematic: https://40.media.tumblr.com/cdadca4e95808b376de52a88a5468367/tumblr_mi61oww6cu1s5t695o1_1280.png
Do I need a resistor?


texts: If value in serial begin is greater than that of delay in arduino, does delay time matters?

texts: I think if the value inside Serial.begin() is greater than the value inside delay(),then delay will not take the next step as soon as the next input is there ... So , the delay() function is insignificant...no?


texts: ESPTOOL not recognizing ESP32-S2 chip for SPIFFs transfer

texts:
I have a spiff file that uploads fine using a regular esp32, but when I try on the esp32-32, with a fresh installation, I get:
esptool.py v3.0-dev
Serial port COM3
Connecting....
A fatal error occurred: This chip is ESP32-S2 not ESP32. Wrong --chip argument?
SPIFFS Upload failed!
Any ideas??
Thanks


texts: Stream esp-32 camera to RMTP server like YouTube

texts:
I am doing research for a project in which I need to play with camera streams. After multiple hit and trails and googling I am not getting even close to the solution for streaming ESP-32 Camera stream to my own RMTP server directly.

Already tried solutions:

1) I have tried re-streaming of ESP-32-cam with Raspberry pi, that works well but not something I am looking for

2) ESP-32-cam: Record and FTP transfer with time triggers (Not tried but believed that it is not a good approach).

Please note: I am not looking at the solution in which ESP-32 cam acts as stream server and browser can connect to it like : https://www.hackster.io/BnBe_Club/9-rtsp-video-streamer-using-the-esp32-cam-board-8832b4

I have already tried it and it works well but not for the usecase which involves streaming to RTMP server without restreaming.

On google, I found a similar thread : https://forum.arduino.cc/index.php?topic=634605.0
The guy with solution is not interested in sharing it.

may be some modification required in below code MAY BE
ref: https://github.com/espressif/esp32-camera

static esp_err_t stream_handler(httpd_req_t *req){
  camera_fb_t * fb = NULL;
  esp_err_t res = ESP_OK;
  size_t _jpg_buf_len = 0;
  uint8_t * _jpg_buf = NULL;
  char * part_buf[64];

  res = httpd_resp_set_type(req, _STREAM_CONTENT_TYPE);
  if(res != ESP_OK){
    return res;
  }

  while(true){
    fb = esp_camera_fb_get();
    if (!fb) {
      Serial.println("Camera capture failed");
      res = ESP_FAIL;
    } else {
      if(fb->width > 400){
        if(fb->format != PIXFORMAT_JPEG){
          bool jpeg_converted = frame2jpg(fb, 80, &_jpg_buf, &_jpg_buf_len);
          esp_camera_fb_return(fb);
          fb = NULL;
          if(!jpeg_converted){
            Serial.println("JPEG compression failed");
            res = ESP_FAIL;
          }
        } else {
          _jpg_buf_len = fb->len;
          _jpg_buf = fb->buf;
        }
      }
    }
    if(res == ESP_OK){
      size_t hlen = snprintf((char *)part_buf, 64, _STREAM_PART, _jpg_buf_len);
      res = httpd_resp_send_chunk(req, (const char *)part_buf, hlen);
    }
    if(res == ESP_OK){
      res = httpd_resp_send_chunk(req, (const char *)_jpg_buf, _jpg_buf_len);
    }
    if(res == ESP_OK){
      res = httpd_resp_send_chunk(req, _STREAM_BOUNDARY, strlen(_STREAM_BOUNDARY));
    }
    if(fb){
      esp_camera_fb_return(fb);
      fb = NULL;
      _jpg_buf = NULL;
    } else if(_jpg_buf){
      free(_jpg_buf);
      _jpg_buf = NULL;
    }
    if(res != ESP_OK){
      break;
    }
    //Serial.printf("MJPG: %uB\n",(uint32_t)(_jpg_buf_len));
  }
  return res;
}


texts: ESP8266 and DHT22 reads wrong values after restart

texts:
I put together a circuit on a breadboard with Wemos D1 Mini (ESP8266) and a DHT22 sensor. Important to say that I am using ESP Home and configuring the code using the yml format.
When it uploads the code and starts, the readings are correct, as below:
INFO Connecting to temp-test.local:6053 (192.168.1.166)
INFO Successfully connected to temp-test.local
[15:22:19][D][dht:048]: Got Temperature=29.1°C Humidity=27.0%
[15:22:19][D][sensor:092]: 'Living Room Temperature': Sending state 29.10000 °C with 1 decimals of accuracy
[15:22:19][D][sensor:092]: 'Living Room Humidity': Sending state 27.00000 % with 0 decimals of accuracy

Now, if for some reason I restart the board using the board's reset button, it starts reading weird values, as below. Sometimes it reads both humidity and temperature, sometimes just temperature.
INFO Connecting to temp-test.local:6053 (192.168.1.166)
INFO Successfully connected to temp-test.local
[15:22:58][D][dht:048]: Got Temperature=4.5°C Humidity=25.4%
[15:22:58][D][sensor:092]: 'Living Room Temperature': Sending state 4.50000 °C with 1 decimals of accuracy
[15:22:58][D][sensor:092]: 'Living Room Humidity': Sending state 25.40000 % with 0 decimals of accuracy

The reads keep being wrong even after several restarts via the board's reset button. I noticed that if I remove the USB cable and connect it again it starts reading correctly, as below.
INFO Connecting to temp-test.local:6053 (192.168.1.166)
INFO Successfully connected to temp-test.local
[15:24:20][D][dht:048]: Got Temperature=29.0°C Humidity=26.4%
[15:24:20][D][sensor:092]: 'Living Room Temperature': Sending state 29.00000 °C with 1 decimals of accuracy
[15:24:20][D][sensor:092]: 'Living Room Humidity': Sending state 26.40000 % with 0 decimals of accuracy

I don't have a big issue with this, but I am annoyed by it, since I have noticed this behavior in a NodeMCU board using similar wiring and ESP Home.
Below, a picture of the wiring.
Has anyone experienced this before or have any clues?
Edit
esphome:
  name: temp-test
  platform: ESP8266
  board: d1_mini

sensor:
  - platform: dht
    pin: D2
    temperature:
      name: "Living Room Temperature"
    humidity:
      name: "Living Room Humidity"
    update_interval: 10s

  - platform: adc
    pin: A0
    name: "Living Room Light"
    update_interval: 10s

wifi:
  ssid: "mywifinetwork"
  password: "mysupersecretpass"

  # Enable fallback hotspot (captive portal) in case wifi connection fails
  ap:
    ssid: "Temp-Test Fallback Hotspot"
    password: "xxxxxxxxxxxxx"

captive_portal:

# Enable logging
logger:

# Enable Home Assistant API
api:

ota:


texts:
I'm currently working on a Arduino project that plays audio files from SD card through a speaker.

First Arduino sends the list of all music files, and when I send it a file name, the music is played.

The project is working well but there's no GUI. Everything has to be done via serial, and now I want to add a TFT screen that will list the music files on the screen, so that whenever I touch a file name  it should be played.

I haven't bought the TFT yet, and that's because I have a little question for which I need an answer.

If I start listing the files, can I scroll up and down ? Because at some point the TFT screen will become full of text, and I don't want the text to be overwritten.

Any help would be appreciated.


texts: Arduino Uno - External Power not working properly

texts:
I am a newbie to Arduino and created my first project. The project is using a Sharp short range sensor and a 7 seg LED board (http://embedded-lab.com/blog/new-version-of-max7219-based-4-digit-serial-seven-segment-led-display/) to count objects.

Everything works fine when on USB power to my computer or if I use a 5v 1A wall adapter with a USB cable. The problem is when I use an external power adapter or use a DC power supply to the Vin. The board powers up and I measured the output voltage on the 5v pin and is measuring around 4.8v.

The Sharp sensor is connected to the A0 Analog in and I see the voltage fluctuate when an object passes, but the LED is not displaying a value when on the external power. The display is connected to GRD, 5v where DIN, CLK, and LOAD pins of the display are connected to pins 7, 6, and 5 as the instructions stated.

I tried two different Arduino boards and several different AC to DC power adapters ranging from 9v to 12v plus used a DC power supply to the Vin and same results.

The code is below and pretty simple (although I am sure there is a lot better way of doing it but this is my first project in C so go easy on me and the function for digits is from a website and not written by me).

If a picture of the project would help I can upload one.

Any ideas or thoughts?
Thanks,
Steve

#include "LedControl.h"
#include <stdio.h>
#include <math.h>

// Arduino Pin 7 to DIN, 6 to Clk, 5 to LOAD, no.of devices is 1
LedControl lc = LedControl(7, 6, 5, 1);
int sensorpin = 0;      // analog pin used to connect the sharp sensor
int val = 0;            // variable to store the values from sensor(initially zero)
int cnt = 1;

void setup()
{
    // Initialize the MAX7219 device
    lc.shutdown(0, false);   // Enable display
    lc.setIntensity(0, 10);  // Set brightness level (0 is min, 15 is max)
    lc.clearDisplay(0);     // Clear display register

}
void loop()
{

    val = analogRead(sensorpin);       // reads the value of the sharp sensor
    if (val >= 650)
    {

    //write values to LED
    if (cnt<=9)
    {
        lc.setDigit(0, 0, cnt, false); // Display 4 to Digit 1-9, " "
    }
    if (cnt >= 10 && cnt <= 99)
    {
        lc.setDigit(0, 0, getDigitFromNum(cnt,0), false); // Display 4 to Digit 1-9, " "
        lc.setDigit(0, 1, getDigitFromNum(cnt, 1), false); // Display 3 to Digit 1-9, " "
    }

    if (cnt >=100)
    {
        lc.setDigit(0, 0, getDigitFromNum(cnt, 0), false); // Display 4 to Digit 1-9, " "
        lc.setDigit(0, 1, getDigitFromNum(cnt, 1), false); // Display 3 to Digit 1-9, " "
        lc.setDigit(0, 2, getDigitFromNum(cnt, 2), false); // Display 2 to Digit 1-9, " "
    }

    delay(400);
    cnt++;

}
}

// Function: getDigitFromNum returns a digit at a given index of a integer.
// Goes from right to left with the starting index of 0.
int getDigitFromNum(int num, int digit) {
    num /= pow(10, digit);
    return num % 10;
}
// Function: getDigitFromDec returns a digit at a given index of a double.
// Goes from left to right with the starting index of 0.
int getDigitFromDec(double dec, int digit) {
    dec *= pow(10, digit);
    return (int)dec % 10;
}
// Function: getDigitFromNum returns the decimal values of a double.
double getDecimals(double dec) {
    return dec - (int)dec;
}


texts: Do I have to wire up my WS2812 LED strip in "series", if I want to address each LED individually?

texts:
Let's assume I want to make an asterisk (*) out of LED strips. I want to control each leg individually, while still being connected to only one GPIO pin. The layout I had in mind, looks like this:

Since it's an LED strip with individually addressable LEDs, I can't just supply 5V, GND, and DATA to the middle and expect it to work (I highly assume).

If I want to do this, I assume I need to keep running them in "series", basically meaning I hook up one of the strips to the Arduino, then at the end of the strip I run a long wire to the start of one of the others and then repeat. Something like this:

but only for the data wire, as I can simply power all of them in the middle. If not, how can I do this? What happens if I hook up 5 strips' DATA to a single GPIO pin on the Arduino? Are all 5 strips shared then, so each strip's first LED is also the first I would turn on?


texts: How to program the Robotdyn Mega 2560 PRO MINI?

texts:
I want to program the Robotdyn Mega 2560 PRO MINI which has no USB port.

How do I connect the pins to an FTDI?

Which setting do I have to use in the Arduino IDE?


texts: Is it possible to build a 1080p OSD webcam shield?

texts: What do I need to build a shield capable of receiving 1080p video from USB camera, timestamp each frame and send the frame to memory card?


texts:
The first challenge on the Arduino Uno manual is to make a closed circuit with a button and LED. The voltage is provided by the 5V pin (non IO), connected by wire to (+) on the bus (breadboard). The wire connects to a resistor, which makes sense since it resists current running from source. The button connects to the resistor, if pushed, the button closes the circuit and current passes through LED (making it shine) and through a wire to GND.

OK. The second challenge makes no sense. The resistors are connected not to the 5V, but the GND. WHY? Doesn't current dissipate past at ground?? As if the GND is supplying power!? It's like flipping the anode/diode! Here's the challenge: .What is the logic behind connecting the resistors to GND and WHY DOES IT SUPPLY POWER? I'm not talking about the button, which step two somewhat explains but not why, but the LEDs. Thank you thank you thank you!!

EDIT: Ok, then. I am now being told current flows negative to positive. Fine, then why resistor connected to positive? Also, I was told that GND is there to dissipate the energy flowing from positive because some of that energy was lost. Then, could you explain the circuit and whether flow is perpetual or lost at the end (wherever that is) and if it isn't perpetual in a loop, why have a resistor past the LED when the LED recieved all the volts and the electrical energy it then outputs back on the cycle is reduced by the resistor. Thanks.

Also, I'm changing my question to "Why does resistor on GND ever work on LED" to "Why have resistor at end of circuit cycle if GND dissipates final energy?".


texts: What is the pinout of the Arduino MKR motor carrier when using external power supply, not the Li-Po battery

texts:
I see there is a blue terminal connector an the tags below the PCB Vin, 5V, 3,3V and GND, but I am unsure where should I supply voltage to power up the board.
Also, in the product page it says the power can range from 6.5 to 11v, so what is those 5V and 3.3V all about?
Thanks


texts: Controlling a DC motor with an external power source

texts:
I'm trying to use an Arduino to release a single drop of water using a solenoid valve.  This article describes how to create this circuit with a Raspberry Pi using a DC powered solenoid that opens and closes very quickly and they use this for photographing water drops.  Exactly what I need, if I could only get it to work with the starter kit items first.

The design for the solenoid circuit from that site looks like:

I don't have a solenoid yet, but I've been experimenting with the cheap motor that comes with the Arduino and a 9 V battery.  I've burned out several transistors in my attempts to get this working.  My schematic looks like:

Relays won't work.  They are too slow.  Also, I need to use an external battery.  I can't use the power from the Arduino because I will eventually be moving up to a 12 V battery and the Arduino won't be able to handle that.


texts: I'm looking for a way to serially communicate with a multi mesh Arduino slave network

texts:
I have one PC running Visual Studio and a program that will be sending commands to Arduinos via serial COM Ports. So, in 11 Nano MCUs, I will have motor drivers L293D/L298N ICs, while in other Nanos I will have sensors.

What I would like to do is have a program in Visual Studio which sends commands via serial to actuate motors to each and every MCU on board. This is a robotic application and everything I mentioned above will be enclosed within the Humanoid.

Here are some examples of what I'm thinking of doing:

char data = Serial.read();
if (data == 'A')
{
  digitalWrite(13, HIGH);
}

Or something like this:

servodata = Serial.read();
if (servodata == '1') // Single Quote! This is a character.
{
  SERVO.write(pos);
}

As you can see, Arduinos will have something like this running and waiting for Visual Studio to send commands via serial to one or multiple MCUs simultaneously. I'm thinking 30 char dividing/spiting that number across each Rx Arduino.


texts:
I'm doing a research for RGB LED chips that MCU can control with one pin. I found this LED chip and it seems controlling LEDs is not as I've tought. I understand hardware part, software side is a problem.
In chip's datasheet, on page 6, you can find chapter four Data Transfer Format.
My questions are: Why D2 has only second 24 bit, third 24 bit while D3 has only third 24 bit and why D4 has no bits? What should I do when I'm done with "updating LEDs"?
I thought controlling LEDs can be done like this:

Lets say I have five LEDs to control. Every LED has Red, Green and Blue and every color is 8-bit. Five times three is 15 bytes array.
First three bytes in array are for last LED chip. While sending the data, highest bit(bit 7) will go first.
After first three bytes, MCU will stop for X microseconds. After delay, new three bytes will push old three bytes to second LED chip.
After MCU is done with sending data, it will leave data pin low.

Thanks!


texts:
For an battery driven application I want to measure the Vcc (using an Atmega 32u4). That is my code:

int readBandGap() {
  ADMUX = (B01 << REFS0)    // VCC
        | (0 << ADLAR)      // right-adjusted result
        | (B011110 << MUX0) // 1.1V
        ;
  // switch off any ADC conversion
  ADCSRA &= ~(1 << ADEN);
  // enable ADC
  ADCSRA |= 1 << ADEN;
  // start ADC
  ADCSRA |= 1 << ADSC;
  // wait until finished
  while (bit_is_set(ADCSRA, ADSC));
  // first read low, then high!
  uint8_t low = ADCL;
  uint8_t high = ADCH;
  // switch off any ADC conversion
  ADCSRA &= ~(1 << ADEN);
  return (high << 8) | low;
}

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

void loop() {
  int value = readBandGap();
  float vcc = 1.1 * 1023 / value;
  Serial.print(value);
  Serial.print("  ");
  Serial.println(vcc);

  delay(1000);
}

My Olimexino 32u4 board has the ability to switch the voltage between 5V and 3.3V. There are two strange things:

the first measurement is always significantly different than the later measurements
with 5V I'm getting 450, followed by ~367; with 3.3V I'm getting 422, followed by ~395. I would have expected a higher Vcc resulting in a lower measured value (bandgap should be measured compared to Vcc).

Any ideas what is wrong with my approach?


texts: Wemos Mini & Pro Micro Serial connection

texts:
While using a 3.3v Pro Mini & Wemos mini to communicate via Serial was successful, when tried with a 5v Pro Micro it fails.
To overcome different logic level I used a 10K + 20K resistors to lower Pro-Micro's 5v to 3.3v successfully to Tx and Rx pins. Also since they are on the same PCB, GND pins are connected and RAW to 5V at wemos mini  is also connected. At the moment, it is powered up using MCU's USB input ( tried to connect to Pro-Micro only, Wemos Only, and both ).

What might be the problem ?


texts: Parallel Chaining of APA102 LED matrices

texts:
I have four APA102 LED matrices (those flexible ones) and I want to connect them together to make a display for showing images. Now my problem is this:

Consider the coordinate system with four quadrants. I put one matrix in each of the quadrant and my target is to have a one single display as mentioned above. I connect like this: The input of matrix 1 is connected to Arduino, the output of matrix 1 to input of matrix 2, output of matrix 2 to input of matrix 3 (or can be input of 4 also ) and then finally output of 3 (or output of 4th matrix) is connected to input of 4th matrix (or input of 3rd matrix accordingly).

The problem with this is that although this might seem a big display from a distance with 4 matrices working in sync but actually its 4 matrices daisy chained and split into 2 rows. This would split my image if I were to display.

Question: Is it possible to parallel chain these APA102 matrices and thereby form one continuous display which can be controlled by FASTLED library?? I might be somehow able to address an individual LED in this type of weird pattern, but while displaying images, I am lost. Can't figure out how to do that? Realised that I need to have parallel chaining.....which I have no idea of.

Any help, guidance would be great!

Thanks


texts:
I'm trying to make a robot dance on several songs using Arduino.
I need to understand how to get the rhythm from the songs, something like detecting the beats, calculating the bpm..
I'm not expert but I read that probably I'll have to use some filters, is that right? or I can use a simple mic and opamp? do I have to analayze some frequencies?
I hope someone has some ideas and can explaing me how to do such a thing, thanks!! :)


texts: How to control an 12V 2A Car lamp using relay or MOSFET in Arduino

texts:
I am working with the project controlling an 25W 12V Car lamp. I have a 12V car battery. I want to control it with the Arduino using a relay or MOSFET.

Any suggestion for my project would be appreciated.


texts: LCD Pin Numbering vs I2C Controller Pin Numbering vs Sketch

texts:
I've been playing with an Arduino Uno, trying to get a 16x2 LCD screen to work with an I2C controller. I've got this LCD screen and this controller. And I've been trying to get the sketch below to work.

#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27,2,1,0,4,5,6,7,3,POSITIVE);//, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
void setup()
{
    lcd.begin(16,2);
    lcd.backlight();
    lcd.setCursor(0, 0);
    lcd.print("Hello world!");
    lcd.setCursor(0, 1);
    lcd.print("Row number: ");
    lcd.setCursor(12, 1);
    lcd.print("2");
}
void loop()
{

}

I've used an address scanner to verify that the address is correct (39 [0x27]), but it still won't display anything. It lights up, and I've tried adjusting the contrast, but it just won't display any characters.

I'm wondering if the definition of which pins are which is correct, but I can't seem to find anything detailing how the numbers used in the sketch correlate to the pins on the controller, which then correlate to the pins on the LCD screen. If any body can give me some insight I'd appreciate it.


texts: Extracting data from Arduino MultiWii Flight Controller

texts: I am new to the world of Arduinos but have a new project going with a MultiWii Flight controller. With the MultiWii comes a software for showing all data that is measured from the sensors (acceleration, velocity, roll, pitch, etc) which is nice but I would like to have/extract this data (call raw data or something) from all sensors (i.e. the data plotting everything, in numbers). Maybe it is the simplest thing to do, and I guess I have to set up some serial connection between the controller and tell it to send this data somehow but I do not know where to start so any guidance and help is appreciated.


texts: Trouble while using Arduino DUE as programmer

texts:
I'm trying to use the arduino DUE board as a  AVR Programmer. My target device is atmega328p. After uploading the ArduinoISP into the DUE Board. I've tried to let a pin toggle using the following code:

#define F_CPU 10000000
#include <avr/io.h>
#include <util/delay.h>

int main (){
    DDRD |= (1<< PD7);
    for(;;){
        PORTD ^= (1<< PD7);
        _delay_ms(1000);
    }
    return 0;
}

I want to use the internal oscillator and based this example  I've adjust the makefile:

DEVICE     = atmega328p
CLOCK      = 8000000
PROGRAMMER = -c arduino -P COM10 -b 19200
OBJECTS    = main.o
FUSES      = -U lfuse:w:0x62:m -U hfuse:w:0xd9:m -U efuse:w:0xff:m

the problem that I have is that when run :

make flash

I get the following :

and yes the port COM10 is definitely correct.

does anyone have a suggestion how to solve this ?

thanks in advance !


texts: How do I use the Arduino Mega as a 16-bit SPI slave?

texts:
I have to interface an Arduino Mega as a slave with a SPI master running at 1 MHz SCK. The master will send and ask for two bytes in a single transaction. I tried using the following code for the Mega. Its intended functionality is to store the master's sent data in acc and return local data ret, which is simply an integer to be incremented every transaction.

However, while the master data is stored in acc (verified through serial output), the data returned to the master is not the value in ret. Instead, the first response byte is correct (MSB of ret) and the second response byte is just the first byte received by the Mega, which was the value already present in SPDR.

How do I send the second byte of ret as the second byte of the response? What am I doing wrong?

// SPI Slave

#include <SPI.h>

// return to master
volatile unsigned int ret;

// accept from master
volatile unsigned int acc;

// MSB/LSB indicator
volatile byte SB;

void setup(void)
{

  ret = 0;
  SB = 0;

  pinMode(MISO, OUTPUT);

  // turn on SPI in slave mode
  SPCR |= _BV(SPE);

  // turn on interrupts
  SPCR |= _BV(SPIE);

  // set CPOL, CPHA modes
  // byte dataMode = 0;
  // SPCR = (SPCR & ~SPI_MODE_MASK) | dataMode;

}

// SPI interrupt routine
ISR(SPI_STC_vect)
{

  if(SB == 0) {
    acc = SPDR << 8;
    SPDR = ret;
    ret++;
  }
  else {
    acc += SPDR;
    SPDR = ret >> 8;
  }
  SB = (SB + 1) & 0x01;

}

void loop(void)
{
  // interrupt processing only
}

Edit Changed SCK from 16 MHz to 1 MHz


texts:
not sure if this is the right place to post, but basically I am trying to make a Love-O-Meter, similar to the Arduino project example.

However, my method of determining the score is different. Instead of basing it on temperature, I am basing it on capacitance instead (Let me know if you think there are better ways to determine the score. I have tried body resistance, but it is too insensitive and I have also tried making it random but it doesnt make sense and its not as fun)

Another difference is that I want to make it only measure when both people place 1 of their hands on the foil and their other hand holding onto each other. However, the issue I have is Im not sure how to start measuring when the condition I mention happens.

Link to code: https://pastebin.com/bWyiDtfB (Using reference from here: https://playground.arduino.cc/Main/CapacitiveSensor?from=Main.CapSense) (The code starts measuring the capacitance when it detects that both foils have their hands placed on it, i.e.  when it detects that the capacitance exceeds a certain threshold, 200 for my case. It will then measure 100 samples and the score will be from the median of the 100 samples)
Link to fritzing diagram: https://imgur.com/YFmgizr (Ignore the black wire from A5)


texts: How to convert kitchen timer code into a countdown

texts:
I found this code for a kitchen timer, it was the closest thing to a countdown. The code is here:

#include <LiquidCrystal.h>

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

signed short minutes, secondes;
char timeline[16];

void setup() {

  lcd.begin(16, 2);
  lcd.print("Chronometre :");

}

void loop() {

  lcd.setCursor(0, 1);
  sprintf(timeline,"%0.2d mins %0.2d secs", minutes, secondes);
  lcd.print(timeline);

  delay(1000);
  secondes++;

  if (secondes == 60)
  {
    secondes = 0;
    minutes ++;
  }

}

How do I convert it properly for it to countdown from 1 minute and 30 seconds?


texts: How to troubleshoot the Arduino Mini and Arduino usb2serial?

texts:
I am trying to get an Arduino Mini (R5, mega 328p) working.

Just connecting it to power has following effect: the on-board LED lights up. It's the power-on-led, I presume.

Since other Arduino devices often come with the blink-example pre-flashed I hooked up a LED to pin 13 - result: no blinking.

Curiously, connecting the LED to pin 12: blinking

Does the Mini come pre-flashed with a blink 'sketch' that blinks pin 12 instead of 13?

To test uploading I've connected it to an Arduino USB2Serial module. The module is labeled with 'made in Italy' and has printed 'USB2SERIAL LIGHT' on it where the LIGHT is overwritten with a blue marker.

I've connected it like described in the arduino mini guide.

In the IDE I've selected the board 'Arduino Mini' and the '328' CPU.

Unfortunately, uploading fails with:

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00

The external reset is connected like in the guide. But I also tried to manually press the reset button (immediately before the upload, or long press and release after upload button is clicked). Still, the same error.

When the manual reset is pressed the pin-12-blinking stops for a while (perhaps the bootloader is then executed) but then starts again.

The Arduino2serial has 3 LEDs. The ON-LED lights up when connected to the USB. When hitting the upload button in the IDE, the RX-LED flashed shortly one time after a while. That's it.

Thus my question: How to I troubleshoot this? Can I test the arduino usb2serial on its own? What's up with the pin-12 blinking of the mini?

In case this matters, I am on Fedora Linux, uploading to other Arduino devices (Uno, Micro) works as expected.

update usb2serial: I just hooked up the Arduino usb2serial and connected the TX/RX pins via a jumper cable - a minicom session then results in text being displayed and the rapid flashing of the RX/TX LEDs. Disconnecting RX/TX again shows no display of any text inside minicom, and no flashing of the RX/TX LEDs.

I used following command line:

$ minicom -D /dev/ttyACM0 -b 115200

Thus, the usb2serial module seems to work.

update: I've checked all the jumper cables and there was a faulty one. With that replaced flashing works. After hitting the reset-button. The 'ext reset' pin is connected but the remote-reset does seem to work. Anyways, hitting the reset-button is easy-enough, for now.

final update: The root cause for remote-reset (a.k.a. auto reset) that the capacity of the used capacitor was too small. After exchanging it with a 100 nF one (as specified in the guide) the remote-reset works as expected. That means just hitting the upload button in the IDE automatically resets the device and the sketch is uploaded.