texts: Input from serial monitor to control stepper direction coding problem

texts:
I am attempting to create a simple code that will home the motor then wait for input for direction.  I have the homing function working, however the loop that reads the data from the serial monitor and returns it to the program is acting really buggy.  If I enter a 1 the stepper will rotate one turn in the CCW direction, hit the home mark then reverse and go CW.  If I enter a 0 the stepper will make one turn in the CW direction then repeat that move.  I added a bit of feedback so I could see what my direction variable is doing, it will hold a "1", make the move, rehome and show a "0".  I know the problem is in the loop, but for the life of me I can't seem to figure it out.  I am new to coding, so for the love of god, go easy on me!  I have added my full code so someone a little higher up in the coding world will see what I am doing.  This is just some code so I can try and learn a little something and make some strange stuff in the future.  Gotta start somewhere.  If this question is better asked on a different thread, please direct me to it.
    // Connections
#define HALL_SENSOR      3
#define DIR      10
#define STEP      11

void homefunction() {

  while (digitalRead(HALL_SENSOR) == 1) {

    digitalWrite(DIR, LOW);
    digitalWrite(STEP, HIGH);
    delayMicroseconds(4000);
    digitalWrite(STEP, LOW);
    delayMicroseconds(4000);
  }

}

void setup() {

  // Setup the stepper controller pins as Outputs
  pinMode(DIR, OUTPUT);
  pinMode(STEP, OUTPUT);

  // Setup the Hall Effect switch as an Input
  pinMode(HALL_SENSOR, INPUT_PULLUP);

  // Home the motor
  homefunction();

  // Sets up serial monitor
  Serial.begin(9600);

}

void loop()

  {int Direction; //Use to get the direction from the serial monitor
    Serial.println("What Direction would you like the motor to spin?"); //Input data
    while (Serial.available() == 0) //Wait for data
    Serial.read();
       Direction = Serial.parseInt();

 {
  // Read motor direction
  digitalWrite(DIR, Direction);
  Serial.println(Direction);

  // Spin motor
  for(int x = 0; x < 200; x++)
  {
    // while (Direction==0) //Added to hold value
    digitalWrite(STEP, HIGH);
    delayMicroseconds(4000);
    digitalWrite(STEP, LOW);
    delayMicroseconds(4000);
    //Serial.println(x);
  }}}


texts: Pass Color to a function without using a specific Adafruit_NeoPixel

texts:
I'm initializing my strips as an array:
// Declare NeoPixel strip array:
Adafruit_NeoPixel strip[] = {
  Adafruit_NeoPixel(LED_COUNT[0], LED_PIN[0], NEO_RGBW + NEO_KHZ800),
  Adafruit_NeoPixel(LED_COUNT[1], LED_PIN[1], NEO_RGBW + NEO_KHZ800),
  Adafruit_NeoPixel(LED_COUNT[2], LED_PIN[2], NEO_RGBW + NEO_KHZ800),
  Adafruit_NeoPixel(LED_COUNT[3], LED_PIN[3], NEO_RGBW + NEO_KHZ800),
  Adafruit_NeoPixel(LED_COUNT[4], LED_PIN[4], NEO_RGBW + NEO_KHZ800)
};

and when I pass Color to a function, I'm arbitrarily using my first strip to create the Color:
  everyother( strip[0].Color( 0, 255, 0), strip[0].Color( 255, 0, 0), 500);

but in the subroutine I use those colors to set pixels to every strip of the array in a loop:
// set every other color to color1 or color2
void everyother( uint32_t color1, uint32_t color2, int wait) {
  for(int k=0; k<NUM_STRIPS; k++) {
    for( int j=0; j<LED_COUNT[k]; j++) {
      if( j%2 == 0) strip[k].setPixelColor(j, color1);
      else strip[k].setPixelColor(j, color2);
    }
  }
  for(int k=0; k<NUM_STRIPS; k++) strip[k].show();
  delay(wait);
}

Is there another way to define Color that isn't using a real Adafruit_NeoPixel? Yes, it works this way but it feels sloppy.


texts: Find number in a reply returned via serial


texts: How many and fast interrupt pin can handle in Uno?

texts:
So I am using Arduino UNO to do phase cutting and read Fan RPM.

For phase cutting, every half frequency it will triggers interrupts and then arduino will triggers TRIAC. Half frequency(50Hz) is 20ms. And for reading rpm, my fan running at 950rpm or 15.83rps, or doing a revolution for 63ms.

I think both of that works is doing a fast work, and I am afraid if I do it simultaneously the arduino will get an error(like a skip on one half wave, or a skip on reading one revolution), or will it not? Thanks.


texts: Can't extract basic data using ThingspeakHTTP

texts:
I don't know anything about HTML, but I want to extract the % probability of the Northern lights being visible from this webpage
http://aurorawatch.ca/.
I entered this into the URL field, and selected HTML version 1.

When I inspect the text element I want and copy the Xpath I get the following:

"/html/body/div1/div[5]/table/tbody/tr1/td/div1/table[2]/tbody/tr[2]/td/div/table/tbody/tr/td[2]/span"

and enter this into the "parse string" field of the ThingSpeak API app, but get the following error:

"Error parsing document, try a different parse string."

Most people who get this error seem to be getting data that doesn't load with the original page, so I think I must be missing something.

If there is a better solution for pulling this number to my ESP8266 than creating a thingspeak API, I would love to hear it too!


texts:
I am trying to get relays to switch on or off based on if I touch a capacitive sensor, basically a light switch. For some reason, I get two readings that are high capacitive readings when I do a printout. I am not really sure why this is happening. I tried delays in case it was reading my touch too fast but with no luck.

The hardware is basically a 1M resistor between send and receive.

// capactitive sensing
#include <CapacitiveSensor.h>
CapacitiveSensor   cs_7_6 = CapacitiveSensor(7,6);
// 10 megohm resistor between pins 4 & 2, pin 2 is sensor pin, add wire, foil
const int numReadings = 5;
int index = 0;                  // the index of the current reading
int readings[numReadings];      // the readings from the analog input
int total = 0;                  // the running total
int average = 0;
int relay = A2;
int relay2 = A3;
int relay3 = A4;
int relay4 = A5;
boolean lightState = false;
// sound sample
const int sampleWindow = 50; // Sample window width in mS (50 mS = 20Hz)
unsigned int sample;
//other
boolean isRelaysOn = false;

// capacitive sensor
void setup() {
  cs_7_6.set_CS_AutocaL_Millis(0xFFFFFFFF);
  // turn off autocalibrate on channel 1 - just as an example
  Serial.begin(9600);
  for (int thisReading = 0; thisReading < numReadings; thisReading++)
    readings[thisReading] = 0;
  // other
  pinMode(relay, OUTPUT);
  pinMode(relay2, OUTPUT);
  pinMode(relay3, OUTPUT);
  pinMode(relay4, OUTPUT);
  turnRelayOff();
  Serial.begin(9600);
}

boolean state = false;
boolean lastState = true;
boolean lightTurnedItOff = false;

void loop() {
  Serial.println(capReading());
  if(capReading() >= 3000) {
    Serial.println("threadhold reached");
    lightState = !lightState;
    controlRelay();
  }
}

boolean isOn = false;

void controlRelay() {
  if(lightState == true && isOn == false) {
    turnRelayOn();
    //delay(1000);
  }
  if(lightState == false) {
    turnRelayOff();
    // delay(1000);
  }
}

void turnRelayOn() {
  int delayAmount = 100;
  digitalWrite(relay, LOW);
  delay(delayAmount);
  digitalWrite(relay2, LOW);
  delay(delayAmount);
  digitalWrite(relay3, LOW);
  delay(delayAmount);
  digitalWrite(relay4, LOW);
  delay(delayAmount);
  digitalWrite(relay4, HIGH);
  delay(delayAmount);
  digitalWrite(relay4, LOW);
  isOn =true;
}

void turnRelayOff() {
  digitalWrite(relay, HIGH);
  digitalWrite(relay2, HIGH);
  digitalWrite(relay3, HIGH);
  digitalWrite(relay4, HIGH);
  isOn = false;
}

int capReading () {
  // get average.
  total= total - readings[index];
  readings[index] =  cs_7_6.capacitiveSensor(30);
  total= total + readings[index];
  index++;
  if (index >= numReadings)
    index = 0;
  average = total / numReadings;
  delay(100);
  return average;
}

The output doesn't make much sense sometimes either, here are a few samples:

  11 16 21 22 32 61 74 threadhold reached 6191 threadhold reached 6167
  threadhold reached 30 15 11 12

  6 10 17 44 2144 3745 threadhold reached
  -475 threadhold reached
  -3129 22 10 12 13

  15 13 7 20 23 725 2726 2735
  -6373
  -3197 threadhold reached 4127 2714 54 40 43 34 24 27 31


texts: ESP8266 unresolved mDNS host in .local domain

texts:
I am trying to implement a mDNS for esp8266 in Arduino IDE following this guide.

https://tttapa.github.io/ESP8266/Chap08%20-%20mDNS.html

I cannot get the esp8266.local name to work - when i ping it it returns an error unresolved host and putting it in a browser also does not resolve...

The IP address does resolve though. Any advice would be greatly appreciated. I am using Mac OS High Sierra and have seen that many people have experienced this problem on both windows and mac but there does not seem to be a solution yet.

Any ideas?

Thanks x


texts:
I'm using a Relay Channel and NodeMCU(8266-WIFI). When i trigger the connection, LED Turns ON in Node MCU But the Relay connection is not working. I'm not sure what is the issue, Please help to fix it..
My Pin connection as follows.

NodeMCU (VIN) -> Relay (VCC)
NodeMCU (G) -> Relay (G)
NodeMCU (D1) -> Relay (IN4)

My code as follows,
#include <ArduinoJson.h>
#include <ESP8266WiFi.h>
#include <FirebaseCloudMessaging.h>
#include <Firebase.h>
#include <FirebaseHttpClient.h>
#include <FirebaseArduino.h>
#include <FirebaseError.h>
#include <FirebaseObject.h>

// Set these to run example.
#define FIREBASE_HOST "xxx-xxxx.firebaseio.com"
#define FIREBASE_AUTH "xxxxxx"
#define WIFI_SSID "xxxx"
#define WIFI_PASSWORD "xxxxx"

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

  // connect to wifi.
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("connecting");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }
  Serial.println();
  Serial.print("connected: ");
  Serial.println(WiFi.localIP());

  pinMode(D1, OUTPUT);
  pinMode(LED_BUILTIN, OUTPUT);

  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
  Firebase.set("LED_STATUS",0);
}

int n = 0;

void loop() {
  // Get value
  n=Firebase.getInt("LED_STATUS");

  if (n==1) {
     digitalWrite(D1, LOW);
     digitalWrite(LED_BUILTIN, LOW);
     Serial.print("LED is ON ");
     Serial.println(Firebase.getInt("LED_STATUS"));
     delay(1000);
  }
 else{
   //LED_BUILTIN
   digitalWrite(D1, HIGH);
   digitalWrite(LED_BUILTIN, HIGH);
   Serial.print("LED is OFF ");
   Serial.println(Firebase.getInt("LED_STATUS"));
   delay(1000);
 }

}


texts:
I was watching Jeremy Blum's Arduino tutorial series, and he explained the need for debouncing in a simple circuit involving a pushbutton. Pressing the button once should mean the led stays on, and pushing the button again should mean the led should stay off, and so on.
He implemented hardware debouncing on this circuit: using an RC circuit along with an inverting Schmitt trigger.
https://www.youtube.com/watch?v=CRJUdf5TTQQ&list=PLA567CE235D39FA84&index=10 2:45-8:45.
However, the circuit isn't performing as expected, when I implemented the denbuncing. Its behaving as if the debouncing has no effect:-

If anyone wants to see the simulation:-
https://www.tinkercad.com/things/dniOQmnxJPY
Where exactly have I gone wrong? I have checked all the connections multiple times, it seems to be what Jeremy blum had in his video...


texts: How to directly solder wires to protoshield to connect them to Arduino pins

texts:
I bought an assembled Arduino Uno protoshield version 5, similar to this:

I bought it because I would like to solder wires from Arduino IOs, and I was quite disappointed with the impossibility to do so, since the solder points are already taken by the female headers, which are not connected to anything (there are not tracks coming from then to other islands, which I find quite dumb).

I am considering to remove (by desoldering) the headers, so I can access the holes for soldering wires (instead of plugging them to headers), but before doing so, I ask:

  Is there a good way to solder wires so they are electrically connected to the Arduino IO pins?


texts:
I bought an FC-22 (MQ135) gas sensor module which I plugged into my Arduino Uno. I connected it to the A0 analog port. Then created a code that reads the raw data from A0 (code below).

When I run the code on my Arduino Uno in my house I get values of about 30. If I blow over the sensor I get values until about 160. My question is now how I have to read / interpret these values.

According to the MQ135 specifications the sensor has a sesitivity for air quality, measuring benzene, alcohol and smoke.

How can I interpret the values I get? What is a good value and what isn't? Do I have to calculate something out of these values?

My code looks like this:

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

void loop() {
  int sensorValue = analogRead(0);
  Serial.print(sensorValue, DEC);
  delay(100);
  if (sensorValue > 50) {
    digitalWrite(13, HIGH);
  }
  else {
    digitalWrite(13, LOW);
  }
}


texts:
I did the AT&F command and I guess it is the Factory command, how do I fix this? I tried searching it up but I don't seem to find it..
I have a Sodaq Mbili board.


texts:
#include <PubSubClient.h>
#include <ESP8266WiFi.h>

//EDIT THESE LINES TO MATCH YOUR SETUP
#define MQTT_SERVER "YOUR.MQTT.SERVER.IP"
const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASSWORD";

//LED on ESP8266 GPIO2
const int lightPin = 2;

char* lightTopic = "/test/light1";

WiFiClient wifiClient;
PubSubClient client(MQTT_SERVER, 1883, callback, wifiClient);

void setup() {
    //initialize the light as an output and set to LOW (off)
    pinMode(lightPin, OUTPUT);
    digitalWrite(lightPin, LOW);

    //start the serial line for debugging
    Serial.begin(115200);
    delay(100);

    //start wifi subsystem
    WiFi.begin(ssid, password);
    //attempt to connect to the WIFI network and then connect to the MQTT server
    reconnect();

    //wait a bit before starting the main loop
        delay(2000);
}

void loop(){

    //reconnect if connection is lost
    if (!client.connected() && WiFi.status() == 3) {reconnect();}

    //maintain MQTT connection
    client.loop();

    //MUST delay to allow ESP8266 WIFI functions to run
    delay(10);
}

void callback(char* topic, byte* payload, unsigned int length) {

    //convert topic to string to make it easier to work with
    String topicStr = topic;

    //Print out some debugging info
    Serial.println("Callback update.");
    Serial.print("Topic: ");
    Serial.println(topicStr);

    //turn the light on if the payload is '1' and publish to the MQTT server a confirmation message
    if(payload[0] == '1'){
        digitalWrite(lightPin, HIGH);
        client.publish("/test/confirm", "Light On");

    }

    //turn the light off if the payload is '0' and publish to the MQTT server a confirmation message
    else if (payload[0] == '0'){
        digitalWrite(lightPin, LOW);
        client.publish("/test/confirm", "Light Off");
    }

}

void reconnect() {

    //attempt to connect to the wifi if connection is lost
    if(WiFi.status() != WL_CONNECTED){
        //debug printing
        Serial.print("Connecting to ");
        Serial.println(ssid);

        //loop while we wait for connection
        while (WiFi.status() != WL_CONNECTED) {
            delay(500);
            Serial.print(".");
        }

        //print out some more debug once connected
        Serial.println("");
        Serial.println("WiFi connected");
        Serial.println("IP address: ");
        Serial.println(WiFi.localIP());
    }

    //make sure we are connected to WIFI before attemping to reconnect to MQTT
    if(WiFi.status() == WL_CONNECTED){
    // Loop until we're reconnected to the MQTT server
        while (!client.connected()) {
            Serial.print("Attempting MQTT connection...");

            // Generate client name based on MAC address and last 8 bits of microsecond counter
            String clientName;
            clientName += "esp8266-";
            uint8_t mac[6];
            WiFi.macAddress(mac);
            clientName += macToStr(mac);

            //if connected, subscribe to the topic(s) we want to be notified about
            if (client.connect((char*) clientName.c_str())) {
                Serial.print("\tMTQQ Connected");
                client.subscribe(lightTopic);
            }

            //otherwise print failed for debugging
            else{Serial.println("\tFailed."); abort();}
        }
    }
}

//generate unique name from MAC addr
String macToStr(const uint8_t* mac){

  String result;

  for (int i = 0; i < 6; ++i) {
    result += String(mac[i], 16);

    if (i < 5){
      result += ':';
    }
  }

  return result;
}

The error is 'callback' was not declared in this scope


texts: Is a HC-SR04 fast enough to make decisions on moving robot (4 Johnson motors 300 rpm)?

texts:
I am working on a project in which I have made a robot powered by 4 Johnson DC motors (300 rpm) and controlled by Arduino UNO R3. Now in my project I'd used ultrasonic sensor (HC-SR04) for detecting obstacles.

What I want is that as soon as my an obstacle is detected robot should turn by 180° but what actually happening is that sometimes robot takes turn very late (though I'd kept range of sensor approximately 50cm) and sometimes it just collides with obstacles.

As I'm new to Arduino I just want to know if an ultrasonic sensor is fast enough to sense obstacles and signal the Arduino about it, before it gets close enough?

Here's my code

int sense()
{
     analogWrite(trigPin, 0);
 // instead of digitalWrite(trigPin,LOW);
     delayMicroseconds(2);

/* as I'd used my digital pins for  motors and all i have to use pwm pin for  trigger pin of sensors i guess it doesn't make any difference*/

     analogWrite(trigPin, 255);
  // instead of digitalWrite(trigPin, HIGH);
     delayMicroseconds(10);

     analogWrite(trigPin, 0);
     duration = pulseIn(echoPin, HIGH);

     distance = duration/58.2;

      if (distance > maximumRange)
          return 0;
      else
          return 1;
}


texts:
I'm trying to implement the "BNO055 9 Axes Motion Shield".
There is an existing Arduino sketch GitHub that reads out the Euler data, I changed it a bit to print out quaternion data.

#include "NAxisMotion.h"        //Contains the bridge code between the API and the Arduino Environment
#include <Wire.h>

NAxisMotion mySensor;         //Object that for the sensor
unsigned long lastStreamTime = 0;     //To store the last streamed time stamp
const int streamPeriod = 20;          //To stream at 50Hz without using additional timers (time period(ms) =1000/frequency(Hz))

void setup() //This code is executed once
{
  //Peripheral Initialization
  Serial.begin(115200);           //Initialize the Serial Port to view information on the Serial Monitor
  I2C.begin();                    //Initialize I2C communication to the let the library communicate with the sensor.
  //Sensor Initialization
  mySensor.initSensor();          //The I2C Address can be changed here inside this function in the library
  mySensor.setOperationMode(OPERATION_MODE_NDOF);   //Can be configured to other operation modes as desired
  mySensor.setUpdateMode(MANUAL);   //The default is AUTO. Changing to MANUAL requires calling the relevant update functions prior to calling the read functions
  //Setting to MANUAL requires fewer reads to the sensor
}

void loop() //This code is looped forever
{
  if ((millis() - lastStreamTime) >= streamPeriod)
  {
    lastStreamTime = millis();
    mySensor.updateQuat();        //Update the Quat data into the structure of the object
    mySensor.updateCalibStatus();  //Update the Calibration Status

    Serial.print("Time: ");
    Serial.print(lastStreamTime);
    Serial.print("ms ");

    Serial.print(" W: ");
    Serial.print(mySensor.readQuatW());

    Serial.print(" X: ");
    Serial.print(mySensor.readQuatX());

    Serial.print(" Y: ");
    Serial.print(mySensor.readQuatY());

    Serial.print(" Z: ");
    Serial.print(mySensor.readQuatZ());

    Serial.println();
  }
}

Here is a snippet of the "NAxisMotion.h" header file:

    /*******************************************************************************************
    *Description: This function is used to return the w-axis of the quaternion data
    *Input Parameters: None
    *Return Parameter:
    *   int16_t:    W-axis quaternion data multiplied by 1000 (for 3 decimal places accuracy)
    *******************************************************************************************/
    int16_t readQuatW(void);

    /*******************************************************************************************
    *Description: This function is used to return the x-axis of the quaternion data
    *Input Parameters: None
    *Return Parameter:
    *   int16_t:    X-axis quaternion data multiplied by 1000 (for 3 decimal places accuracy)
    *******************************************************************************************/
    int16_t readQuatX(void);

    /*******************************************************************************************
    *Description: This function is used to return the y-axis of the quaternion data
    *Input Parameters: None
    *Return Parameter:
    *   int16_t:    Y-axis quaternion data multiplied by 1000 (for 3 decimal places accuracy)
    *******************************************************************************************/
    int16_t readQuatY(void);

    /*******************************************************************************************
    *Description: This function is used to return the z-axis of the quaternion data
    *Input Parameters: None
    *Return Parameter:
    *   int16_t:    Z-axis quaternion data multiplied by 1000 (for 3 decimal places accuracy)
    *******************************************************************************************/
    int16_t readQuatZ(void);

I understand that the output data type is signed integer, but what syntax do I need to use to store them in an array?
Because it seems the only way to access them is through "mySensor.readQuatX()"


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


texts: Bluetooth serial readings on 0.96'' Adafruit OLED

texts:
I am trying to display the readings of LDR connected to slave arduino through serial monitor of master arduino paired with bluetooth. I got the readings and it is working fine.

But when I connected OLED to the master arduino so that the LDR readings can be displayed on OLED as well as serial monitor, it is not displaying as expected.

So for simplicity I tried sending the word "hello" from slave to master. The code for slave is :

#include <SoftwareSerial.h>
SoftwareSerial BTSerial(10, 11); // RX | TX

void setup() {
  pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
  digitalWrite(9, HIGH);
  BTSerial.begin(9600);
  Serial.begin(9600);
}

void loop() {
  BTSerial.println("hello");
  Serial.println("hello");
  delay(1000);

}

Then I tried displaying the same only on serial monitor of master. The code:

#include <SoftwareSerial.h>
SoftwareSerial BTSerial(10, 11); // RX | TX
char state ;

void setup() {
 pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
 digitalWrite(9, HIGH);
 BTSerial.begin(9600);
 Serial.begin(9600);
 Serial.println("<Arduino is ready>");
}

void loop() {
 if (BTSerial.available()) {
   state = BTSerial.read();
   Serial.write(state);
 }
}

It is showing valid readings in serial monitor with hello being printed after every one second

<Arduino is ready>
hello
hello
hello
hello

But when I modified the code so that I can get the readings on OLED as well as serial monitor;

#include <SoftwareSerial.h>
SoftwareSerial BTSerial(10, 11); // RX | TX
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);
char sensor;
void setup()
{
  Wire.begin();
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);// initialize with the I2C addr 0x3C (for the 128x32)(initializing the display)
  Serial.begin(9600);
  BTSerial.begin(9600);
  pinMode(9, OUTPUT);  // this pin will pull the HC-05 pin 34 (key pin) HIGH to switch module to AT mode
  digitalWrite(9, HIGH);
}

void displayreading()
{
   if (BTSerial.available()) //checks for incoming data
    {

      sensor = BTSerial.read();//reads data from bluetooth serial
      display.clearDisplay();
      display.setTextColor(WHITE);
      display.setCursor(30,0);
      display.setTextSize(1);
      display.print("LDR Reading:");
      display.setCursor(30,10);
      display.setTextSize(2);
      display.print(sensor);
      Serial.write(sensor);
    }
}

void loop()
{
    displayreading();
    display.display();
}

The OLED is showing one letter at a time clearing the screen after every letter rapidly (since I did not add delay which will add up to the problem of data lag). Like :
h , (clear screen)
e (clear screen)
l (clear screen)
l (clear screen)
0 (clear screen)

The serial monitor is showing the readings as:

<Arduino is ready>
hello
hello
hello
hello

But the word hello is printed letter after letter and not in a whole like in the previous master code.There is one second gap after every printing of "hello".

Can somebody please help me with this problem?
Thanks in advance


texts: Is it bad to leave my Arduino UNO on uninterruped?

texts:
I'm developing a project (Data logger) that requires that the Arduino remains on for several weeks.

Is it okay to leave it on for about 6 weeks? Do I need to frequently reset it?


texts:
I have put together a breadboard version of the arduino by following the tutorial on arduino's main website https://www.arduino.cc/en/Main/Standalone.

I have done everything exactly how that tutorial explains it and have double checked my work to ensure I didn't mess up a connection somehow. I have a usb mini breadout board that I am connecting from the breadboard to my computer and the pin outs are as follows:

GND -> Breadboard GND
5v -> Breadboard + rail
TXO -> IC pin 2
RXI -> IC pin 3
GND (GRN) -> IC pin 1 through .1μF cap

When I go to the arduino IDE and select the arduino duemilanove setting and upload a sketch I come out with this error:

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

I am using a pre-bootloaded atmega328 chip and have switched it out with two others to make sure it wasn't the switch, but that didn't help either.

Any ideas on what might be the problem?


texts:
This is my first library so feel free to burn me and vote this down :D
This is a library that provides me with Watchdog deep sleep on my ATtiny85 projects.

In the test sketch I use the watchdog timer's interrupt vector but I want to place this within the library. How can I do this?

I have tried to add this to the init method but that did not work out;
powernap.h:26: error: expected unqualified-id before string constant
     ISR(WDT_vect) {

Also; feel free to shoot at the rest of the library, I am here to learn.

Test Sketch

#include "powernap.h"

#define LED 0

Napper napper = Napper();

volatile boolean f_wdt = 1;

ISR(WDT_vect) {
  f_wdt=1;
}

void setup() {
  delay(2000);
  napper.setup(8); // configure watchdog timer
}

void loop() { // blink
  pinMode(LED, OUTPUT);
  digitalWrite(LED, LOW);
  delay(200);
  digitalWrite(LED, HIGH);
  delay(200);
  digitalWrite(LED, LOW);
  delay(200);

  napper.sleep(); // deep sleep
}

powernap.cpp

#include "powernap.h"

 #ifndef cbi
   #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
 #endif
 #ifndef sbi
   #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
 #endif

Napper::Napper() {

}

void Napper::init(float initial) {
//  volatile boolean f_wdt = 1;

//  ISR(WDT_vect) {
//  f_wdt=1;
//  }
}

void Napper::setup(int cycle) {
    byte bb;
    int ww;
    if (cycle > 9 ) cycle=9;
    bb=cycle & 7;
    if (cycle > 7) bb|= (1<<5);
    bb|= (1<<WDCE);
    ww=bb;

    MCUSR &= ~(1<<WDRF);
    // start timed sequence
    WDTCR |= (1<<WDCE) | (1<<WDE);
    // set new watchdog timeout value
    WDTCR = bb;
    WDTCR |= _BV(WDIE);
}

void Napper::sleep() {
    cbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter OFF

    set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here
    sleep_enable();

    sleep_mode();                        // System sleeps here

    sleep_disable();                     // System continues execution here when watchdog timed out
    sbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter ON
}

powernap.h

#ifndef Fader_h
#define Fader_h

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

#include <avr/sleep.h>
#include <avr/wdt.h>
#include <util/delay.h>

class Napper {
    public:
        Napper();

        void init(float initial);
        void setup(int cycle);
        void sleep();

    private:
        int flag;

};

#endif


texts: Minimum value I2C-pull up resistor for arduino

texts:
I'm trying to determine the minimum value of pull resistor for Arduino Uno

The datasheets says for arduino; VOL = 0,4 for IOL = 20 mA. (VDD = 5V)

For formula for calculation of minimal pull-up is: Rmin=Vcc−0.4V/20mA = 4,6V / 20mA = 230 ohms.

But I saw that people use 0,4V for 3mA. Than the minimal value is 1,6K ohms.

So whats the minimum value of pull-up for arduino?

(also my slave has 0,4 Vol for 20 mA IOL)


texts:
A while ago I have bought NodeMCU board along with few sensors to play with. I have coded everything, and, when powered via USB, works like a charm. Problem begins, when I try to use my contraption as a standalone system. It works for few minutes, then it starts giving me false readings from the sensors (like, luminosity of few thousands in a dark room).

I am powering the system with (pics at the bottom of the post) AC-DC step down module, 230v -> 5v (1A of current), which then I am stepping down with DC-DC step down module, 5v -> 3v (800mA of current). Using only these two modules, I power NodeMCU and all of my sensors - currently luminosity, temp&humid, motion, SSR (I had led matrix too. I thought that maybe it drags too much current, but no luck there - after disconnecting it I have same problems).

My main indicator that something is not right, is SSR module. It has a built-in diode of the same size that NodeMCU has. It lights immediately as I start the system, and it (it's diode) flickers (it's intensity changes). It does not flicker, when I connect everything through USB.

I have also tried to put 50uF capacitor into the wiring, but no luck either, system is still unstable. What am I doing wrong? Why does the light flickers? Is 1A/800mA not enough power for my system?

Edit: I know what is the cause. I just do not know how to fix it. I just kept my multimeter on for 10mins for both of the step down modules. 5V -> 3V step down (2nd item in the pics below) is initially giving me 800mA, but then gradually losing current (right now it's at 350mA after just few minutes of work). Is there anything I can do here? Or just throw the thing away and look for some other power supply? It's a standard AMS 1117 with some capacitors on it.

Below are the pictures, of my step-down modules and SSR module:


texts: Are my stepper motors being burnt out? What is the issue here?

texts:
I am building a mini-cnc laser engraver as shown in this intructable and this youtube video.

I have built the circuit (minus the jst connector and two male pins at the top left of the board) and have attached a stepper motor from a dvd drive. It worked like a charm, but made a loud ringing noise (like tinnitus.) I proceeded to test it with laser GRBL, and it moved great, but gradually started missing steps, at first only in one direction and eventually in both. After a couple hours of being connected, it wouldn't budge at all. I switched the motor for another motor, and tested it again. This time the motor was much shorter-lived. It made 5 steps perfectly and then just shut off. You could hear the motor try to turn, but it was like it didn't have any torque at all. What could be the issue? (I also tried it on the other axis with the other motor driver, no change.)

It's also worth noting that at one point both the positive and negative (ground) cables from my power supply made contact with metal at once, throwing a spark. However, the steps were already beginning to be lost before that happened.

As per your request, I have attached the circuit layout I am attempting (it's identical to the one in the tutorial) as well as a picture of my physical circuit board. (sorry, a link was my only option as the pics were to big for upload) I know the soldering is pretty bad- I have a giant soldering iron. I don't see any shorts though.


texts: Sum values, store them and print the last value

texts:
I have a mass flow meter connected to an Arduino Uno board. I have managed to read the volume flow in L/hour, but now I'm struggling to implement a code that stores the values so that I see the number of Liters used.

For instance, I can see on my monitor this:

0 L/hour

0 L/hour

And if I have some water running through,

10 L/hour

20 L/hour

20 L/hour

Then when I stop the flow it goes back to 0.

0 L/hour

Is there any ways to sum up time instances, get the total number of liters and keep it printed during every instance?

Mathematically is not that difficult (Volume = Volume Flow in L/hour * time), but I don't know how to implement this. Can anyone help with this? It can be in seconds or ms or whatever.

Paul


texts:
I'm working on a project that consists of sending data from flex sensors from a master Arduino to a slave arduino that uses that data to control servo-motors. I am trying to start slow and just control an LED using a button.
I have gone through all AT commands, have set both a master and a slave and binded the addresses but when I try to light the LED on it for some reason doesn't work. My serial monitor keeps printing the letter "d" over and over again and I don't know what this is. Code is below:

int val=0; //Master code
#define button 3
void setup() {
Serial.begin(38400);
pinMode(button,HIGH);
}
void loop(){
val=digitalRead(HIGH);
if(val==HIGH){
Serial.write(100);
delay(500);
}
delay(50);
}
}

#define led2
int pos=0;
int val;

void setup(){
Serial.begin(38400);
pinMode(led,OUTPUT);
}
void loop(){
if(Serial.available()>0){
val=Serial.read();
if(val==100 && pos==0)
{
digitalWrite(led,HIGH);
pos=1;
}
else if(val==100 && pos==1)
{
digitalWrite(led,LOW);
pos=0;
}
}
}

If anyone can help i'd appreciate


texts: Shift Register 74HC595 circuit working weirdly

texts:
I built the circuit from the arduino ShiftOut tutorial, but it is not working as expected. I made a simulation model and that one isn't working either.

The code I used is from the tutorial:

// SH_CP; 11
const int clockPin = 9;
// DS; 15
const int dataPin = 8;
// ST_CP; 12
const int latchPin = 10;

void setup() {
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);
  pinMode(latchPin, OUTPUT);

  Serial.begin(9600);
  Serial.println("reset");
}

void loop() {
  for (int number = 0; number < 256; number++) {
    Serial.println(number);
    digitalWrite(latchPin, LOW);
    shiftOut(dataPin, clockPin, MSBFIRST, number);
    digitalWrite(latchPin, HIGH);
    delay(500);
  }
}

Any idea as to what's wrong?


texts: Change css form color from esp32 if statement

texts:
I am fairly new to arduino and ESP though am very familiar with css and javascript.

I have an esp webserver that includes a button

client.print("<button style='background-color: #F30C0C; color:#000;'></button>");

but need it to change the css backbround-color when pin is reading HIGH

 if (c == '\n') {
          currentLineIsBlank = true;
          buffer = "";
        }
        else if (c == '\r') {
          if (buffer.indexOf("GET /?relay1") >= 0)
            relayPIN1read = digitalRead(relayPIN1);

          if (relayPIN1read == HIGH) {
            digitalWrite(relayPIN1, LOW);
          }
          if (relayPIN1read == LOW) {
            digitalWrite(relayPIN1, HIGH);
          }
        }
      }

Does any one know of any way to do this?


texts: Distance Measurement - between 6 points, individually moving in (almost) any direction within 1m

texts:
I'm trying to find a solution for a given task in a problem I want to solve.
Assume I have 6 individual Points in a 3D environment of about 1m³. Each point will be able to change position (almost) freely.
Is there a way I can get the information of which distance each point is to any of the remaining 5 points?
Background Idea for understanding: Say its 2 wooden triangles (one of those points on each angle) and I need to calculate how far and in which direction one is moving from or towards the other.
By comparing all those distances, direction and step-width may be easily calculated.
Are there like "coded" distance-sensors so they don't mix their signals?
Any thoughts highly appreciated.


texts: I have been trying to implement a simple HTTP get request with an A6 GSM module, and am finding it very difficult, i couldn't get any useful docs or tutorial online to guide me through, all i could find is for the SIM900/800 modules which doesn't seems to work with A6 GSM module, i would love to be pointed to any useful docs or just provide for me simple steps to make a HTTP get request using the module from the serial terminal with AT commands


texts: Power small hobby motor using Vin pin on Arduino and 9V battery, safe?

texts:
MOVED
HERE

I want to motor a small motor with a 9V battery and control it with PWM using an Arduino Leonardo. I know I can power the motor separately, but this introduces the problem of needing a battery to power the motor (9V battery) and another power source to power the Arduino (another 9V battery?)

Would it be safe to simply power the Arduino with a 9V battery and use the Vin pin on the board (which is unregulated and outputs directly the power source powering the Arduino) to drive the motor? That way, I power everything from the 9V battery, and use a transistor to drive the motor.

Thanks a lot!

Steve.


texts:
How can I only let half of the LEDs light up,
for example, LED 1 on, LED 2 off, LED 3 on...and so on.

I did it this way
(this example fades also all LEDs on and off)

   int x = 1;
   for (int i = 0; i > -1; i = i + x){
      leds[0] = CRGB(i,0,0);
      leds[1] = CRGB(0,i,0);
      leds[2] = CRGB(i,0,0);
      leds[3] = CRGB(0,i,0);
      Serial.println(i);
      FastLED.show();
      if (i >= 55) x = -1;             // switch direction at peak
      delay(10);
   }

but that is not so nice if you have 100 LEDs or so.


texts:
When I send data using

Serial.println()

in what format does it go? I want to observe the data using the software 'Terminal'. When I observe there, if I've sent 255 using Serial.println(), I get a series of numbers 0 0 224 on the terminal. I've kept the baud rate same in both places(9600), Stop Bits as 1 in Terminal.


texts:
The below picture is the introduction of setModemRegisters .

First: What is the mean of ModemConfig* config? I mean: how to write the parameter. Maybe just give a example, and it will be better if it's suitable for this SO question.
Second: What is the mean of data rate? It is the speed of SPI between the SI4463 and MCU or speed of two SI4463  ?
Third, What is the mean of bandwidths? I never saw it...

Thanks for any help .


texts: PWM signaling with Arduinos: What is the reason for the ground connection?

texts:
This may sound like a very dumb question and I apologise in advance.

I've gone through reading about PWM and working on some example sketches to control PC fan speeds using PWM and Arduino.

In all documents I read, it is mentioned that "PWM is a signal".

My questions:

Is PWM really a signal? To me, it looks like an electric current turned on and kept on for a certain time, then off for a while repeatedly. What makes this a "signal"?
If PWM is a signal, why do we need to connect the Ground from Arduino to the ground of the device to which "PWM signal" is being sent to?

This is confusing me because in my mind, for example, radio signals do not need a ground connection. The signal comes and gets read.


texts:
I want to add zero before the float number like this:
010.0

The code I'm using is this:
if(value < 10){
  lcd.print(F("0"));
}

lcd.print(value);

But when the value is exactly 10, it adds the zero anyway:
0010.0

I tried something like this but haven't had any luck:
if(value < 10 && value != 10){
  lcd.print(F("0"));
}

How can I solve this issue?

- EDIT:
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x3B, 16, 2);

#define turnOff 3
#define turnOn 2
#define gateStatus 8
#define btn 4

float ADC0, current, ADC1, voltage, ADC2, temp, watt;
int8_t state, btnState, btnPushed, btnToggle, lcdClear;
uint32_t deBounce = 0;

void setup() {
  analogReference(EXTERNAL);
  pinMode(turnOff, OUTPUT);
  pinMode(turnOn, OUTPUT);
  pinMode(gateStatus, INPUT);
  pinMode(btn, INPUT_PULLUP);
  pinMode(13, OUTPUT);
  lcd.begin();
}

void loop() {
  digitalWrite(13, LOW);
  state = digitalRead(gateStatus);
  btnState = digitalRead(btn);

  if (!btnState) {
    if (millis() - deBounce > 200) {
      btnPushed = 1;
      deBounce = millis();
    }
  }
  if (btnPushed && btnState) {
    btnToggle = 1;
  }
  if (btnToggle && state) {
    digitalWrite(turnOn, HIGH);
    delay(5);
    digitalWrite(turnOn, LOW);
    btnToggle = 0;
    btnPushed = 0;
  }
  if (btnToggle && !state) {
    digitalWrite(turnOff, HIGH);
    delay(5);
    digitalWrite(turnOff, LOW);
    btnToggle = 0;
    btnPushed = 0;
  }

  for (int i = 0; i < 500; ++i) {
    ADC0 += analogRead(A0);
  }
  ADC0 /= 500;
  current = ADC0 * (2.5 / 1023.0);
  current = current / 0.211;

  for (int i = 0; i < 500; ++i) {
    ADC1 += analogRead(A1);
  }
  ADC1 /= 500;
  voltage = ADC1 * (2.5 / 1023.0);
  voltage = voltage * 20.2;

  for (int i = 0; i < 100; ++i) {
    ADC2 += analogRead(A2);
  }
  ADC2 /= 100;
  temp = ADC2 * (2.5 / 1023.0);
  temp = temp * 100.5;

  watt = voltage * current;

  lcd.setCursor(0, 0);
  if(voltage < 10){
    lcd.print(F("0"));
  }
  lcd.print(voltage);
  lcd.setCursor(5, 0);
  lcd.print(F(" V"));

  lcd.setCursor(9, 0);
  if(temp < 10){
    lcd.print(F("0"));
  }
  lcd.print(temp, 1);
  lcd.print((char)223);
  lcd.print(F(" C"));

  if (state) {
    lcd.setCursor(0, 1);
    lcd.print(F("   OUTPUT OFF   "));
    lcdClear = 1;
  }

  else {
    if (lcdClear) {
      lcd.clear();
      lcdClear = 0;
    }
    lcd.setCursor(0, 1);
    if (current < 10) {
      lcd.print(F("0"));
    }
    lcd.print(current);
    lcd.setCursor(5, 1);
    lcd.print(F(" A"));

    lcd.setCursor(9, 1);
    if (watt < 10) {
      lcd.print(F("0"));
    }
    if (watt < 100) {
      lcd.print(F("0"));
    }
    lcd.print(watt, 1);
    lcd.setCursor(14, 1);
    lcd.print(F(" W"));
  }
}


texts:
I'm planning to build a device that would read some sensor data and send it via GPRS, eg. once per day. (Not that original, yeah.) But my problem is choosing a GSM/GPRS shield.

The official shield has a nice interface for doing an HTTP POST/GET. OTOH, the shield seems to be sold out (and would be quite expensive anyway).

There seem to be other shields available, but their code examples tend to look quite hacky: the device waits for an arbitrary moment and then hopes that the server is done. That's IMO both inefficient or unreliable.

My question: which GSM/GPRS shield would you recommend, with these features:

a sane library w/ examples, such as the official onean external antennabonus: a competitive priceanother bonus: hopefully a "real" shield, so no soldering required and a few pins still easily usable for the sensors.


texts: Need help to set PWM frequency to 25kHz on pin 8 of Arduino Mega

texts:
I am trying to follow Need help to set PWM frequency to 25kHz and generate the same 25khz on pin 8 of arduino mega which is controlled by TIMER 4; I dont see any success; could someone please help?

Given below is the code I have tried based on an answer by @EdgarBonet in the linked post and  I tried on connecting fan pwm on each of the 3 pins 6, 7, 8 one by one and still cannot get the speed to change and the fan is just running at full speed;

void analogWrite25k(int value)
{
    OCR4A = value;
    OCR4B = value;
    OCR4C = value;
}

void setup()
{
    TCCR4A = 0;
    TCCR4B = 0;
    TCCR4C = 0;
    TCNT4  = 0;
    TCCR4A = _BV(COM4A1)
           | _BV(COM4B1)
           | _BV(COM4C1)
           | _BV(WGM11);
    TCCR4B = _BV(WGM13)
           | _BV(CS10);
    TCCR4C = _BV(WGM13)
           | _BV(CS10);
    ICR4   = 320;

    // Set the PWM pins as output.
    pinMode( 8, OUTPUT);
}

void loop()
{
    analogWrite25k(10);
    for (;;) ;  // infinite loop
}

edit2:

Thanks for the hints by @dannyf; I read the datasheet again and below is what I am trying now but even this is not working and I am really unable to figure out if something is not right in this; I am trying to set value of OCR4C only in analogWrite25k method since fan pwm line is connected to digital pin 8 of my Mega;

TCCR4A = 0;
TCCR4B = 0;
TCNT4  = 0;
TCCR4A = _BV(COM4C1)
      | _BV(WGM41);
TCCR4B = _BV(WGM43)
     | _BV(CS40);
ICR4   = 320;         // TOP = 320


texts: Combining an NRF24L01 transmitter/receiver with an Adafruit Motor Shield V1?

texts:
I'm making a vehicle project as a way to learn Arduino. I've set up motor control for a number of DC-motors plus a servo via an Adafruit Motor Shield V1 that I picked up.
Everything works fine, but now I've started looking at adding wireless control for the setup using a second Arduino and two NRF24L01 wireless units. However, reading up on the specs for the NRF24L01 it seems it requires pin 12 on the Arduino, which is already in use by the motor shield.
So, can I combine a NRF24L01 and an Adafruit Motor Shield V1? And if so, how?
If it's not possible, what would be the pros and cons of slaving the shielded Arduino to a Nano that would carry the NRF24L01, versus replacing the Adafruit motor shield with external DC motor driver(s)?
Edit:
I now found this previous question:
Motor shield and wireless transceiver compete for same pins
A difference in my project is that I'm not using stepper motors, so perhaps that makes a difference?


texts:
I wanted to have your comments about one of my questions.
I am currently working on the sketch for the Arduino Portenta H7. However, due to my poor electrical background, I would like to ask your opinion about the pinouts.   Below you can find the pinout diagram from the document page 1 available at the below link.
https://content.arduino.cc/assets/Pinout-PortentaH7_latest.pdf
I am a bit confused about the analog pins. As the diagram and color-coding show ADC A0 ( available on the high-density connector)  and analog pin A0 both separately.   What can be the difference between them ? or maybe I am interpreting wrong.
Because, on an ordinary Arduino board ( as far as I found), we have the Analog pins which are used for the ADC too. However, here in the Portenta pinout diagram, we have ADC A0 and analog A0 separate?
I thank you for your time and opinion.


texts: Trouble trying to turn a stepper while a button is pressed down

texts:
So i'm currently coding a little device that rotates a step motor round one 8th of a full revolution every time a button is pushed. the motor is attached to a question reel with 8 questions on it, each one is viewable through a little window covering the reel after each button press. the thing im concerned about is that if even one of the question sections is slightly larger or smaller than the others, it will cause the question to become misaligned with the window after a certain number of run throughs.

in order to combat this I want to have a back up code that simply rotates the stepper while the button is held down. this will allow me to manually reset the reel to its proper positioning should the questions become misaligned. im not achieving this however, and was hoping someone may be able to detect where the issues are in my code?

#include <Stepper.h>

#define STEPS 2048

Stepper myStepper(STEPS, 8, 10, 9, 11);

const int  buttonPinBlue = 6;

void setup() {

  myStepper.setSpeed(5);
}

void stepp() {

 myStepper.step(1);

  pinMode(buttonPinBlue, INPUT);
}

void loop() {

 if (buttonPinBlue == HIGH) {

  Serial.print("pin is high");

   stepp();
  }

}

also just as a side note, the stepper runs fine using the 'define steps' value and the speed that I've set here, the issue appears to be that the button press is not being detected


texts: Blinking 2 LED having input from serial monitor

texts:
Sir while entering the values on the serial monitor, I ask the user to enter the value for red led voltage(0-255) then again ask for yellow at the red voltage asking it produces the user to  put the value, after that it asks for yellow led input but the time to enter the value for yellow led input is very less and so it does not get entered and the futher program starts. So only red led works where as Yellow does not.

int REDledpin=9;        //RED led on pin 9 of the uno board.
int YELledpin=7;        //YELLOW led on pin 8 of the uno board.
int REDonleddelay=500;  //The red led will be on for 500 ms.
int REDoffleddelay=500; //The red led will be off for 500 ms.
int YELonleddelay=600;  //The YELLOW led will be on for 600 ms.
int YELoffleddelay=600; //The YELLOW led will be off for 600 ms.
int countredled=5;        //The RED LED count variable
int countyellowled=5;     //The YELLOW LED count variable
String red="Red led is blinking";
String Yellow="Yellow led is blinking";
int redintensity;
int yellowintensity;

void setup() {
  Serial.begin(9600);
  pinMode(REDledpin,OUTPUT);
  pinMode(YELledpin,OUTPUT);

  Serial.println("How much voltage you want to apply to the red LED (0-255)?");
  while(Serial.available()==0){}
  redintensity= Serial.parseInt();

  Serial.println("How much voltage you want to apply to the yellow LED (0-255)?");
  while(Serial.available()==0){}
  yellowintensity = Serial.parseInt();

}

void loop() {
Serial.println(red);
for(int j=1;j<=countredled;j=j+1)
  {
    Serial.print("The red LED blink star: ");
    Serial.println(j);
    analogWrite(REDledpin,redintensity);
    delay(REDonleddelay);
    analogWrite(REDledpin,0);
    delay(REDonleddelay);
  }

Serial.println(" ");
Serial.println(Yellow);
  for(int j=1;j<=countyellowled;j=j+1)
  {
   Serial.print("The yellow LED blink stars");
   Serial.println(j);
   digitalWrite(YELledpin,yellowintensity);
   delay(YELonleddelay);
   digitalWrite(YELledpin,0);
   delay(YELoffleddelay);
  }
 Serial.println(" ");
}


texts:
With verbose upload selected the IDE provides the executed avrdude command at the top of the log.

I am interested in copy pasting that avrdude command. However at the end of the upload the command is not available anymore. The IDE only shows some last lines of the log and discard the top part.

Is that log saved anywhere? (I am on ubuntu). Any ideas how I can get that command?


texts: Connecting multiple boards to Arduino Uno r3

texts: How can I connect the Arduino RFID RC 522 and SD card adapter to one Arduino Uno R3? As each library takes specific pins in Arduino for MOSI, MISO, CLK. So I have conflict in the pins, how can this be solved?


texts:
This is my first Arduino project, and I would like to stop my servo's loop after 1 minute. Can someone help me?

#include <Servo.h>
Servo myservo;

void setup()
{
  myservo.attach(5);
}

void loop()
{
  myservo.write(45);
  delay(1000);
  myservo.write(125);
  delay(1000);
}

Thanks!


texts: Output frequency from an SPI DAC (MCP4922) is lower than expected

texts:
I'm using a 2-channel, 12-bit DAC (MCP4922, datasheet) with an Arduino Uno, using the library written for it here. With the clock divider set to 2, I should have the SPI clock frequency at 8MHz. If each value sent to the DAC takes about 12 of these clock cycles, that leaves me with about 650kHz as my output frequency (when I'm sending a simple on-off signal like below), but the fastest I see is about 25kHz.

  void loop() {   dac.output2(4095, 0);   dac.output2(0, 4095);  }

Am I misunderstanding how the transfer protocol works? How can I make this faster? I'd like to both understand why this is so slow, and also to get an output frequency of at least 50kHz.


texts: converting int or float into bytes array in arduino

texts:
I am trying to send data from one arduino to another over ethernet using udp protocol.
In arduino writing data over udp is like this
UDP.write(buffer, size);

where buffer is an array to send as a series of bytes and size is the size of the array.
Now, i am reading a sensor value from a0 pin of the arduino it will be stored either in int or float type variable. As mentioned earlier udp only sends byte type array. so all i want to do is convert the value stored in the variable to the byte type array.
my variable will be.
pinMode(A0,INPUT);
int data;
byte data_array[Size];

and in loop
data=analogRead(A0);

now i have convert this value in data_array;
Please provide the suggestion with proper explanation.
Thank you


texts: Is there a way to traverse a filesystem and read files with an arduino?

texts:
I recently got into arduino and I want to set up something big. My project will need the arduino to be able to get into a specific directory of a windows (later may change to linux but for now windows) computer which will have some files with values required for the arduino to run.

Is it possible to set it to go to a fixed path and open a file with a specific name and get it's contents?

Ideally I would want those values to be stored to my micro sd so I do not load too many things on memory as my board is a Leonardo and the code is quite extensive already. (The board can be changed if needed)

Any help/ideas are appreciated!


texts: How to set CS pin on Beetle BLE/Bluno Beetle to Adafruit SD Card Breakout - Initialization Failed!

texts:
Hi I have a Beetle BLE (https://www.dfrobot.com/wiki/index.php/Bluno_Beetle_SKU:DFR0339) and I am trying to connect an Adafruit MicroSD card breakout board+ (https://www.adafruit.com/product/254) via SPI connections. I am trying the following code, but I am having trouble selecting the CS pin using D4 since the Beetle has no D10. Does anyone know if I am selecting D4 correctly, while keeping pin 10 as an output. I keep getting initialization failed! My setup is on the ICSP 6 pin configuration:

5V --> 5V

MISO --> DO

SCK -->CLK

GND --> GND

MOSI --> DI

D4 --> CS

RST is left out

Here is my code:

#include <SPI.h>

#include <SD.h>

File myFile;

void setup()
{
  Serial.begin(9600);
  Serial.print("Initializing SD card...");
  // On the Ethernet Shield, CS is pin 4. It's set as an output by default.
  // Note that even if it's not used as the CS pin, the hardware SS pin
  // (10 on most Arduino boards, 53 on the Mega) must be left as an output
  // or the SD library functions will not work.
//   pinMode(4, OUTPUT);
   pinMode(10, OUTPUT);
//   digitalWrite(4, HIGH); // Add this line

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

  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.

  myFile = SD.open("test.txt", FILE_WRITE);

  // if the file opened okay, write to it:
  if (myFile) {
    Serial.print("Writing to test.txt...");
    myFile.println("testing 1, 2, 3.");
  // close the file:
    myFile.close();
    Serial.println("done.");
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }
}

void loop()
{
  // nothing happens after setup
}


texts: Am I at the limit of UART transmission time?

texts:
I'm currently using an STM32F103C8 (With an arduino core) to read 4 sensors at 1kHz, then send that data via UART (at 115200 baud) to another device. Each sensor returns a float, I also include an unsigned long representing milliseconds since boot time. This adds up to be a 20 byte package, that I attempt to send at 1kHz. Sensor sampling is carried out via a timer interrupt, as it is crucial the time between samples is constant.
The data transmission itself (If I send it slowly) takes approx. 70 microseconds. When sped up to 1kHz, it takes approx. 2500. I assume this is because I am filling a serial buffer of some sort.
Is this about the limit of the communication method? If it takes longer than 1000 microseconds to send the data, then presumably the interrupt will trigger before the data is sent and it will have to start again?


texts:
I've got 2 int16_t numbers, say 388 and 10288, which are sensor readings from an accelerometer. I want to estimate the angle of the device on that, but seemingly there are some type overflow issues:

My final goal is this:

theta =  atan(-ax/sqrt((float)ay*ay+az*az));

The problem occurs in the bracket: ay^2 and az^2 are the 2 power of the given numbers. I recalculated with matlab and for the above example I get a^2+b^2 = 388^2+10288^2 = 105993488 what I get from the arduino however is 152848.
To be short: I don't know much about fixed point math or thelike and I couldn't find a sufficient answer to this: How do I calculate the square root term?


texts: Can an AT89S52 be programmed using an Arduino as ISP?

texts:
Since the AT89S52 controller is ISP programmable is it possible to use an Arduino UNO as a programmer to upload the hex file to the 8952 ?

I've tried various programmer softwares such as progisp, 8051 loader and ISP Prog v1.4 but the Arduino doesnt show up as a programmer on any of these. I've uploaded the ArduinoISP sketch on the UNO and then tried to program the 8952 without any luck.

According to my understanding the ISP programmers use an ATMega8 ,so is what I'm trying to do possible or do I need to purchace an ISP programmer ?


texts:
Schematic: 1 Button and 1 Potentiometer
Sketch: Each time the button is pressed, acquire the value of the potentiometer in a vector of 10 positions and print it on the serial monitor or LCD display.
At the end print the average (sum of values / 10)
#define BUTTON 5
#define ARRAY_SIZE 10
int counter = 0;
int valori[ARRAY_SIZE];
int pinPotenziometro = A0;
int statoPresenteBottone = LOW; //why so LOW?
float media = 0.0;
void setup() {
  Serial.begin(9600);
  pinMode(BUTTON, INPUT);
  for (int i = 0; i < ARRAY_SIZE; i++) valori[i] = 0;
}
void loop() {
  if (counter > ARRAY_SIZE) {
    counter = 00;
    media = 0.0; // when we fill array fully - we start again
    for (int i = 0; i < ARRAY_SIZE; i++) valori[i] = 0;
  }
  statoPresenteBottone = digitalRead (BUTTON);
  while (statoPresenteBottone == HIGH) {
    valori[counter] = analogRead(A0);
    media = media + valori[counter];
   Serial.print("Average: ");
   Serial.println(media / counter);
   Serial.print("Button pressed times: ");
   Serial.println(counter);
    statoPresenteBottone = LOW;
    counter++;
  }
}

That's what I did but it doesn't work like I want. I need to get the average of the 10 numbers I acquired at the end but it does it each time.


texts: Multiple arduino slaves with one master computer that sends instructions for the actuators to work

texts:
I am in the middle of an automation project and suddenly after completing one stage of my assembly, I now need to scale it. So my computer which until now was sending data to only one arduino UNO can send to multiple arduino uno's, also I am seeking an advice, I am using up all the digital pins on my arduino Uno and this makes me think if I should upgrade to arduino mega or leave it the way it is.
The communication protocol I am using is UART which is done through USB from my computer to the board, so can I just use a USB hub to handle this issue?


texts: Can I connect a voltage, higher that the 1.1V bandgap voltage, to an ADC pin

texts:
Can I (attempt to) measure a voltage that is higher that the ADCs Vref, without damaging my IC?

I'm trying to measure the battery voltage using a resistive divider, and using the internal 1.1V bandgap voltage. I selected the resistors so the voltage would be around 1V when fully charged.

My project can however also be power by a wall-adapter, which exceeds the batteries voltage, resulting in a voltage higher than 1.1V at the ADC.

In the datasheet the table of ADC Characteristics seems to indicate that the maximum input voltage is Vref. Though I'm not sure if that's the maximum voltage is can convert, or if that's the maximum voltage that's allowed.

Elsewhere in the datasheet it says: Single ended channels that exceed VREF will result in codes close to 0x3FF, which seems to indicate it isn't a problem to exceed Vref (as long as it's below Vcc).

The part I'm using is an ATtiny13A, but the relevant sections of the datasheet seem identical to the ATMega328.


texts: Will I be able send a HTTP request using the Arduino Yún?

texts:
After spending countless hours trying to get my wifi module to work only to fail, I've decided I might as well get an Arduino with built-in wifi.

Would I be able to send HTTP requests (GET, POST etc) straight out of the box or would I have to configure and connect some additional components/modules to the board?

Also, I plan on connecting a thermistor and a GPS module to the Arduino. When the thermistor reaches a certain level, it sends the GPS coordinates of my server. Is this possible in terms of practicality and voltage? And would I be able to write a sketch using the Arduino board or would I have to switch the board to something like 'Generic ESP8266 Module' (something we have to do if we want to program the ESP8266 using the Arduino IDE).


texts: How to calculate phase shift between two square waveforms with Arduino DUE

texts:
I have two square wave signals with the same frequency. I want to measure the phase shift between these two signals. There will be a small phase difference between two signals. (0-90 degree) and the frequency will vary in the range 100mHz - 50kHz. I am using an Arduino DUE (ATMEL ATSAM3X8E AU ,ARM)

I tried to use "micros()" for timer functionality to get 2 different times and then calculate the phase shift using the following code:

int led=47,count1=0,count2=0,temp=0;
int i=0,j=0;
float time1[3]={0,0};
float time2[3]={0,0};
float freq1=0,freq2=0;
float period1=0,period2=0;
float ps=0;

void setup()
{
      Serial.begin(9600);
      Serial.println();
       Serial.println();
      pinMode(31,INPUT);
      pinMode(33,INPUT);
      pinMode(led,OUTPUT);
      digitalWrite(led,HIGH);
      noInterrupts();
      attachInterrupt(31,in1,RISING);
      attachInterrupt(33,in2,RISING);
      interrupts();
}

void in1()
{      noInterrupts();
       switch(i){
           case 0 : time1[i]=micros(); i++;  break;
           case 1 : if(j==1){time1[i]=micros(); i++; break;}
       }
       interrupts();
}
void in2()
{      noInterrupts();
       switch(j){
            case 0 : if(i==1){time2[j]=micros(); j++; break;}
            case 1 : if(i==2){time2[j]=micros(); j++; break;}
       }
           if(j==2){
             period1 = (time1[1]-time1[0]);
             period2 = (time2[1]-time2[0]);
             freq1 = 1000.0/period1;
             freq2 = 1000.0/period2;
             ps = (((time2[1]-time1[1])*360.0)s/period1);
          if(freq1==freq2){
          Serial.println("");
          Serial.print("TIME1[0] = ");
          Serial.print(time1[0],6);
          Serial.print("\t TIME1[1] = ");
          Serial.print(time1[1],6);
          Serial.print("\t DEL1 = ");
          Serial.println(time1[1]-time1[0],6);
          Serial.print("TIME2[0] = ");
          Serial.print(time2[0],6);
          Serial.print("\t TIME2[1] = ");
          Serial.print(time2[1],6);
          Serial.print("\t DEL2 = ");
          Serial.println(time2[1]-time2[0],6);
          Serial.print("\t x = ");
          Serial.print(time2[0]-time1[0],6);
          Serial.print("period1(ms) = ");
          Serial.print(period1,6);
          Serial.print("\t period2(ms) = ");
          Serial.println(period2,6);
          Serial.print("freq1 = ");
          Serial.print(freq1,6);
          Serial.print("\t freq2 = ");
          Serial.print(freq2,6);
          Serial.print("\t Phase Shift = ");
          Serial.println(ps,6);
          }
          else {
          i=0;j=0;
          interrupts();
          }
       }
       interrupts();
}
void loop()
{
       ;
}

When I run this code I am not getting any errors, but in high frequency (above 400 Hz) Ihave a problem. When I tested at 0 degrees, this code produced this output:

400 Hz 1.152 degree
500 Hz 1.440 degree
600 Hz 1.727 degree
700 Hz 2.015 degree
800 Hz 2.304 degree
900 Hz 2.592 degree
1 kHz  2.880 degree
2 kHz  5.760 degree
3 kHz  8.649 degree
.
.
.
10 kHz 28.8 degree

Each frequency has lowest degree that this code can calculate.

How can I fix this code? Is it possible to calculate the phase shift between two square wave signals this way?


texts: Generating a 38 KHz signal without timers

texts:
I am currently trying to generate a 38 KHz signal for my TSOP4838 (http://www.vishay.com/docs/82459/tsop48.pdf) with an ATtiny84A.

I know the real thing would be to utilize a timer but the ATtiny only has 2 Timers (T0 and T1). Timer1 can not be used because it is already used by other features.

I don't want to transmit actual data to the TSOP4838. I only want to use it as a light barrier (Iknow there are better ICs for that but I am stuck with the ones I already have).

So what I have tried so far is setting up timer0 for my PWM stuff and everything worked IR LED-wise. The delay functions (micros(), millis() etc.) stopped working and prevented me from using my serial communication. I tried to change the code in wiring.c to use a prescaler of 1 instead of 64 by changing the defines but that didn't work out.

I am now stuck with two options I guess:

A: somehow modify timer0 to generate my 38 KHz signal and still provide correct functionality for the timing functions.

B: let timer0 be initialized the way the Arduino wants it and utilize the delay functions to blink the IR LED.

I would prefer A but Google didn't give me a solution. Maybe some of the gurus around here could help?

If A is not possible can somebody give me a hint how to "bit bang" the IR LED with delay? (I guess that is a silly question but I can't figure it out at the moment :()


texts:
I want to write a class that allows the user to attach his own function to a member function that listens for messages coming from a wireless module, so that the user's function can be called depending on the message.

I am thinking about using function pointers but I don't know how it will work since I don't know the user's function parameters, return type and number of functions that will be added.

//sketch.ino

<unknown> (*funcPtr)(<unknown>)[<unknown>];

void receive() {
  message.type = 'o';
  if (message.available()) {
    message.receive();
  }
  switch (message.type) {
    case 'p': {
      Serial.println(p);
      break;
    }
    case 'f': {
      funcPtr[message.funcID](message.parameter1, message.parameter2);
      break;
    }
    default: break;
}

void userFunction1() {
  Serial.println("User function 1");
}

int userFunction2(int x) {
  return x * 2;
}

funcPtr[0] = &userFunction1;
funcPtr[1] = &userFunction2;

void setup() {}

void loop() {
  receive();
}

Is this kind of thing possible?


texts: Is there any difference in the end product when coding the atmel avr using arduino ide and in embedded c are there advantages with embedded c?


texts: Arduino with HC-05 Bluetooth Module | No data will be transmitted

texts:
I've got an Arduino Uno (Elegoo R3) and a Hc-05 bluetooth module. First of all i want to send data with an android app (Bluetooth terminal) to the Arduino and turn pin 13 (LED) on.
My Arduino code:
#include <SoftwareSerial.h>

int state = 0;

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

  pinMode(13, OUTPUT);
}

void loop() {
  if (Serial.available() > 0) {
    state = Serial.read();

    if (state == '1') {
      Serial.println("Turned on LED");

      digitalWrite(13, HIGH);
    }

    if (state == '0') {
      Serial.println("Turned off LED");

      digitalWrite(13, LOW);
    }
  }
}

The RX and TX pins I have hooked up with the HC-05 but if I connect my smartphone with the HC-05 and type in a 1 or a 0 nothing happens. If I type a 1 or a 0 in my serial monitor on my computer (hooked up via usb to my arduino) it turns the LED on/off. The RX and TX lights also flashes one time. The bluetooth terminal app recognises all what was sent via serial monitor on pc and displays it in the app. But if I type something in the app, it won't flip the LED or show me some "Turned off LED" or "Turned on LED".
I also tried different apps from the PlayStore but all of them didn't work.
Does someone has an idea how I could fix this? Thank you for your answers.
EDIT: A drawing how my Arduino is connected to my HC-05 https://imgur.com/a/FtUz5So


texts: Can I control 4 DC Brushless motors with arduino uno and Adafruit motor shield?

texts: I need to control 4 DC brushless motors. I have no experience with arduino or coding. After some research the cleanest setup seems to be using the Adafruit motor shield, however the motors I'm using have 5 wires. Can I still make this work? I envision the motors being connected to the shield via the negative and positive power wires, but what do I do with the rest?  Thank you in advance.


texts:
I'm planing to use the ESP8266 to create a web server as a start. My set up is: Arduino nano- Esp8266- Logic level converter  as shown in the diagram.

After I connected everything my device doesn’t recognize the Arudion’s USB serial port, but when I disconnect everything from the breadboard and connect the Arduino alone it show up as COM3 and when I put the circuit back again and hock up the USB to my device it no longer show up.
I’m having the issue on both win 10 and mac.
Whenever I connected the usb cable to my computer the ESP8266 flashes a light for ones.


texts: Cycling LED's for specific time period with millis()

texts:
My goal in pseudo code is :

only LED-6 HIGH for 6 seconds, then only LED-7 HIGH for 2 seconds, then only LED-8 HIGH for 4 seconds, then restart

This is very easy with delay(), but I struggle with millis(). Here is my code. Only led 7 and 8 blinks.

unsigned long currentTime;
unsigned long previousTime1 = 0;
unsigned long previousTime2 = 0;
unsigned long previousTime3 = 0;
unsigned long interval1 = 6000;
unsigned long interval2 = 2000;
unsigned long interval3 = 4000;

void setup() {

  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);

}

void loop() {

  currentTime = millis();

  if (currentTime - previousTime1 >= interval1){
    previousTime1 = currentTime;
    digitalWrite(6, HIGH);
    digitalWrite(7, LOW);
    digitalWrite(8, LOW);
  }

  if (currentTime - previousTime2 >= interval2){
    previousTime2 = currentTime;
    digitalWrite(6, LOW);
    digitalWrite(7, HIGH);
    digitalWrite(8, LOW);
  }

   if (currentTime - previousTime3 >= interval3){
    previousTime3 = currentTime;
    digitalWrite(6, LOW);
    digitalWrite(7, LOW);
    digitalWrite(8, HIGH);
  }
}


texts: Arduino Obstacle Avoiding Shield controlor motor L293D

texts:
I am a beginner with Arduino . I wanted to make a Arduino obstacle avoiding so I commanded last week an L293D Shield Motor Driver and I don't know if what I receive is the good ithem . First picture is how it looks on the site and the second picture is what I get .

I saw that if you search for this motor you get resolts for both motor , but they are not the same . And I saw in this tutorial , this persone use a motor as mine https://www.youtube.com/watch?v=ydDvoknlJ9M and than he switch to the motor in the first picture . Questions : This motors are the same ? Should I request a return ? If they are the same , how can I add ... I don't know how to say ... that thing that is in the third picture ?

Again , I am a beginner and I would apereciate if someone can help me .


texts: PC not recognizing Arduino when working with a class and MIDIUSB library

texts:
I've recently bought an Arduo Due to create some sort of a Midi controller together with the MIDIUSB library.

I have create a simple a test program with 1 potentiometer (without the use of a class) to test the MIDIUSB library and everything works fine, so I decided to expanded my program to make it work with more than 1 potentiometer (with the use of a class).

However my pc stopped recognizing my Arduino as a MIDI device with my updated code. When I upload my previous example code it all works fine. I get no compile errors or whatsoever.
I don't understand what I'm doing wrong.
If anybody could explain me what I'm doing wrong or could give me a solution you would be a hero since I can't really work further if this issue doesn't get resolved.
Thanks!

Here is my code for Custom_MIDI_controller_V2.ino:

#include "MIDIUSB.h"
#include "Class.h"
#define TOLERANCE 8

byte NUMBER_POTS = 5;

Pot PO0(A0, 1, 14);
Pot PO1(A1, 1, 15);
Pot PO2(A2, 1, 16);
Pot PO3(A3, 1, 17);
Pot PO4(A4, 1, 18);

Pot *POTS[] = {&PO0, &PO1, &PO2, &PO3, &PO4};

void setup() {

}

void loop() {
  for (int i = 0; i < NUMBER_POTS; i++) {
    int potValue = POTS[i]->getValue();
      if(potValue != 255) {
        controlChange(POTS[i]->_channel, POTS[i]->_control, potValue);
        MidiUSB.flush();
      }
   }
}

void controlChange(byte channel, byte control, byte value) {
  midiEventPacket_t event = {0x0B, 0xB0 | channel, control, value};
  MidiUSB.sendMIDI(event);
}

Here is my Class.cpp code:

#include "Arduino.h"
#include "Class.h"

#define TOLERANCE 8

Pot::Pot(int pin, int channel, int control) {
  _pin = pin;
  _channel = channel;
  _control = control;
  _value = analogRead(_pin);
  _oldValue = _value - 10;
}

int Pot::getValue() {
  int diff = abs(_value - _oldValue);
  if(diff > TOLERANCE)
  {
    _oldValue = _value;
    return map(_value, 0, 1023, 127, 0);
  } else {
    return 255;
  }
}

And this is my header Class.h code:

#ifndef Class_h
#define Class_h
#include "Arduino.h"

class Pot
{
  public:
    Pot(int pin, int channel, int control);
    int getValue();
    int _pin;
    int _channel;
    int _control;
    int _value;
    int _oldValue;
};

#endif


texts: What is the purpose of F() and FPSTR() in ESP8266WebServer -> FSBrowser?

texts:
I found this code sample from the FSBrowser (Flash File System) example in the ESP8266WebServer library:
replyServerError(FPSTR(FS_INIT_ERROR));
replyBadRequest(F("DIR ARG MISSING"));

I was a bit confused at what F() and FPSTR() do, so I looked up the source (WString.h) and found this:
#define FPSTR(pstr_pointer) (reinterpret_cast<const __FlashStringHelper *>(pstr_pointer))
#define F(string_literal) (FPSTR(PSTR(string_literal)))

Which raised more questions. How does this code work and what does this added complexity gain over just using char* or String as is?
EDIT: Added Metrics
Here's the memory usage before and after I removed all 25 instances of F() from a file system class, measured by PlatformIO Project Inspector:

With F()
Without F()
Difference

RAM Used
29,488 bytes (36.0%)
29,792 bytes (36.4%)
+304 bytes

Flash Used
355,312 bytes (34%)
355,188 bytes (34.0%)
-124 bytes

Total (uncompressed)
359,472 bytes
359,344 bytes
-128 bytes

Adding F() decreases RAM usage by 1% and increases Flash by around half that. That's for a single class with 25 instances of F(). For a program containing 20x this code, the difference can be significant. However, you'll run out of RAM before you get there. The space savings will be limited to around 5-8%. Still not nothing.


texts: How to connect a a three state switch (ON-OFF-ON) to arduino?

texts:
I have created a car that can detect obstacle and change its direction, but now I want to add a bluetooth module to control it and I want to switch between the two circuits using a three state switch (ON-OFF-ON), so how can I do that and how can I upload two different codes on the arduino.
Here is a fritzing diagram, (the pins for the bluetooth will be changed).

Sensor:

Bluetooth:

And here is the code for the sensor:

   #define echopin  8 // echo pin
   #define trigpin 9 // Trigger pin

   int maximumRange = 30;
   long duration, distance;

    void setup() {
        Serial.begin (9600);
        pinMode (trigpin, OUTPUT);
        pinMode (echopin, INPUT );
        pinMode (4, OUTPUT);
        pinMode (5, OUTPUT);
        pinMode (13, OUTPUT);
        pinMode (6, OUTPUT);
        pinMode (7, OUTPUT);
    }

    void loop ()
    {
        digitalWrite(trigpin,LOW);
        delayMicroseconds(2);

        digitalWrite(trigpin,HIGH);
        delayMicroseconds(10);

        duration=pulseIn (echopin,HIGH);

        distance= duration/58.2;
        delay (50);
        Serial.println(distance);
    }

        if (distance >= 30 ){
            digitalWrite(4,HIGH);
            digitalWrite(5,HIGH);
            digitalWrite(6,LOW);
            digitalWrite(7,LOW);
            delay (200);
        }
        else if (distance >=15 && distance <= 25) {
            digitalWrite (4,HIGH);
            digitalWrite (5,LOW);
            digitalWrite (6,LOW);
            digitalWrite (7,LOW);
            delay (1000);
        }
        else if (distance < 15){
            digitalWrite (4, LOW);
            digitalWrite (5, LOW);
            digitalWrite (6,HIGH);
            digitalWrite (7,HIGH);
            delay (1000);
            digitalWrite (4,LOW);
            digitalWrite (5,HIGH);
            digitalWrite (6,LOW);
            digitalWrite (7, LOW);
            delay (1000);
        }
    }

Please write in the most details and write any code as I am still a beginner.


texts:
I am trying to get the current speed of my car using the GPS Neo, but my code always returns that the speed from the GPS is invalid. The green led of the GPS Neo is blinking. What is the isValid() function? Below the code:

#include <EEPROM.h>
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
//LOAD WIRE LIB
#include<Wire.h>
static const int RXPin = 10, TXPin = 9;
static const uint32_t GPSBaud = 9600;
// The TinyGPS++ object
TinyGPSPlus gps;
// The serial connection to the GPS device
SoftwareSerial ss(RXPin, TXPin);
//***************************************************************
int aux = 0;
int vel_prog = 20; //programed SPEED
float vel_atual;//  actual SPEED
int val_inc = 0;
int val_dec = 0;
int led0 = 2;//led pin
int led20 = 3;//led pin
int led60 = 4;//led pin
int led80 = 5;//led pin
int ledsinal = 6;//led pin
int buzzer = 7;//buzzer pin
int incrementa = 8;//button pin
//****************************************************************
void setup()
{
  Serial.begin(115200);
  ss.begin(GPSBaud);
  pinMode(incrementa, INPUT);
  pinMode(led0, OUTPUT);  // declare LED as output
  pinMode(led20, OUTPUT);  // declare LED as output
  pinMode(led60, OUTPUT);  // declare LED as output
  pinMode(led80, OUTPUT);  // declare LED as output
  pinMode(ledsinal, OUTPUT);  // declare LED as output
  pinMode(buzzer, OUTPUT);  // dbuzeer
  delay(10);
}

void loop()
{

  smartDelay(1000);
  val_inc = digitalRead(incrementa);  // read increment button
  if (val_inc == 1) {
   if (vel_prog > 80) {
      vel_prog = -20;
   }
      vel_prog = vel_prog + 20;
  }

  if (vel_prog == 0) {
    digitalWrite(led0,HIGH);
    digitalWrite(led20,LOW);
    digitalWrite(led60,LOW);
    digitalWrite(led80,LOW);
  } else if (vel_prog == 20) {
    digitalWrite(led0,LOW);
    digitalWrite(led20,HIGH);
    digitalWrite(led60,LOW);
    digitalWrite(led80,LOW);
  } else if (vel_prog == 60) {
    digitalWrite(led0,LOW);
    digitalWrite(led20,LOW);
    digitalWrite(led60,HIGH);
    digitalWrite(led80,LOW);
  } else if (vel_prog == 80) {
    digitalWrite(led0,LOW);
    digitalWrite(led20,LOW);
    digitalWrite(led60,LOW);
    digitalWrite(led80,HIGH);
  }

  if (gps.speed.isValid()){
  Serial.print(gps.speed.kmph());
  } else {
  Serial.print("*");
  }

 if (gps.speed.isValid()) {
  if (gps.speed.kmph() >= vel_prog && aux == 0) { //comparacao da velocidades
    digitalWrite(ledsinal, HIGH);  // turn LED OFF
    tone(buzzer, 2200);
    delay(5000);
    digitalWrite(ledsinal, LOW);  // turn LED OFF
    noTone(buzzer);
    aux = 1;
  }
}
}

static void smartDelay(unsigned long ms)
{
  unsigned long start = millis();
  do
  {
    while (ss.available())
      gps.encode(ss.read());
  } while (millis() - start < ms);
}


texts: Error "avr-g++: error: CreateProcess: No such file or directory" When Compiling Script

texts:
Whenever I try to compile a script, the Arduino IDE throws the error avr-g++: error: CreateProcess: No such file or directory. I've already tried reinstalling the IDE, changing the board version in the board manager to 1.6.21, and deleting the Arduino15 folder under AppData/Local/Arduino15.
This problem appeared suddenly - one compilation worked, and two minutes later, nothing would compile - and occurs across all scripts that I've tried.

I'm working from Windows 10 and compiling for an Arduino Uno.


texts: How to enable TIMER/COUNTERS of arduino uno with a push button?

texts:
This is my code for stopwatch. I want the timer to start when a push button is pressed.

#include <LiquidCrystal.h>
#define PIN 2

const uint16_t load = 0;
volatile int  sec=0;
unsigned int minute =0, hour = 0;
volatile bool buttonPressed = false;

LiquidCrystal lcd(13,12,11,10,9,8);

void setup()
{
  pinMode(PIN,INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(PIN), timecount, CHANGE);
  lcd.begin(20,4);
}

ISR(TIMER1_COMPA_vect)
{
  sec++;
}

void loop()
{
  if(buttonPressed)
  {
    buttonPressed = false;
  }
  if(sec > 59)
  {
    minute++;
    sec = 0;
  }
  if(minute > 59)
  {
    hour++;
    minute = 0;
  }
  if(hour<=9999){
    lcd.setCursor(4,0);
    lcd.print("Stopwatch");
    lcd.setCursor(3,1);
    lcd.print("hhhh : mm : ss");
    char buf[20];
    sprintf(buf,"%04d : %02d : %02d",hour,minute,sec);
    lcd.setCursor(3,2);
    lcd.print(buf);
  }
}

void timecount()
{
  buttonPressed = true;
  noInterrupts();
  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1  = 0;
  OCR1A  = 62500 - 1;
  TCCR1B = _BV(WGM12)
         | _BV(CS12);
  TIMSK1 = _BV(OCIE1A);
  interrupts();
}

The timer is getting enabled without even pressing the pushbutton. Any suggestion?


texts: Rfid stops scanning after wrong card scanned

texts:
My Rfid reader stops scanning cards after scanning the wrong rfid card. It doesn't scan it anymore after turning off the relay. *It turns on the relay if my rfid card is the right one

#include <SPI.h>
#include <MFRC522.h>

#define SS_PIN 10
#define RST_PIN 9
#define relay 2
MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.
int touchPin = 8;
unsigned long previousMillis = 0;        // will store last time LED was updated
unsigned long tacc = 5000UL;           // interval at which to blink (milliseconds)
boolean opened = false;
void setup()
{
  pinMode(touchPin, INPUT);
  pinMode(relay, OUTPUT);
  digitalWrite(relay, HIGH);
  Serial.begin(9600);   // Initiate a serial communication
  SPI.begin();      // Initiate  SPI bus
  mfrc522.PCD_Init();   // Initiate MFRC522
  mfrc522.PCD_SetAntennaGain(mfrc522.RxGain_max);
  Serial.println("Approximate your card to the reader...");
  Serial.println();
}
void loop()
{
  unsigned long currentMillis = millis();
  int touchValue = digitalRead(touchPin);
  if (touchValue == HIGH) {
    digitalWrite(relay, HIGH);
  }
  // Look for new cards
  if ( ! mfrc522.PICC_IsNewCardPresent())
  {
    return;
  }
  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial())
  {
    return;
  }
  //Show UID on serial monitor
  Serial.print("UID tag :");
  String content = "";
  byte letter;
  for (byte i = 0; i < mfrc522.uid.size; i++)
  {
    Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
    Serial.print(mfrc522.uid.uidByte[i], HEX);
    content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
    content.concat(String(mfrc522.uid.uidByte[i], HEX));
  }
  Serial.println();
  Serial.print("Message : ");
  content.toUpperCase();
  if (content.substring(1) == "72 02 EF E9" ) {
  Serial.println("Authorized access");
    digitalWrite(relay, LOW);
    opened = true;
  }
  if (((unsigned long)(currentMillis - previousMillis) >= tacc) && (opened== true)) {
  digitalWrite(relay, HIGH);
    previousMillis = currentMillis;
    opened = false;
  }
}


texts: Increasing analogread speed on the Arduino Uno

texts:
I want to transfer data from my smartphon to the Arduino by using the audio jack of my smartphone. For this I need verry high reading frequencys.

I have used

bitClear(ADCSRA,ADPS0);
bitSet(ADCSRA,ADPS1);
bitClear(ADCSRA,ADPS2);

to boost analogread to ~10microseconds, which would be enough. But somehow I am still wasting 5.4 ms at the beginning of the transmission.

The only thing between signal start and first analogread is a start of a for loop:

while(analogRead(A0)<50) (true); //wait for start of transmission
for(i = 0; i<500;i++){
data[i]=analogRead(A0);
}

But does starting a for loop take 5.4 ms?
Do you have any ideas?


texts: How to debug an Arduino sketch on a Mac?

texts:
I have 2 Lowpowerlab WaterMote's talking to each other using the 'out of the box' pre-installed sketch that just confirm they're talking to each other. I verified this by opening a COM connection and saw traffic of 'receiving packets...' That was just to show that they are functioning and talking to each other.

Now, using Arduino IDE on Mac OS X 1.9.x (Lion?) I have loaded the WaterMote sketch (found on Github) on the Moteino with the sensor (not the gateway) as it should be. The traffic looks like it's working, except the text being transmitted (number of Gallons) stays the same at 0.02 Gallons.

So... I want to debug the WaterMote sketch, but I do not see an option in my Arduino IDE on Mac OS X. Is there a way to debug sketches using Macs? Searching online shows various and preferred options, but mostly on Windows (of which I don't have any at home).

My current setup

Moteino Gateway (as out of the box) connected to a Raspberry Pi (with ssh enabled)

Connected via USB to the RasPi

Moteino with WaterMote sketch loaded

Connected via USB to the MacBook Pro
Arduino IDE running, but I see strange "[][][]" square output in the Serial connection.
I do not know what to make of this since that text is not in the WaterMote sketch.

Is there a way to debug sketches loaded on Arduino clones using Arduino IDE on Macs?

I found a debugging article:

Visual Micro


texts:
To make LCD display, Pro Mini and ATMega2560 to run on one set of battery for months, appreciate idea and comment.

Which LCD to use?

Which LCD chip controller chip (hide inside the LCD) has better power saving mode?

Which library with functions of power saving and also can put out VERY beautiful per-programmed display, like multiple fonts, different fonts size, some graphics like circle, rectangles, color fills, gradual-color-changing background with text and graphic at 'foreground' (as in PC power point style)?

Under context of

Small Mono chrome 2 lines text display
3 inches mono chrome graphic 128 x 64 or similar
3 inches color graphic, 320 x240 or similar

Many thanks in advance


texts: Why is my text inverted while using U8glib?

texts:
I am displaying text using this code.
#include <U8glib.h>
U8GLIB_SSD1306_128X64 u8g(12, 11, 8, 9, 10);
int Buffer[128];int Buffer2[128];int max=0;

void pageEMG();
void recordEMG();
void pageECG();
void recordECG();
void pageBP();
void recordBP();
void clear_screen();

const int pageCount = 10;
int p;
void (*pages[pageCount])() = {clear_screen,recordEMG,pageEMG,clear_screen,recordECG,pageECG,clear_screen,recordBP,pageBP,clear_screen};
int duration [pageCount] = { 100,5000,10000,100,5000,10000,100,5000,10000,100};
void setup() {

  u8g.setFont(u8g_font_unifont);
  u8g.setColorIndex(1);
  p = 0;
  Serial.begin(9600);

}

void loop()
{
u8g.firstPage();
  do {
    (*pages[p])();
  } while( u8g.nextPage() );
  delay(duration[p]);
  p = p+1;
  if (p == pageCount)
    p=0;
}
void recordEMG(){
for(int x=0;x<128;x++)
{
Buffer[x]=analogRead(A2)*.091;
Serial.println(Buffer[x]);
delay(35);
}
u8g.drawStr( 0, 20, "Reading EMG...");
}
void pageEMG() {

for(int x = 0;x < 127;x++)
{
u8g.setFont(u8g_font_unifont);
u8g.drawStr( 0, 20, "EMG");
u8g.drawLine(x, Buffer[x], x+1, Buffer[x+1]); //OP to OLED for BP

}}
void recordECG(){
for(int x=0;x<128;x++)
{
Buffer[x]=analogRead(A0)*.08;
Serial.println(Buffer[x]);
delay(35);
}
u8g.drawStr( 0, 20, "Reading ECG...");
}
void pageECG() {

for(int x = 0;x < 127;x++)
{
u8g.setFont(u8g_font_unifont);
u8g.drawStr( 0, 20, "BP");
u8g.drawLine(x, Buffer[x], x+1, Buffer[x+1]); //OP to OLED for BP

}}
void recordBP(){
for(int x=0;x<128;x++)
{
Buffer[x]=analogRead(A1)*.091;
Serial.println(Buffer[x]);
delay(35);
}
u8g.drawStr( 0, 20, "Reading BP...");
}
void pageBP() {

for(int x = 0;x < 127;x++)
{
u8g.setFont(u8g_font_unifont);
u8g.drawStr( 0, 20, "BP");
u8g.drawLine(x, Buffer[x], x+1, Buffer[x+1]); //OP to OLED for BP

}}
void clear_screen(void) {
  u8g.setColorIndex(0);
u8g.drawBox(1, 1, 64, 128);
}

And my text is coming inverted.
Why is this happening?


texts:
I want to use a switch and an Arduino to "power" a 24 V DC appliance and I am not really sure what relay to use for this.
So I need the relay to be able to switch it on and off, but I have not really been able to find any that do it for 24 V DC, only for mains.

Can I use a mains relay or is there special one for 24 V.
I have all tried searching for the problem but haven't really found anything that helps. I'm probably searching for the wrong thing.

I am new just started learning electronics and stuff.
Thanks.


texts:
My Arduino nano make weired thing...
The TX LED is on when i define a Variable and a digital Pin as output. Do you now if it is a error in the code? If I upload a clear new sketch the LED is off.

~Nico

Code:

int ok = 1;
int err = 0;
int x1 = 2;
int x2 = 3;
int x3 = 4;
int x4 = 5;
int x5 = 6;
int x6 = 7;
int y1 = 8;
int y2 = 9;
int y3 = 10;
int y4 = 11;
int y5 = 12;
int y6 = 13;
int value1 = digitalRead(14);
int value2 = digitalRead(15);
int value3 = digitalRead(16);
int test = digitalRead(17);

void setup() {
  pinMode(0, OUTPUT);
  pinMode(1, OUTPUT);
  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(4, OUTPUT);
  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
  pinMode(10, OUTPUT);
  pinMode(11, OUTPUT);
  pinMode(12, OUTPUT);
  pinMode(13, OUTPUT);
  pinMode(14, INPUT);
  pinMode(15, INPUT);
  pinMode(16, INPUT);
  pinMode(17, INPUT);
}

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

}


texts: Water level Detection using Ultrasonic Sensor and arduino

texts: I'm making a water level detector to control my motor which supplies water in water tank and for that I'm going to use ultrasonic sensor to be attached to tank lid. My question is whether the vapor arising from water inside the tank hamper the overall working of ultrasonic sensor and/or it may be damaged permanently. I can cover complete ultrasonic sensor using hot glue stick but cannot cover its diaphragm as it will block sound waves. Please suggest something.


texts: Arduino board to control microwave oven?

texts:
So I've taken apart an old microwave oven with a touch-sensitive LCD screen. I understand that I could die from playing around with this, so I've disconnected the high-voltage transformer and the magnetron. I'm also not going to remove any of the safety switches like the door switch. My question is, how is the microwave controlled? I'm thinking there is a computer chip somewhere in the circuit, and I'm looking to replace it with an Arduino board plus some extras, like AC relays and such. I'm curious as to how the microwave oven controls its functions, like power level, cooking time, and the beeping. Any advise as to how I could get started interfacing?

Is the power level controlled by PWM by any chance? Can you PWM alternating current?


texts: Is there any way to download a sketch from an Arduino?

texts: I made a sketch, but then I lost it. However, I uploaded it to the Arduino before losing it. Is there any way I can get it back?


texts:
I have an ESP8266 Node MCU and am learning to use its wifi capabilities. In my home I have a router provided by my ISP that runs a network we'll call 'network1'. I also have an Eero mesh network that runs in the house, called 'network2'.
When I upload the following minimal example and use network1,

my 8266 device connects to network1 (the messages in the serial monitor confirm this) and
I can use my phone and laptop to connect to the 8266 - i.e., I can put the IP into my browser and see a webpage telling me 'Hello World'.

However, I have trouble with network2, the Eero network.

I can connect my 8266 device to network2 (the messages in the serial monitor confirm this)
but
I can't connect to the 8266 device with my phone/laptop. (Yes, I switch these over to network2 first.) I put the new IP into my browser and I am told the page is taking too long to respond.

I haven't done anything special with my network1 router; things just worked. With network2, I've tried various settings with my Eero - given the 8266 a static IP address, enabled port forwarding (on port 80) and established a firewall rule for it, but nothing works.
I can run many different programs through network1, and nothing works on the Eero network. Any suggestions on getting things to work?
My minimal working example:
#include <ESP8266WiFi.h>

const char* ssid = "network1"; // or 'network2'
const char* password = "thepassword"; // real password used in code

WiFiServer server(80); //just pick any port number you like

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

  // Connect to WiFi network
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");

  // Start the server
  server.begin();
  Serial.println("Server started");

  // Print the IP address
  Serial.println(WiFi.localIP());
  //gateway = WiFi.gatewayIP();
  Serial.print("GATEWAY: ");
  Serial.println(WiFi.gatewayIP());

  // print your subnet mask:
  //subnet = WiFi.subnetMask();
  Serial.print("NETMASK: ");
  Serial.println(WiFi.subnetMask());
}

void loop() {
  // Check if a client has connected
  WiFiClient client = server.available();
  if (!client) {
    return;
  }

  // Prepare the response
  String s = "HTTP/1.1 200 OK\r\n";
  s += "Content-Type: text/html\r\n\r\n";
  s += "<!DOCTYPE HTML>\r\n\r\n";
  s += "\r\n";
  s+= "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\r\n";
  s+= "<title>ESP Web Server</title>\r\n";
  s+= "\r\n";
  s += "Hello World";
  s += "\n";

  client.flush();

  // Send the response to the client
  client.print(s);
  delay(1);
}


texts:
I have search lots, and finally I was able to get my project moving!
I have learned to create an xml file and get data from it using XMLRequest vía "get".
I'm using a Nodemcu 12e v.1 I believe, have the WiFi and server running. The index.html and xml file are both in a spiff format folder and running!

My question is:
Can Data let's say from a sensor be loaded to the xml file?
If so, can someone guide me in the right direction?
Thank you all!


texts:
I try to flash an ESP12E microcontroller through an FTDI serial converter. It seems like the UART connection is a bit unstable, because when I try to flash it via esptool it often throws "Timed out waiting for packet header" error. Also when I thy to get the flash_id the same error occures at around 50% of the time. The simplier commands like get_mac and chip_id are working well.

I'm using an ESP module with wires soldered to its pads. It is put into a breadboard and it's connected to a USB-UART converter via jumper wires.

What could be the problem?


texts: Looking for a wireless soil moisture sensor

texts: I am new to arduino and have a basic question. I want to build a sprinkler controller system for my lawn which would detect moisture in the lawn soil and automatically starts the sprinkler controller to water the lawn when moisture in the lawn soil reaches a certain level. I am looking for soil moisture sensors that would be installed in the lawn soil and wirelessly transmit the moisture level to my arduino in the house. Any ideas where I can find these sensors?


texts: Error 101 Server Did Not Report Size from OTA Upgrade framework via git hub

texts:
I have tried this video:
ESP8266 Self Update OTA from GitHub
Instruction and made this GitHub repo:
And changed the main code to this type, but I get this error:
HTTP_UPDATE_FAILD Error (-101): Server Did Not Report Size

when the    FirmwareUpdate(); code is running.
So I don't know why GitHub don't answer to the esp8266, as said here:

The error has nothing to do with your sketch. Also, the error code is
not a HTTP 101 error. The problem is that your server does not send
the response header 'Content-Length'

I have some dupt about the bin URL file address which have many dot on the end of it (https://github.com/soheilpaper/ota_github_blink/blob/main/BlinkWithoutDelay.ino.esp8285.bin) on it, could it be the reason for none answering and giving the 101 code form GitHub server!
Any suggestion would be good help to fix this bug.
Update 1:

I have changed the bin file name to this kind :
 BlinkWithoutDelay.ino.esp8285.bin  ---->      BlinkWithoutDelay_ino_esp8285.bin

But I have again the same GitHub 101 error.

Update 2:
Based on the timemage answer, I have changed the address of bin and TXT file by finding the download link of those files form the GitHub. And it has been working by changing the blob part of address to raw, so the bin address changed form https://github.com/soheilpaper/ota_github_blink/blob/main/BlinkWithoutDelay_ino_esp8285.bin to https://github.com/soheilpaper/ota_github_blink/raw/main/BlinkWithoutDelay_ino_esp8285.bin And the https://github.com/soheilpaper/ota_github_blink/blob/main/version.txtto  https://raw.githubusercontent.com/soheilpaper/ota_github_blink/main/version.txt
And now that error has been fixed as you can see below:

Although I gave some dupt about upgrading the main code by getting this output via serial port:
Device already on latest firmware version

And I would check it after some resting!.
Thanks.