texts:
I'm writing a PID program for a simple DC Motor. This motor has an encoder at the bottom which allows me to read motor speed. The goal of the project is to provide a constant speed if there is light friction applied to the motor. Although speed may vary slightly, I can still graph the PWM signal and show the duty cycle increases in response to friction. I've gotten the motor speed and potentiometer to function perfectly, now I'm just stuck on the actual PID part.

The issue I'm having is that whenever I set my SET pin high, the motor completely shuts off. I don't understand why because I'm sending it values in that while loop which should be sufficient to initiate the compensation

Here is my code:

#include "TimerOne.h"
#include <PID_v1.h>

int counter=0;
//Polarity
const int IN1 = 11;
const int IN2 = 10;

volatile float pot=0;
//PWM Signal and Analog from the Potentiometer
const int POT = 0;
const int ENA = 6;

const int SET = 12;

int rotation;

double Setpoint, Input, Output;
double Kp=1, Ki=1, Kd=1;

PID myPID(&Input, &Output, &Setpoint, Kp, Ki, Kd, DIRECT);

void docount()  // counts from the speed sensor
{
  counter++;  // increase +1 the counter value
}

//This takes the docout() counter and calculates how many holes its read to give rotations per second
void timerIsr()
{
  Timer1.detachInterrupt();  //stop the timer
  Serial.print("Motor Speed: ");
  rotation = (counter / 31);  // divide by number of holes in Disc
  Serial.print(rotation,DEC);

  Serial.println(" Rotation per second");
  counter=0;  //  reset counter to zero
  Timer1.attachInterrupt( timerIsr );  //enable the timer
  Serial.print("pot = ");
  Serial.print(pot);

  Serial.print("\n");

}

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

  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  pinMode(SET, INPUT);
  Timer1.initialize(1000000); // set timer for 1sec
  attachInterrupt(0, docount, FALLING);  // increase counter when speed sensor pin goes High
  Timer1.attachInterrupt( timerIsr ); // enable the timer

  myPID.SetMode(AUTOMATIC);
  myPID.SetSampleTime(10);
}

void loop()
{
  // This bit is how you convert the pot values to manually control the fan
  pot=analogRead(POT)/4.01569;
  analogWrite(ENA, pot);

  // This basically acts as a push button. If the SET pin is HIGH it initiates the PID and whatever
  // the current rotation and pot setting are, they're used to send to the myPID function above to
  // maintain current operating values
  while (digitalRead(SET) == HIGH)
  {

      Setpoint = rotation;
      Input = pot;
      myPID.Compute();
      analogWrite(ENA, Output);
      digitalWrite(10, HIGH);  // set rotation of motor to Clockwise
      digitalWrite(11, LOW);

  }
  digitalWrite(10, HIGH);  // set rotation of motor to Clockwise
  digitalWrite(11, LOW);

  delay (50);
}


texts: I have 2 sketches with same RTC DS1307 but when I combine the 2 sketches it gives errors

texts:
I have 2 sketches one is pixel clock with RTC ds 1307 and the other is 7 Segment with DHT 11, I want to merge the two into one but it is giving errors for rtc.
sketch for pixel clock
#include <Wire.h>
#include <RTClib.h>
#include <Adafruit_NeoPixel.h>

#define PIN 6
#define PIXEL 60

Adafruit_NeoPixel strip = Adafruit_NeoPixel(PIXEL, PIN, NEO_GRB + NEO_KHZ800);

RTC_DS1307 RTC; // Establish clock object
DateTime Clock; // Holds current clock time

byte hourval, minuteval, secondval;

void setup() {
 Serial.begin(9600);
  Wire.begin();          // Begin I2C
  RTC.begin();   // begin clock

    if (! RTC.isrunning()) {
//  Serial.println("RTC is NOT running!");
  // following line sets the RTC to the date & time this sketch was compiled

  }

//  RTC.adjust(DateTime(__DATE__, __TIME__));
  strip.begin();
  strip.show(); // Initialize all pixels to 'off'
  strip.setBrightness(20);

}

sketch for 7 segment
#include <Time.h>        //Time Library
#include <TimeLib.h>
#include <DS1307RTC.h>   //Real Time Clock Library
#include <Wire.h>        //Auxiliary Library for DS1307RTC (Real-Time Clock) - Pins to Arduino UNO: A4 (SDA), A5 (SCL)
#include <DHT.h>         //Temperature and Humidity Library

#define DHTPIN 8         //Sensor DHT11  conected to the pin 8 on Arduino

// Definition of what DHT sensor type you are using
#define DHTTYPE DHT11   // DHT 11
//#define DHTTYPE DHT22   // DHT 22 (AM2302), AM2321
//#define DHTTYPE DHT21   // DHT 21 (AM2301)

DHT dht(DHTPIN, DHTTYPE);

int clockPin = 13; // Pin 13 of Arduino connected in the pin 11 of 74HC595 (Clock)
int latchPin = 10; // Pin 10 of Arduino connected in the pin 12 of 74HC595 (Latch)
int dataPin = 11; // Pin 11 of Arduino connected in the pin 14 of 74HC595 (Data)

int hora, minuto, temp, umid;
int unidadeHora, unidadeMinuto, dezenaHora, dezenaMinuto;
int unidadeTemp, dezenaTemp, unidadeUmid, dezenaUmid;
unsigned long ti;
int brightness; // Brightness of display (Min=1 / Max=20)
int k;

//Digits Matrix - 0 a 9
byte num[] = {
  B01111110, // Zero
  B00110000, // One
  B01101101, // Two
  B01111001, // Three
  B00110011, // Four
  B01011011, // Five
  B01011111, // Six
  B01110000, // Seven
  B01111111, // Eight
  B01111011, // Nine
};

void setup() {

  pinMode(latchPin, OUTPUT); // Define the 3 digital pins as output
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);

  dht.begin();

  setSyncProvider(RTC.get);   // Update the time with data of RTC (Real Time Clock)
  setSyncInterval(300);       // Set the number of seconds between re-sync

  //setTime(hours, minutes, seconds, days, months, years);
  //setTime(15, 05, 00, 13, 02, 2016);
  //RTC.set(now());           // Set the RTC time

  brightness = 15; // Set the brightness of display (Min=1 / Max=20)

}

error in the
void loop{
a function-definition is not allowed here before '{' token

E:\pixel_clock_with_7_segment\pixel_clock_with_7_segment.ino: In function 'void setup()':

pixel_clock_with_7_segment:86:15: error: a function-definition is not allowed here before '{' token

   void loop() {

E:\pixel_clock_with_7_segment\pixel_clock_with_7_segment.ino: At global scope:

pixel_clock_with_7_segment:257:1: error: expected declaration before '}' token

 }

Can anybody help me in merging the two sketches as I am new to Arduino programming?


texts:
I am working on an experiment with the HC-SR04 sound sensor, and i am using it to record the speed of sound. I successfully measured the speed of sound in air, but when measuring it in water, I encountered a small problem. The sound waves emitted by the sensor are both absorbed and reflected off the water. Obviously, the reflected sound waves are the first ones to reach the sensor, and therefore are the ones used for calculating the speed of sound. Is there a way to code the Arduino program in order to ignore the first set of waves and only record the set of waves that were absorbed by the water? I was thinking of increasing the delay time for the pulse, but I'm not sure that would work.

Thanks.


texts:
I'm building a MIDI guitar, using an Arduino, sound synthesising and wood.

To properly know which note I'm pressing, I built a voltage divider with 12 equal resistors (10K). One side is connected at +5V and the other end at GND, so each of the 6 strings connects the right tap to the ADC.
I had just calculated the expected value w/ a bit of math considering I also needed a pullDown resistor(1M) and capacitor for every analog channel to keep the readings stable when no key is pressed.

When measuring with my multimeter the readings are stable, and there are variations of less than 0.02V, and since the difference from tap to tap is about 0.4V that's quite good.

The problem is when reading the 6 channels together: channels supposed to be pulled down to gnd read voltages caused by nearby channels, readings are shaky and similar errors.
This mess disappears on one channel when I connect the multimeter to that one.
Instead of buying 6 multimeters, I figured I could ask you if someone has an idea on why this happens, my guess is on the pulldown resistor, but I'm not sure about Arduino's ADC; I'm also worried about having 6 wires half of a meter each so close, so any other idea on finding the keys is welcome.

EDIT
@EdgarBonet was right, I used 12x220ohm resistors, and at first the results were absolute garbage, then I made it so the code would read each channel about 10 times, discard the readings, wait a millisecond and finally read and store the value. Now it is perfect.
Thanks again.


texts:
I wonder how to calculate pulldown resistor to make interrupt work?
I need to connect 5 buttons to A0 and get pressing event via interrupts.
Using different resistors, finally, I made work only 4 buttons. On 5th interrupt does not fire.
Currently I use the following resistors for the buttons:

R1      Vout
0       5,00
2,7K    4,45
5K      3,70
10K     2,77
22K     1,78

And Pulldown Resistor = 22K.

If pulldown Resistor = 10K I can get event for 1-3 button only.
Looks like the voltage 1,78V is quite low.
But I’d liked make it work with 1V at most.
I use RISING mode.

PS. Arduino Nano


texts: Serve currently uploaded code from Arduino

texts: I'm creating a project where multiple ESP8266 12-E's are connected together. I want to use ArduinoOTA with the HTTP option (described here) and I want to have one ESP be able to send its code to another. I just need to figure out how to get the currently uploaded code in the form of cpp.bin in the Arduino language from the Arduino, without using an external computer, and then serve it (I can figure out the serving part though). How could I go about this?


texts: analogWrite is not working - while trying to control DC motor speed

texts:
I'm trying to control the speed of DC Motor using

Arduino R3
NPN Transistor (2N2222A331)
10k potentiometer
2M ohm resistor
Diode

I'm not using L298N and I'm also not using L293D.

DC motor is running, but the speed of DC motor doesn't seem to change with changes in potentiometer.
Circuit seems to be alright as DC motor is running.

The code is as follows

int potPin = A0;
int motorPin = 9;
int potValue = 0;
int motorValue = 0;

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

void loop()
{
 potValue = analogRead(potPin);
 motorValue = map(potValue, 0, 1023, 0, 255);
 analogWrite(motorPin, motorValue);
 delay(2);
 Serial.print("potentiometer = " );
 Serial.print(potValue);
 Serial.print("t motor = ");
 Serial.println(motorValue);
}

Whenever I tweak the Potentiometer, I can see the relative changes from Arduino  "Serial Monitor" (both Potentiometer values and Motor values), but the speed doesnt seem to change physically.

Things that I tried

tried different combinations of resistors(100,1k,10k,1M,2M ohm) so as to vary voltage that goes to DC Motor
tried to check with different Output pins like 3,5,9

Nothing works, DC motor speed isn't changing.

this leads me - to believe that, my analogwrite isn't working.
please help me understand as to what i'm i doing wrong?

The Circuit is as follows


texts: XL335B accelerometer reports false readings

texts:
I'm using an XL335B accelerometer in a GY-61 breakout board. I'm powering the device using the UNO's built-in 3.3V power supply. The following code should convert the readings to m/s² (SI); however, it returns (-0.43|-0.52|-5.83) instead of the expected (0|0|-9.81) when lying untouched.

Code:

const float CYCLE_LENGHT_MILLIS = 1000;

// REFERENCE_VOLTAGE 5 & STEP_COUNT 1024
// => VOLTAGE_STEP 0.0048828125
// MAX_ACC_VOLTAGE 3.3
// => MAX_ACC_VOLTAGE_STEP 675.84
// MIN_ACC_VOLTAGE 1.65 = 0.5 MAX_ACC_VOLTAGE
// => MIN_ACC_VOLTAGE_STEP 337.92
// MAX_ACC_MEASUREMENT 29.43 = 3g

// acceleration = (read()-MIN_ACC_VOLTAGE_STEP) * MAX_ACC_MEASUREMENT/(MAX_ACC_VOLTAGE_STEP-MIN_ACC_VOLTAGE_STEP)
//This can be simplified to: acceleration = read()*j - k
// => j = MAX_ACC_MEASUREMENT / (MAX_ACC_VOLTAGE_STEP-MIN_ACC_VOLTAGE_STEP)
// => k = MIN_ACC_VOLTAGE_STEP * j

const float j = 29.43/(675.84-337.92);
const float k = 337.92*j;

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

void loop(){
  Serial.print("(");
  Serial.print(analogRead(0) * j - k);  //X-AXIS
  Serial.print("|");
  Serial.print(analogRead(1) * j - k);  //Y-AXIS
  Serial.print("|");
  Serial.print(analogRead(2) * j - k);  //Z-AXIS
  Serial.println(")");
  delay(CYCLE_LENGHT_MILLIS);
}


texts:
I have LED bar graph on pins 2-11. Eventually I want to use a voltage divider to figure out the amount of voltage left in a power supply. Currently, this script should set the number of LEDs on the bar graph based on round((v_actual/v_reference)*10), I am just using some placeholder numbers in the mean time to test this portion of the script e.g. v_actual of 5 and v_reference of 10. However, the convert variable keeps printing 0. I've checked that the other variables were passing and they are. What is the issue here?

#include <Wire.h>

int ledBarNum = 10;    // # of leds
int vref = 10;     // max voltage of power supply

void setup(){
  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);
}

void loop() {

  ledBarSetup(5);
}

void ledBarSetup(int v) {

  // logic vref=8; vactual or v = 4; (4/8)*10 = 2
  // e.g. number of leds we need to light up to represent the total amt left

  Serial.println(v);
  Serial.println(vref);

  int convert = round((v/vref)*10);

  Serial.println(convert);

  ledBar(convert);

}

void ledBar(int n) {

  int startingPin = 2;

  for (int thisPin = 2; thisPin < ledBarNum; thisPin++) {

    if (thisPin <= n) {

      digitalWrite(thisPin, HIGH);

    } else {

      digitalWrite(thisPin, LOW);

    }

  }

}


texts: UNO R3 + WiFi ATmega328P+ESP8266 (32Mb memory) USB-TTL CH340G For Arduino Uno - External ESP8266 Pins

texts:
This board have pins to ESP8266's GPIOs.
What is Tout pin ?
On the back of the board it label pins :GPIO12, GPIO02, and another GPIO02 ? a continuity test shows that they are not connected. So what is it ?


texts: I got this ILI9341 *i 'm not sure * from ebay and i cant manage to use any librarys

texts:
I have Arduino Uno R3 i can't mange to upload code for the display .
I tried to use librays from this  http://www.buydisplay.com/default/arduino-2-4-inch-tft-lcd-touch-shield-li9341-library-for-mega-due-uno

After uploading

In file included from C:\Users\radum\Downloads\Libraries-Examples_RTP_for-2.4-2.6-2.8-3.2-inch (1)\Libraries-Examples_RTP_for-2.4-2.6-2.8-3.2-inch\Examples_RTP-Software-SPI_2.4inch-3.2inch\Graphic_Test\Graphic_Test.ino:8:0:

C:\Users\radum\Documents\Arduino\libraries\UTFT/UTFT.h:200:42: fatal error: hardware/avr/HW_AVR_defines.h: No such file or directory

#include "hardware/avr/HW_AVR_defines.h"

compilation terminated.

exit status 1
Error compiling for board Arduino/Genuino Uno.

But the file exists in the specified folder .
What should i do?


texts:
I want to send data to my php server using sim900 module but I am unable to initialize http service on sim900.

code:

#include <SoftwareSerial.h>
SoftwareSerial gprsSerial(8, 9);

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

  Serial.println("Con");
  delay(2000);
  Serial.println("Done!...");
  gprsSerial.flush();
  Serial.flush();

  // See if the SIM900 is ready
  gprsSerial.println("AT");
  delay(1000);
  toSerial();

  // SIM card inserted and unlocked?
  gprsSerial.println("AT+CPIN?");
  delay(1000);
  toSerial();

  // Is the SIM card registered?
  gprsSerial.println("AT+CREG?");
  delay(1000);
  toSerial();

  // Is GPRS attached?
  gprsSerial.println("AT+CGATT?");
  delay(1000);
  toSerial();

  // Check signal strength
  gprsSerial.println("AT+CSQ ");
  delay(1000);
  toSerial();

  // Set connection type to GPRS
  gprsSerial.println("AT+SAPBR=3,1,\"Contype\",\"GPRS\"");
  delay(2000);
  toSerial();

  // Set the APN
  gprsSerial.println("AT+SAPBR=3,1,\"APN\",\"web\"");
  delay(2000);
  toSerial();

  // Enable GPRS
  gprsSerial.println("AT+SAPBR=1,1");
  delay(10000);
  toSerial();

  // Check to see if connection is correct and get your IP address
  gprsSerial.println("AT+SAPBR=2,1");
  delay(2000);
  toSerial();

}

void loop()
{
   // initialize http service
   gprsSerial.println("AT+HTTPINIT");
   delay(2000);
   toSerial();

   // set http param value
   // ToDO : send dynamic value
   gprsSerial.println("AT+HTTPPARA=\"URL\",\"http://www.fohoraayo.000webhostapp.com/?lat=1111&lon=1111\"");
   delay(4000);
   toSerial();

   // set http action type 0 = GET, 1 = POST, 2 = HEAD
   gprsSerial.println("AT+HTTPACTION=0");
   delay(6000);
   toSerial();

   // read server response
   gprsSerial.println("AT+HTTPREAD");
   delay(1000);
   toSerial();

   //gprsSerial.println("");
   gprsSerial.println("AT+HTTPTERM");
   toSerial();
   delay(300);

   gprsSerial.println("");
   delay(10000);
}

void toSerial()
{
  while(gprsSerial.available()!=0)
  {
    Serial.write(gprsSerial.read());
  }
}

output:

Config SIM900...
Done!...
AT

OK
AT+CPIN?

+CPIN: READY

OK
AT+CREG?

+CREG: 0,1

OK
AT+CGATT?

+CGATT: 1

OK
AT+CSQ

+CSQ: 31,0

OK
AT+SAPBR=3,1,"Contype","GPRS"

OK
AT+SAPBR=3,1,"APN","web"

OK
AT+SAPBR=1,1

ERROR
AT+SAPBR=2,1

+SAPBR: 1,1,"xx.xxx.x.x"

OK
AT+HTTPINIT

ERROR
AT+HTTPPARA="URL","http://www.fohoraayo.000webhostapp.com/?lat=AT+HTTPACTION=0

ERROR
AT+HTTPREAD

ERROR
AT+HTTPTERM

ERROR


texts: TCP client readStringUntil only when data exists

texts:
I have the attached script that reads data from a socket server (it is PHP at the server end).
My problem (I think) is that the readStringUntil() needs a test above it, so that it "reads up to \r" only if there is any data being received, otherwise it seems to keep trying to read forever, because when I DO send data, it is received with 1-2 seconds delay.
If I constantly send (properly \r delimited) data without any pause, then it seems to be received instantly (10-20ms or so).
I tried: if (client.available()) { String received_message = client.readStringUntil('\r'); } but it doesn't seem to be the right function, doesn't do anything.
This is ESP32 board, compiler mentioned it found two wifi libraries, one in arduino folder and one in ESP32, it used the second one. This might be relevant to what functions are available.
#include <WiFi.h>

const char* ssid = "MyWiFi";
const char* password =  "1234";

const uint16_t port = 8080;
const char * host = "myserver.example.com";

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

  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println("...");
  }

  Serial.print("wifi connected with IP: ");
  Serial.println(WiFi.localIP());
}

void loop() {

  WiFiClient client;

  if (!client.connect(host, port)) {
    Serial.println("connection to host failed");
    delay(500);
    return;
  }

  Serial.println("connected to server");

  // I assume this is where I need a test like "if any received data exists" >>>

  String received_message = client.readStringUntil('\r');
  Serial.println(received_message);

  // intentional delay doesn't seem to do much
  // when it constantly tries to read for data that is not always there
  delay(100);

  // do I need to disconnect here ?!
  // client.stop();
}

EDIT: my PHP loop looks like this:
do{
    $accept = socket_accept($socket) or die("Could not accept incomming connection");

    // $message_to_send = 'hi there '.microtime(true)."\r";
    // OR
    // get message from memcached variables

    if($message_to_send!=''){

        echo "\nsending: ".$message_to_send;

        socket_send($accept, $message_to_send, strlen($message_to_send), MSG_OOB);
    }

} while (true);


texts: How to send numbers to Arduino UNO via Python 3 and the module serial

texts:
I am new to Arduino (and computer programming in general), so I apologize if this question  looks silly.

Once I set up a basic arduino-LED connection, I have problems sending INTEGERS to arduino through the serial port. I can easily send characters such as 'm', 'o' and so on.. However if I send a number it looks like it simply does not get it.

Here is the Arduino code, ideally it should get a value from the usb port through python or the serial monitor and then adjust the brightness of the LED according to the value. (value must be in range [0,255]).

NOTE: I am using ARDUINO UNO and PYTHON 3

//--------------------------

int LED = 10;
int number;

void setup(){

pinMode(LED,OUTPUT);
Serial.begin(9600);
}

void loop(){

number = Serial.read();
Serial.print(number);
Serial.print('\n');
if(number == -1){
number = 0;
}

else if(number > 255){

number = 255;

}

else if(number < 0){

number = 0;
}

analogWrite(LED,number);
delay(1000);
}

However, when I input a value into the Serial port or through Python, for instance 0, it gives me 48 as answer (which, interestingly, is the ASCII code for 0!) and lights up the LED which is not what should happen since at 0 the LED should be off!!
I am missing something but I cannot find what... Could you please tell me what is wrong?

Here is the code I use in Python:

import serial
import time
try:
    arduino = serial.Serial(port,speed)
    time.sleep(2)
    print("Connection to " + port + " established succesfully!\n")
except Exception as e:
    print(e)

#Note: for characters such as 'a' I set data = b'a' to convert the data in bytes
#However the same thing does not work with numbers...
data = 0
data = arduino.write(valueToWrite)
time.sleep(2)
arduino.close()

what am I doing wrong or misunderstanding? Thank you.


texts: most effective ( progsize/speed ) SD card usage

texts: I am making a project with several modules and libraries involved. I just tested the SD lib example, and got a binary at ~14KB  - way too much. I'd like the SD bits to go below 8KB, since it's just for logging from an NFC and RTC module. I notice some 'stabs' debug bits in my Makefile, and wonder if I could do something with that. Besides that, perhaps the experts here can recommend a smaller library for my SD bits, so I won't exceed my ~27KB flash capacity. I am using the SD example for creating/deleting files. Ask me to clarify if needed.


texts: NodeMCU powered with battery and use WiFi

texts:
I'm running a project with a nodeMCU DevKit and my project runs smooth if I run it connected through the usb wire to the computer.

I need to run my project using battery and I tried with a ICR14500 battery (3.7V and 700mAh). I connected the battery to the Vin pin but the NodeMCU doesn't send the data to the cloud.

When I run it with the battery I have detected some random behaviour, some times the led on the ESP8622 is blinking continiously and the total board power consumption is around 130mA!

Any idea what can be happening?


texts:
I need to know how I can make http posts and http get from Arduino MKR1000 ( act as a client) to a local server.

I made it on Raspberry pi using python like this:

import requests
import json
     url = 'http://192.168.2.139:8040/api/sensor'
     value = {"LDRValue": 200};
     r = requests.post(url, json=value)
     r = requests.get(url)


texts:
I'm using nodemcu and neo6m gps module. I can't send data to firebase. As a library using tinygps++. Can anyone please help me how can i pass data to firebase.

#include <ESP8266WiFi.h>
#include <FirebaseArduino.h>
#include "TinyGPS++.h"
#include "SoftwareSerial.h"

// Set these to run example.
#define FIREBASE_HOST "vessel-monitoring-a21f4.firebaseio.com"
#define FIREBASE_AUTH "EYUZc64JyLMR5cbJc99nZzjah8uwEDxSp3m93Lvr"
#define WIFI_SSID "H17"
#define WIFI_PASSWORD "pass@router"

//GPS
SoftwareSerial serial_connection(4, 0); //tx,rx
TinyGPSPlus gps;// GPS object to process the NMEA data

float latt, lngg;

void setup() {
  Serial.begin(9600);
  serial_connection.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());
  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
}

void loop() {
    while (serial_connection.available()) {
      gps.encode(serial_connection.read());
    }
    if (gps.location.isUpdated()) {
      latt = gps.location.lat();
      lngg = gps.location.lng();
      Serial.println(latt, 6);
      Serial.println(lngg, 6);
      delay(1000);
    }
    char location_str[25]={0};
    sprintf(location_str, "%f, %f", latt, lngg);
    String name = Firebase.push("location", location_str);
    if (Firebase.failed()) {
      Serial.print("setting /location failed:");
      Serial.println(Firebase.error());
      return;
    }
    delay(1000);
}


texts: I'm trying to use an arduino as a controller adapter. How would I get USB-in to get the signal from a usb video game controller?


texts: Why to store a function parameter value in a class private variable?

texts:
I'm just curious, I'm going through a C++ library for the mcu2.4 TFT display.

And this method I notice when I run through C++ libraries.

Which is when a parameter is passed through a function, it's stored in a private variable; like this one:

HCTFT::HCTFT(byte DisplayType)
{
    _Display = DisplayType;

What's the benefit of this method? What's the similar method when I want to do it in C code?


texts: Get the distance to non perpendicular surface

texts:
So I'm using the HC-SR04 modules to get the distance to objects, the problem is that if it's not a perpendicular surface I dont get any reading, and I assume that the reason is that the ultrasounds get reflected in another direction, so they don't come back to the sensor. What's the way to get over this issue?

Thanks in advance


texts: Arduino Due not properly detecting SD card

texts:
I have an SD breakout for my Due that isn't properly detecting the SD card. On one card, it cannot detect at all, and the other it says that the SD isn't formatted with FAT, even though it is. Here is my wiring:

simulate this circuit – Schematic created using CircuitLab

So, I broke out my oscilloscope and started probing lines. One in specific I got worried about, is the SCK line and it's bouncing, specifically from the inductance of the jumpers. This is the SCK line from my scope:

My reaction was to put some buffer caps on there, and so I put 2x 300pf capacitors in parallel for a total of 600pf. This is the waveform as measured after I put in the debouncing caps:

This is much more tolerable, and I can accept this level of bouncing for the SCK line, as I doubt that there will be much misfiring. I upload the SD card test sketch that's on the website, here is the output:

Initializing SD card...Wiring is correct and a card is present.

Card type: SD2
Could not find FAT16/FAT32 partition.
Make sure you've formatted the card

What does The Arduino Due have that makes it hard to detect the card?


texts: need help in code to send sms to multiple contacts using arduino, gsm800, push button

texts:
When button 1 is pressed, the message should be sent to 4 members. But we are receiving the message for one member and after some delay for the other members. But receiving to all members of contacts given in the code (Here numbers are not mentioned)

#include <LiquidCrystal.h>

int ButtonValue1=0;
int ButtonValue2=0;
int ButtonValue3=0;
int ButtonValue4=0;

int Button1=8;
int Button2=9;
int Button3=10;
int Button4=11;
int buz=12;
LiquidCrystal lcd(2, 3, 4, 5, 6, 7);

void okcheck()
{
  unsigned char rcr;
  do{
    rcr = Serial.read();
  }while(rcr != 'K');
}

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

  pinMode(buz,OUTPUT);
  pinMode(Button1,INPUT);
  pinMode(Button2,INPUT);
  pinMode(Button3,INPUT);
  pinMode(Button4,INPUT);

  digitalWrite(12, HIGH);

  lcd.begin(16, 2);
  lcd.clear();
  lcd.print("INNOVATIVE CLG");
  lcd.setCursor(0, 1);
  lcd.print("BUS INFO SYSTEM");

  delay(1000);
}

void loop()
{
  ButtonValue1=digitalRead(Button1);
  ButtonValue2=digitalRead(Button2);
  ButtonValue3=digitalRead(Button3);
  ButtonValue4=digitalRead(Button4);

  if(ButtonValue1!=0)
  {
    lcd.clear();
    lcd.print("BUS STARTED...");
    Serial.write("AT\r\n");         okcheck();
    Serial.write("ATE0\r\n");         okcheck();
    Serial.write("AT+CMGF=1\r\n");         okcheck();
    Serial.write("AT+CNMI=1,2,0,0\r\n");         okcheck();
    Serial.write("AT+CSMP=17,167,0,0\r\n");         okcheck();
    Serial.write("AT+CMGS=\"+91...........\"\r");
    delay(100);
    Serial.write("GUD MNG.. BUS STARTED FROM STARTING POINT\r");
    delay(100);
    Serial.write(0x1A);
    delay(1000);delay(1000);
    Serial.write("AT+CMGS=\"+91...........\"\r");
    delay(100);
    Serial.write("GUD MNG.. BUS STARTED STARTING POINT\r");
    delay(100);
    Serial.write(0x1A);
    delay(1000);delay(1000);
    Serial.write("AT+CMGS=\"+91...........\"\r");
    delay(100);
    Serial.write("GUD MNG.. BUS STARTED STARTING POINT\r");
    delay(100);
    Serial.write(0x1A);
    delay(1000);delay(1000);
    Serial.write("AT+CMGS=\"+91...........\"\r");
    delay(100);
    Serial.write("GUD MNG.. BUS STARTED STARTING POINT\r");
    delay(100);
    Serial.write(0x1A);
    delay(1000);delay(1000);
  }
  if(ButtonValue2!=0)
  {
    lcd.clear();
    lcd.print("BUS IS @ 1st stage");
    Serial.write("AT\r\n");         okcheck();
    Serial.write("ATE0\r\n");         okcheck();
    Serial.write("AT+CMGF=1\r\n");         okcheck();
    Serial.write("AT+CNMI=1,2,0,0\r\n");         okcheck();
    Serial.write("AT+CSMP=17,167,0,0\r\n");         okcheck();
    Serial.write("AT+CMGS=\"+91...........\"\r");
    delay(1000);
    Serial.write("BUS IS @ 1st stage\r");
    delay(1000);
    Serial.write(0x1A);
    delay(1000);delay(1000);
    Serial.write("AT+CMGS=\"+91...........\"\r");
    delay(1000);
    Serial.write("BUS IS @ 1st stage\r");
    delay(1000);
    Serial.write(0x1A);
    delay(1000);delay(1000);
    Serial.write("AT+CMGS=\"+91...........\"\r");
    delay(1000);
    Serial.write("BUS IS @ 1st stage\r");
    delay(1000);
    Serial.write(0x1A);
    delay(1000);delay(1000);
  }
  if(ButtonValue3!=0)
  {
    lcd.clear();
    lcd.print("BUS IS @ 2nd stage");
    Serial.write("AT\r\n");         okcheck();
    Serial.write("ATE0\r\n");         okcheck();
    Serial.write("AT+CMGF=1\r\n");         okcheck();
    Serial.write("AT+CNMI=1,2,0,0\r\n");         okcheck();
    Serial.write("AT+CSMP=17,167,0,0\r\n");         okcheck();
    Serial.write("AT+CMGS=\"+91...........\"\r");
    delay(1000);
    Serial.write("BUS IS @ 2nd stage\r");
    delay(1000);
    Serial.write(0x1A);
    delay(1000);delay(1000);
    Serial.write("AT+CMGS=\"+91...........\"\r");
    delay(1000);
    Serial.write("BUS IS @ 2nd stage\r");
    delay(1000);
    Serial.write(0x1A);
    delay(1000);delay(1000);
  }
  if(ButtonValue4!=0)
  {
    lcd.clear();
    lcd.print("BUS IS @ COLLEGE");
    digitalWrite(buz,LOW);
    delay(1000);
    digitalWrite(buz,HIGH);
  }
}


texts: Using a transistor to get 100mA on a IR led

texts:
What i saw is that the led use 1.3V on 100mA with a 1:10 Cycle (100ms). Im currently at 30mA using only a 100 resistor, but the range of the led is 20cm at max, i want to get at least 2 meters.

Since i know the max output of the Arduino pin is 40mA i need to use a transistor to get the 100 i want. And that is the problem, i read a lot about how transistors works but i can't yet understand how can i achieve 100mA using a transistor.

I did the math using 5v and got 37R.

Is this correct? So i need to use a 37 ohms resistor to get the 100mA i want?

And this resistor is going between the digital input and the transistor base, correct?

Im using a NPN 2n2222 and reading the datasheet 100mA is easy job for this transistor.

I appreciate any help.


texts: Arduino mega 2560 Stacked with Ethernet/SD card Shield Heat up

texts:
Stacked mega and ethernet/sd shield:

When I do this stacking, it heats up. I tried connecting the SPI via ports 13-10 (no stacking), it doesn't work. Also tried connecting the ICSP (red circled mark) via male-female wires without stacking, it works, but still heats up. So I think the ICSP has a defect? or does it? Is it supposed to be like this and I'm just being paranoid?
*PS: the heat in the "pain" level when I touch it, no burning IC odor. Maybe it's because I unplug it immediately after short use? IDK.
**update, I think I got it working, the problem was not about the heating, but the program. Consulted a more experienced person, he said what's happening is normal.


texts: Power Arduino from 230v with battery fallback

texts:
I've build a fairly simple doorbell using Arduino Pro Mini 3.3V: https://www.youtube.com/watch?v=WFd94CYT2Lw&feature=youtu.be

Here's the current setup:

Arduino running off the 9 V battery
A simple speaker is connected to Arduino (powered from the battery, Arduino just drives it through a transistor)
Arduino is reading light level from the light meter every 200 ms.
Bulb is connected to the wire that is lit up when someone presses the doorbell button.

It works well - someone presses the doorbell button, bulb gets lit up, Arduino notices that (using light meter) and doorbell rings.

Problem

In short - battery life. This kind of setup lasts around 2-3 days off a single battery. I was reading all about how to run Arduino off a single battery for a few weeks, even months, but I'm not sure it's feasible in my case. First of all, I need to wake up Arduino every 100-200, maybe 500 milliseconds, to read the light level. Plus, many of those long-battery-life solutions involved basically building own Arduino-compatible scheme from scratch, which I'd like to avoid.

Idea

But... I have a 230 V power source - the one that drives the bulb. Issue is that this power source is down all the time, unless someone is pressing the doorbell button.

I could approach it in two ways:

When someone presses the button, I'd power the Arduino and immediately play a song. Issue with that approach is that if someone presses the button for just a split second, my Arduino would be powered up for just that short amount of time, and I wouldn't have enough time to play the complete song.
If I could possibly reverse the way doorbell button works, I could have +230V all the time, and 0 when someone presses the button. This way Arduino would be on all the time, and it would "notice" someone pressed the button when power would go down. Issue with that approach is that song would be played only once guest would release the doorbell button, + the time it takes for an Arduino to boot.

In both #1 and #2, I need two things then:

a) have Arduino on all the time, regardless of whether button is pressed or not

b) power Arduino from the doorbell to avoid having to use a battery

Which kind of means that I need to power Arduino from a dual source - 230 V and rechargeable battery. 230 V when available, and battery when 230 V goes down. In a perfect scenario, this battery would be charged from 230 V source too :)

Any ideas how to built such a thing? Is there some AC power module that I could use? How would I wire things up in such a case - Arduino, AC power module, rechargeable battery?

Or maybe I'm missing some easier, simpler solution here?


texts: VGAX library only allows 4 colors, library or hardware limitation?

texts: I'm working with VGA DSUB-15 output, however VGAX only allows for 4 colors. I'm using an Arduino Nano that uses an 8-bit atmel chip, and I've seen many 8-bit computers of which have a bit more than 4 colors.


texts:
I have a weird problem. I am currently building a BB-8. Therefore, I am using an Arduino Uno. On top, I have stacked an Adafruit Motor Shield v2.3 and, again, on top of this, I have stacked the Sparkfun USB Host Shield. The Arduino is powered by a 9V-Block battery, the motors are powered separately by two 18650 Li-Ion batteries. To control the two Pololu motors, which have a stall current of 1.6 amps each, I use a Xbox 360 wireless controller, where the receiver is connected to the USB Host Shield.

Now to my problem. Every seems to work fine, until i cover everything with a styrofoam hemisphere. Yes, you've read right. If that happens, the controller signals is lost and does not connect again, unless I restart the Arduino. I have uploaded a small video on youtube, where you can see the problem.

I guess, this is a power problem, since this issue does not occur, when I connect the Xbox receiver to my Mac. Has anyone an idea, how to solve this problem?

I already tried another power source. And the USB host shield should give enough power, since the specs are saying, that 500 mA is no problem, and hit is exactly the USB 2.0 spec. The combination of the shield shouldn't be a problem, too. I carefully chose this shields, because the motor shield is just using the pins A4 and A5, the USB host shield is using some of the digital pins, so I think there is no interference.

Thank you for your help.

EDIT
I have tested it a bit more now and i think i can reduce the probable reasons. First, i tried some other power supplies, from AA batteries on the VIN pin to external power adaptors. Next, i tried other xbox receivers and controllers. I also tried a playstation 3 controller with a Bluetooth dongle. Nothing solved the problem. I also covered the Arduino with other things than styrofoam, like a garbage can, cardboard and some metal box. This worked, so the problem was only with styrofoam. Now i haven't covered the Arduino, but i slowly got closer. About 20 cm from the Arduino, it stopped working. My clue: static electricity. Do you think this can be a problem? And if yes, how can i solve this?


texts:
I have an Arduino program that uses the Thread library to create two concurrent threads, where:

Thread #1 blinks an LED every 500ms; and
Thread #2 blinks another LED every 250ms

I wired things up, flashed the program to my Arduino Due, and it ran beautifully.

I am now trying to add a 3rd thread that sweeps a servo back and forth.

Here's my design:

And the schematic that Fritzing generated for me:

And an accompanying actual picture of the wire up:

If you can see it, I've rigged Pin 10 as an OUTPUT, and attached the servo's signal line to Pin 9. Here's the code:

#include <Thread.h>
#include <ThreadController.h>
#include <Servo.h>

int SERVO_SIGNAL_PIN = 9;
int SERVO_PWR_PIN = 10;
int LED_1_PIN = 12;
int LED_2_PIN = 13;

Servo servo;
int pos = 0;

static bool LED_1_STATUS = false;
static bool LED_2_STATUS = false;

Thread blinkLED1Thread = Thread();
Thread blinkLED2Thread = Thread();
Thread servoThread = Thread();
ThreadController master = ThreadController();

void setup() {
    pinMode(LED_1_PIN, OUTPUT);
    pinMode(LED_2_PIN, OUTPUT);
    pinMode(SERVO_PWR_PIN, OUTPUT);

    servo.attach(SERVO_SIGNAL_PIN);

    blinkLED1Thread.onRun(blinkLED1);
    blinkLED1Thread.setInterval(250);

    blinkLED2Thread.onRun(blinkLED2);
    blinkLED2Thread.setInterval(500);

    servoThread.onRun(runServo);

    master.add(&blinkLED1Thread);
    master.add(&blinkLED2Thread);
    master.add(&servoThread);
}

void loop() {
    master.run();
}

void runServo() {
    // Give the servo a few seconds to reset to the starting position.
    servo.write(0);
    delay(5000);

    while(true) {
        for(pos = 0; pos < 180; pos += 1)  {
            servo.write(pos);
            delay(15);
        }

        for(pos = 180; pos >=1; pos-=1) {
            servo.write(pos);
            delay(15);
        }
    }
}

void blinkLED1() {
    LED_1_STATUS = !LED_1_STATUS;
    digitalWrite(LED_1_PIN, LED_1_STATUS);
}

void blinkLED2() {
    LED_2_STATUS = !LED_2_STATUS;
    digitalWrite(LED_2_PIN, LED_2_STATUS);
}

When I flash this to the Due, two disappointing things happen:

The LEDs, which previously blinked at the correct rates, now stay lit and do not blink at all; and
The servo doesn't move

Now perhaps I have a bum servo, or perhaps I haven't wired it up correctly, but the most concerning thing to me is that the LEDs are no longer blinking. I have a feeling that once I get those blinking again, the servo will probably start sweeping as well.

Can anyone spot anything that jumps out at them as being wrong here, wiring and code alike?


texts: Arduino: How does digitalRead read a value? And what is this value?

texts:
I have a Arduino Uno with 14 digital pins. I believe they have an output of 5V.
But they can also input values. I'm not sure of what exactly it reads when it does that (amperage, voltage ...). Also, how do they read it? How can such a tiny thing possibly know what it's receiving?

Just to provide a little more context to the reading part of this question, here's an example circuit. I have a 5V battery connected to an LED and a 220 Ohm resistor. Next thing in the circuit is a wire, which exits the main circuit and connects to a digital pin on the Arduino Uno (here it reads the value). Then the main circuit closes by connecting to ground.

Hope my question is clear enough :)


texts: Does Keyboard.begin() and Keyboard.end() make my code slower?

texts:
I'm making an IR Macro keyboard, and about 10% of the code is dedicated to the Keyboard commands, would having Keyboard.begin() and Keyboard.end() in the method responsible for typing make any difference to the speed or size?
My code:

void decodeCode(){ // send the macros.
  int pos = 0;
  for(int i = 0; i<output.length(); i++){
    if(output.charAt(i) == '$' && i!=output.length()-1){ //the $ is a symbol for "$pecial" characters
      i++;
      specialDecodeChar(output.charAt(i));
    }
    else if(output.charAt(i) == '%'){
      Keyboard.releaseAll();
    }
    else{
      Keyboard.press(output.charAt(i));
    }
  }
  Keyboard.releaseAll();
}

I currently have Keyboard.begin() in setup().


texts: Arduino ModBus RTU master communication with Power Meter problem

texts:
i have an arduino UNO with RS485 module.

I have made this connection:

And i have an problem with communication of this module with power meter
"InePro PRO-1Mod"
(datasheet) over ModBus protocol. I want for example read an L1 Voltage value, which i know from the manual (page 24 & 25) that this value is stored in "read holding register" with adrress 5002. I should communicate with these paramaters:

Baud rate 9600
8 data bits
even parity
1 stop bit

There is also mention about 120 ohms resistor placed by the power meter (but it is 15cm long cable, and even with the resistor there is no change)

I have tried using many of ModBus libraries and for now none of them doesn't work. I have tried "Modbus-Master-Slave-for-Arduino" , "ModbusMaster and now at last i am using this "simple-modbus".

I think that with that simple modbus library i went far as i can, but it is still doesn't working, but i see on the display of power meter that there is some try to communication (i see a black dot which shows modbus communication)
but i don't receive any useful data.

I am using this code:

    #include <SimpleModbusMaster.h>
#include <AltSoftSerial.h>

#define TxEnablePin 2                    // RS485 modbus direction control pin:
#define baud 9600                           // modbus port speed:
#define timeout 1000                        // modbus timeout in mSec:
#define polling 500                         // modbus scan rate in mSec:
#define retry_count 15

#define TOTAL_NO_OF_REGISTERS 1// number of registers to poll for:

AltSoftSerial altSerial;

enum
{
 PACKET1,
 TOTAL_NO_OF_PACKETS                       // leave this last entry
};

Packet packets[TOTAL_NO_OF_PACKETS];        // array of Packets to be configured

//struct packetPointer packet1 = &packets[PACKET1];
unsigned int regs[TOTAL_NO_OF_REGISTERS];   // master register array
long previousMillis = 0;
long interval = 1200;
unsigned long currentMillis;

void setup() {
 Serial.begin(9600);
 altSerial.begin(9600);
 altSerial.println("Hello World");
 modbus_construct(&packets[PACKET1], 5, READ_HOLDING_REGISTERS, 5000, 2, 0);  //initialize packet
 modbus_configure(&Serial, baud, SERIAL_8E1, timeout, polling, retry_count, TxEnablePin, packets, TOTAL_NO_OF_PACKETS, regs);
}

void loop() {
 modbus_update();

 float Power;
 unsigned long temp = (unsigned long)regs[1] << 16 | regs[0];
 Power = *(float*)&temp;

  currentMillis = millis();
 if (currentMillis - previousMillis >= interval)
 {
   altSerial.print("Exception errors: ");
   altSerial.println(packets[PACKET1].exception_errors);

   altSerial.print("Failed requests: ");
   altSerial.println(packets[PACKET1].failed_requests);

   altSerial.print("Successful requests: ");
   altSerial.println(packets[PACKET1].successful_requests);
   altSerial.print("Low byte: ");
   altSerial.println(regs[0]);
   altSerial.print("High byte: ");
   altSerial.println(regs[1]);
   altSerial.print("Power ");
   altSerial.println(Power);
   altSerial.println("----------");

   previousMillis = currentMillis;
 }

}

And i have got only this output in the pc (its repeating of course):

----------
Exception errors: 0
Failed requests: 5
Successful requests: 0
Low byte: 0
High byte: 260
Power 0.00
----------

Altserial library i am using together with USB2TTL convertor on pins 8 & 9,
to see output.

I should mention that there is only A and B screw terminals on power meter, so i have no option to make common ground connection. I also using an 15cm twisted pair cable UTP.

Can someone help me to make it work ?
I have tried to change adrress of holding register to 0x5000 or 5002, tried changing number of registers.

I have tried to connect rs485 module with USB2TTL to pc and run software called "qModMaster" and it works, but with arduino it doesn't work.

Slave ID (power meter) is 5.

Thank you, for your help.


texts: What does "Update of OCR1x at" mean in the WGM table of ATMEGA328?

texts:
I just finished a reading a couple of online guides on how to use timer registers with pulse width modulation, so I'm still new to its concept.  When I looked in the ATMEGA328 specification sheet, I see this table:

The column that I'm not completely clear on is the "Update of OCR1x at".  I circled row 14 as an example.  If you're operating in mode 14 (ie. setting WGM 13, 12 and 11 to high), then you'll be in Fast PWM.  By setting a value for ICR1, you are effectively setting the TOP value, which will control the period of the pulse waves.  And the overflow flag on the timer will be set when the timer reaches the TOP value.

So does "Update of OCR1x at" mean that only when when the pulse wave form has reached the value of BOTTOM (or the end of a period), that's when the value of OCR1x will be passed on to the OCx pins if COMx bits are set?


texts: How to control 12v water pump by arduino?

texts: I have arduino uno and I've bought 12 Volt/350 GPH Seaflo Electric Bilge Pump, how to control it directly from arduino?


texts:
I am trying to convert 1-5V to 0-20mA which is then used to drive VFD.

Actually, I want 1-5V Variable output from Arduino. I am using PWM but its output 0V or 5V depending upon the duty cycle.

Is their any method to obtain any voltage between 1-5V using Arduino or any other module/controller?


texts: Adding an Arduino variant into ~/sketchbook and using it from a Makefile

texts:
I have a pins_arduino.h file for a given Arduino variant, installed in ~/sketchbook/hardware/attiny/variants/tiny14/pins_arduino.h. The IDE has no problem picking it up if I set the right board type. However, if I use a Makefile like this:

BOARDS_TXT      = $(HOME)/sketchbook/hardware/attiny/boards-cli.txt
BOARD_TAG       = attiny44-8

include /usr/share/arduino/Arduino.mk

then running make fails to compile it because of a missing pins_arduino.h. Moving the tiny14 directory to /usr/share/arduino/hardware/arduino/variants  fixes the problem, but I don't want to pollute my system directory (and also, it sounds fragile if I ever remove/replace my Arduino software distribution).

How do I get the CLI Make toolchain to pick up my pins_arduino.h file from my ~/sketchbook?


texts: Fastest Communication from NodeMCU to Arduino Nano

texts:
For one of my projects, I need to transmit data from NodeMCU to my Arduino Nano, in real time, I used S-Bus, but it quite unsatisfies me, as, slight latency is taking place.
I am transmitting a JSON file, with 4 signed 16 bit integeres.
Now,I need to know, what is the fastest and most reliable way to transmit data from NodeMCU to an Arduino Nano. Any detailed description, or even suggestion will be very much helpful. Thanks in advance !


texts: Why wifiManager.setTimeout(60) is not working?

texts:
in this code I am using wifiManager.setTimeout(60); so that when it fails to connect to the wifi it should restart. However, wifiManager.setTimeout(60) is not working at all. It get stuck and display these lines :

*WM: AutoConnect

*WM: Connecting as wifi client...

*WM: Using last saved values, should be faster

It never displays this :

"failed to connect and hit timeout"

which means wifiManager.setTimeout(60) is not working . Below is the code:

  #include <ESP8266WiFi.h>

 //needed for library
 #include <DNSServer.h>
 #include <ESP8266WebServer.h>
 #include <WiFiManager.h>

  void setup() {
       // put your setup code here, to run once:
       Serial.begin(115200);

      //WiFiManager
       //Local intialization. Once its business is done, there is no need to
       //keep it around
        WiFiManager wifiManager;
      //reset settings - for testing
      //wifiManager.resetSettings();

     //sets timeout until configuration portal gets turned off
     //useful to make it all retry or go to sleep
      //in seconds

      wifiManager.setTimeout(60);

  //fetches ssid and pass and tries to connect
  //if it does not connect it starts an access point with the specified name
 //here  "AutoConnectAP"
 //and goes into a blocking loop awaiting configuration

  if(!wifiManager.autoConnect("AutoConnectAP")) {
     Serial.println("failed to connect and hit timeout");
     delay(3000);
     //reset and try again, or maybe put it to deep sleep
     //ESP.reset();
     ESP.restart();
     //ESP.deepSleep(20e6, WAKE_RFCAL);
    delay(5000);
   }

   //if you get here you have connected to the WiFi
   Serial.println("connected...yeey :)");

    ESP.deepSleep(20e6, WAKE_RFCAL);
    delay(3000);

 }

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

  }

I am using ESP8266 thing dev board. Can anyone please tell me what is wrong and how to resolve the issue ? Thank You!!


texts: Arduino cannot communicate with PC after running servo

texts:
I was messing around with my arduino uno r3 and servo today. The book I got said to run the servo through the arduino. Everything was fine. I started changing the code, and then things started to get bad. I noticed that if I did not put a delay in between the servo movements, the board would freeze, and I would have to get lucky. Well now I just can't communicate with the board. I plug the board in to my pc, windows 7 makes the connection sound, the board turns on the ON light, the L light flashes, then goes steady. In the arduino software, the COM3 port, which is where I'm plugging it in, is not coming up. Only COM1 is there. I'm not sure what to do. The board is still functioning, the servo moves. I tried to plug it in with a different port and with the servo disconnected but it still doesn't want to communicate with my pc. The code I'm using is below

#include <Servo.h>

Servo servo1;

void setup()
{
  servo1.attach(9);
}

void loop()
{
  servo1.write(50);
  delay(500);
  servo1.write(90);
  delay(500);
  servo1.write(140);
  delay(1000);

  for(int i = 50;i<140;i+=10){
    servo1.write(i);
    delay(10);
  }
}

I would also like to add that I understand that you shouldn't run the servos through an arduino. I was following the book, and began researching when things went down hill.


texts: Missing bytes sended through serial from C# app

texts:
I am trying to store values sended by C# app in EEPROM via Arduino UNO. Here is a C# code that reads bytes from file (I'm 100% sure that there are, and always will be 256 bytes) and sends the buffer via SerialPort

        SerialPort port = new SerialPort("COM3", 9600);
        const string fileName = @"filepath";
        port.Open();
        byte[] buffer = File.ReadAllBytes(fileName);
        port.Write("W");
        port.Write(buffer, 0, buffer.Length);

Here is Arduino Code

int flag;
int datasize = 256;
byte byteBuffer[256];

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

  //read_write();
}

void loop() {
  readEEPROM();
  writeEEPROM();
  delay(500);
}

void readEEPROM() {
  if (Serial.available()) {
    flag = Serial.read();
    if (flag == 'R') {
      for (int i = 0; i < datasize; i++) {
        byteBuffer[i] = ME.read(i);
      }
      flag = 'S';
      Serial.write(byteBuffer, datasize);
    }
  }
}
void writeEEPROM() {
  if (Serial.available()) {
    flag = Serial.read();
    if (flag = 'W') {
      int bytesRead = 0;
      digitalWrite(LED_BUILTIN, HIGH);
      delay(500);
      while (bytesRead < 256) {
        if (Serial.available() > 0) {
          byteBuffer[bytesRead] = Serial.read();
          bytesRead++;
        }
      }
  digitalWrite(LED_BUILTIN, LOW);

  for (int i = 0; i < datasize; i++) {
    digitalWrite(LED_BUILTIN, HIGH);
    delay(50);
    ME.writeEnable();
    ME.write(i, byteBuffer[i]);
    ME.writeDisable();
    digitalWrite(LED_BUILTIN, LOW);
    delay(50);
  }
  flag = 'S';
   }
  }
 }

As you can see in writeEEPROM function arduino turns on BUILTIN_LED before it starts reading serial, sadly the LED is never turning off, which makes me think like there are never 256 bytes in SerialPort, whats more, when i turn the c# program on again, the arduino successfully leaves the while loop, but the data is deformed, I mean the values are different.


texts: Arduino signed int can't fire timer > 15 seconds

texts:
I have tried to use different libraries like TimeAlarms , SimpleTimer, Timer and others. My goal is to call function periodically every minute or so. Each library works fine when repeat time is less than 15 seconds ( maybe greater) but 30seconds,45seconds, 60seconds doesn't work at all.
It seems something with internal timer.
I also use NRF24l01 Mesh library.
Please help to solve the problem
SOLVED
The issue was that I used int type instead of long. but I don't understand why 60 000 cannot be stored in int type which is 4 bytes (2^32)


texts:
As far as I know, Ciao uses port 80 as the default and I haven't found a way of changing the port it attempts to connect to.

I tried using "192.168.0.23:8080" but the Ciao.write() seems to timeout after a while. Is there a way to specify the port to use?

P.S I'm using an Arduino Uno WiFi DevEd


texts: Send Color value from Processing into Arduino

texts:
I know this has been asked before, but I'm new to Arduino and Processing, and I'm trying to take this step by step.

I would like to pass an RGB value from processing, into Arduino via the Serial.Write/Read.

I have my Processing as:

void draw(){

  //orange colour in RGB values
  color _rgbColor = color(255, 40, 0);

  //convert colour into hex
  String _hexColor = hex(_rgbColor, 6);

  //convert colour into binary
  String _binaryColor = binary(_rgbColor);

  //pass colour to port
  myPort.write(_hexColor);
  delay(500);
}

I assume I can just pass the HEX value straight across, right?

First problem I get is that I can't debug what my Arduino device is getting (when I run the Processing program, the Serial Monitor wont work. Seems like I can only use one or the other). I can print the myPort.read within my Processing after the delay, and I get:

  -1

So I'm not quite sure what I'm doing wrong there.

On the Arduino side, I'm using Serial.read() to retrieve the Serial data, which I assume will all be broken down into bytes, so I need to then convert it into a HEX formate, right?

----- Update -----

I now know that I need to break down my color variable into a char-message. I'm guessing I can do something like this then, for example: And then on the other side (Arduino), I need to rebuild the message, right?

if(mousePressed == true){
    //Red
     myPort.write('2');
     myPort.write('5');
     myPort.write('5');
     myPort.write(',');

     //Green
     myPort.write('0');
     myPort.write('3');
     myPort.write('0');
     myPort.write(',');

     //Blue
     myPort.write('0');
     myPort.write('0');
     myPort.write('0');
     myPort.write('\n');
  }

My Arduino script is as follows, is this an okay route to go down?

String message;
void loop() {

  int _size = Serial.available();

  if(_size > 0){

    char value = Serial.read();
    message += value;

    //full message received (255,255,255)
    if(message.length() == 11){
      String _red = message.substring(0,3);
      String _green = message.substring(4,7);
      String _blue = message.substring(8,11);
      Serial.println("R:" + _red + " G:" + _green + " B:" + _blue);

      //apply to light system
      setColour(_red.toInt(), _green.toInt(), _blue.toInt());

      //clear buffer
      message = "";
      Serial.flush();
    }
  }
}


texts: How can I control a slave ESP8266 from a local server and also from another ESP8266?

texts:
I have a power strip with a ESP8266 which is supposed to turn it on upon command from a OpenHAB server, or to stay on for a predefined time upon command from another ESP8266 (serverless).

The reason is that OpenHAB is used to directly control the strip, while the other master ESP8266 is powered on and off intermittently and periodically sends "refresh" commands to the slave, that will turn off when no more messages are received.

How should I handle the control of the ESP8266? I have never worked with master/slave and I'm confused by the number of available options. For example, MQTT seems a good choice when the server sends the control command, but it requires a software listening and relaying MQTT messages, therefore is not suitable as only control technique because the communication between ESP8266 must not rely on any further network device.

I also thought about simply controlling the slave ESP8266 via webpage and POST/GET commands, since OpenHAB can be set up to use this method as well and that would work also as direct control between ESP8266.

What are my options, their complexity and pros/cons?


texts: How to fix error line number offset in Sublime Text when compiling for Arduino

texts: When compiling for Arduino via the Stino plugin line numbers are not represented correctly in the output. For example, I have an error on line 117 however the output is: sketch_name.ino.cpp:136:1: error:


texts: Fail to convert time_T from past to tm struct

texts:
Continuing a Question asked few days ago, answered by Edgar, a new question has rised:
My goal was using a past time_t value, and convert it into a struct tm variable in order to  use it, part as a Char to print a readable text and some for logic queries.
At start NTP is configured as:
void myIOT32::startNTP(const int gmtOffset_sec = 2 * 3600, const int daylightOffset_sec = 3600, const char *ntpServer = "pool.ntp.org")
{
  configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
}

and every-time I need to get epoch and or struct tm of current time I call this function
void myIOT32::getTime()
{
  int a = 0;
  while (a < 3)
  {
    if (getLocalTime(&timeinfo))
    {
      delay(100);
      time(&epoch_time);
    }
    a++;
  }

BUT, when using the following function I get not GMT (+3) reference as needed :
struct tm *myIOT32::convEpoch(time_t in_time)
{
  struct tm *convTime = gmtime(&in_time);
  //char time_char[40];
  //sprintf(time_char, "%04d-%02d-%02d %02d:%02d:%02d", convTime->tm_year + 1900, convTime->tm_mon + 1, convTime->tm_mday,
          convTime->tm_hour, convTime->tm_min, convTime->tm_sec);
  return convTime;
}

Meaning I get to correct epoch time, but strcut tm is 3 hrs earlier ( and no, I do not want to hard-code +3... )


texts:
I've been playing with my Arduino for a few months.

But, I just bought a shield that says it needs to be used with ATMEGA328P.  My box says I have a 328P, however, reading the chip, it's inscribed with "ATMEL MEGA16U2".

Does that mean the box is wrong, or is that the same as 328P somehow?

Thanks!!


texts: Can't send serial data throught serial pins but it works with the usb port

texts:
I am just starting out a project and I am having a little bit of trouble. I want to send data collected from an IR distance sensor, and send it with an XBee Pro S2B to my computer so I can do other stuff with it. The code I am using right now is pretty simple:

void setup()
{
  Serial.begin(9600);
}
void loop(){
 int distance = analogRead(0);
  Serial.println(distance);
  delay(1000);
}

The problem I am having is that when I turn on the arduino with batteries and disconnect the usb cable, the tx light stops turning on and no serial data is sended, AND if I connect it to the computer via USB again it won't work anyway, only works right when I upload the code. The XBees are configured correctly, I have done the chat example on the Building Wireless Sensor Networks by Robert Faludy.

Is it some code error? I must be really obvious.
By the way, when I upload the code and the serial data is sended throught usb, the data displayed on Arduino IDE's console is correct, so the sensor is wired correctly.

I am using an Arduino UNO and I have the XBee's and arduino's drivers installed correctly, and for the XBee I am using the XBee Explorer from Sparkfun


texts: Conditional compilation, how to determine whether a variable has been declared?

texts:
Whilst using #if/#end constructs, how can I determine whether a specific variable has already been declared?,
e.g.,

#if [the variable "pinname" has been declared]
Serial.print(F("Pin name: "));
Serial.println(pinname);
#end

If this question has been addressed, I cannot find a reference for it.


texts: Unusual behaviour over serial communication

texts:
I am sending data over serial connection from a python script to my Arduino UNO. Now initially whenever I tried to send data to the arduino, it would reset. The fix was to put a 10 microFarad capacitor between the 5V and RESET pins. I did that and everything started working.

Now after while,  mistakenly today I ran the same script without the capacitor between the 5V and RESET pins and for some reason it was working perfectly well. No more resetting when a value was received over serial communication.

Is something wrong with my Arduino?


texts:
I am running an Apache Server on my pc, by which I am hosting a local website. Everything is connected to router. Now I want to post reading of temperature from my arduino to the localhost via esp8266. I have everything setup and running AT commands are working fine, I have set CIPMUX to 1. It can connect to live websites like AT+CIPSTART=0,"TCP","google.com",80

In this case it give "Ok Linked", but when i try to connect to my localwebserver like
AT+CIPSTART=1,"TCP","XXX.XXX.XXX.XXX",1026
It says "Error Unlink".

What am I missing here? It would be really thankful if someone tell me, by an example may be.

EDIT It gets linked when I change the port to 80, but that's for internet right? Am I connected to a website of this address or my localhost ?


texts: is using two UARTs wiser compared to I2C and UART with Arduino + Xbee + BNO055 Sensor

texts:
Hardware

Arduino Nano
XBee Pro S1 (802.15.4) Modules
Adafruit BNO055 Absolute Orientation Sensor

Purpose

I want to send the Euler angles and Linear Acceleration angles to the a central XBee Coordinator (can be connected to a Computer or a Single Board Computer) every 100 ms

Since the BNO055 has SDA and SCL pins for I2C how will the performance of the Nano matter when sensor data is acquired from the BNO sensor and send to XBee module which will be connected to the Hardware Serial UART Port?

An interesting observation was that if one:

  Shorts the PS1 pin to 3.3V for the BNO055, the SDA and SCL will function as RX and TX pins for UART.
  source

In terms of interfacing, I can think of the Xbee now connected to the Hardware Serial Port and perhaps the BNO sensor will can be connected to the Nano via SoftwareSerial port. But will that serve any better purpose in terms of performance and data acquisition i.e. using two Asynchronous Serial Ports compared to one?


texts: Different Output Voltages from Same Source?

texts:
I'm wondering whether it is possible to wire multiple buck converters with different voltage requirements and amperage draws to the same power source (this idea is for controlling a radio-controlled boat). Going off other related questions this seems to be possible (1, 2).
My background is in programming, not electronics, so the terminology is difficult for me to understand. I'm getting a grasp on voltage and amperage. My problem is always understanding how electricity can be "split" into different modules. In my understanding, this below would be a parallel circuit and that should be fine.

Are there any gotchas to consider with this type of circuit, or is this the totally normal way of doing things (eg. like wiring a house out of a breaker box)?
Is there a better way to do this?
This won't cause a short circuit, right?


texts:
As far as I know a char is an 8 bit variable

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

void loop() {
  char x = 0x80;
  if(x != 0x80){
    Serial.println(x, HEX);
  }

  delay(1000);
}


texts: Return value of 0 if value is less than zero

texts:
Background: I am using an analog pressure sensor with a range from 0-100PSI returning voltage values .44v to 4.44v. It's open air (or 0 PSI) voltage on the signal pin is .47 volts. I have a function that subtracts that .47v (to make zero) and then multiplies it by 25 (25 PSI per volt). Due to signal noise or other factors, sometimes my function returns a negative number, which wreaks havoc on my math. I would like to return a value of 0 when my offset math returns a negative number, but I'm having a problem with it.

The code that I wrote that doesn't work:

double EngineOilPressure() {
    //insert oil pressure code here
    int reading = analogRead(sensorPin3);
    float voltage = reading * 5.0;
    voltage /=1024.0;

    Serial.print(voltage); Serial.println(" volts");

    if (voltage-.47 < 0)
    {
        float voltadj = 0;
    }
    else
    {
        float voltadj = (voltage-.47);
    }

    float pressureP = voltadj * 25;
    return PSIToPascal(pressureP);
}

The error that I get is

dynamic_engine.pde: In function 'double EngineOilPressure()':
dynamic_engine.pde:41:23: error: 'voltadj' was not declared in this scope
Error compiling.

The code that works but sometimes returns a very wrong value:

double EngineOilPressure() {
    int reading = analogRead(sensorPin3);
    float voltage = reading * 5.0;
    voltage /=1024.0;

    Serial.print(voltage); Serial.println(" volts");

    float pressureP = (voltage - .47) * 25;
    return PSIToPascal(pressureP);
}


texts: iterate through values in an array of strings to print

texts:
I (think I) am trying to iterate through the values of an array and print the string to a tft. I have declared the array of 4 strings, and that works fine. But when I try to print it, I get garbage. Am I missing a nuance of print? Or do I just not understand how to use arrays and strings...?

The code is as follows:

Declarations:

//Active System
char hvacSystems[4][5] = {"Off", "Fan", "Cool", "Heat"};
int activeSystem = 0;
String displayActiveSystem = hvacSystems[activeSystem]; <-- Should now be String "off"

Use (note the fake if statement for the question)

  if(systemNeedsToBeCycled){
    activeSystem++;
    displayActiveSystem = hvacSystems[activeSystem]; <-- Should now be String "Fan"
    tft.print(displayActiveSystem);
  }

Instead I get random characters most of the time, sometimes nothing.

In case its a memory thing, please know that:

Sketch uses 26,480 bytes (92%) of program storage space. Maximum is 28,672 bytes. Global variables use 1,126 bytes (43%) of dynamic memory, leaving 1,434 bytes for local variables. Maximum is 2,560 bytes.


texts:
I am trying to send command serially through Vb.through serial monitor working fine . But Through VB it not detecting port
My arduino code:

int ledPin = 2; // the number of the LED pin

void setup() {
Serial.begin(9600); // set serial speed
pinMode(ledPin, OUTPUT); // set LED as output
digitalWrite(ledPin, LOW); //turn off LED
}

void loop(){
while (Serial.available() == 0); // do nothing if nothing sent
int val = Serial.read() - '0'; // deduct ascii value of '0' to find numeric value of sent number

if (val == 1) { // test for command 1 then turn on LED
Serial.println("LED on");
digitalWrite(ledPin, HIGH); // turn on LED
}
else if (val == 0) // test for command 0 then turn off LED
{
Serial.println("LED OFF");
digitalWrite(ledPin, LOW); // turn off LED
}
else // if not one of above command, do nothing
{
//val = val;
Serial.println("Wrong command");
}
Serial.println(val);
Serial.flush(); // clear serial port
}

VB Code

Imports System.IO
Imports System.IO.Ports
Imports System.Threading

Public Class Form1
    Shared _continue As Boolean

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        SerialPort1.Open()
        SerialPort1.PortName = "COM3"

        SerialPort1.BaudRate = 9600
        SerialPort1.DataBits = 8
        SerialPort1.Parity = IO.Ports.Parity.None
        SerialPort1.StopBits = IO.Ports.StopBits.One
        SerialPort1.Handshake = IO.Ports.Handshake.None
        SerialPort1.Encoding = System.Text.Encoding.Default 'very important!

    End Sub

    Private Sub Button1_Click_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1_Click.Click
        SerialPort1.Open()
        SerialPort1.Write("1")
        SerialPort1.Close()
    End Sub

    Private Sub Button2_Click_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2_Click.Click
        SerialPort1.Open()
        SerialPort1.Write("0")
        SerialPort1.Close()
    End Sub

End Class

Error I am getting .Arduino port is 3. and configured to port 3 . i dont know why it giving error.

The port 'com10' does not exist.

This Line added as you said

Private Sub Current_Read_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        SerialPort1.Open()
        Dim str As String
        str = SerialPort1.ReadExisting
        Current_Read.Text = str
        SerialPort1.Close()
    End Sub

This is working But data not being updating

Private Sub Current_Read_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Current_Read.Text =SerialPort1.ReadLine
    End Sub


texts:
I've had a bit of experience with DHT11/DHT22 sensors in a greenhouse environment, and believe that when they get wet they stop working altogether.

Are there any low cost humidity sensors that I can hook up to an Arduino that don't suffer from this problem, or is there a way to protect these sensors from damage when near water? (I'm not talking about immersing them in water - but do expect condensation to get sprayed with water and/or get condensation on them from time-to-time).

Am I correct that the SHTxx sensors are able to withstand this kind of abuse, and that these sensors are about 5-10 times the cost of DHT sensors?  (I did not want to spend that much, but if it's the only possibility I might consider it).


texts: Can I use my phone's charger to connect arduino M0 pro R3 with computer?

texts:
I found out that the arduino M0 pro R3 needs either micro HDMI or micro USB.

Since I don't have any micro USB or HDMI adapters, can I use the Samsung galaxy USB/micro adapter to connect?


texts: Atmega collecting and relaying interrupt calls

texts:
I like to collect all possible interrupt and relay them to an alternative handler interrupt table what the user can set.

In order to do this i have to:
   1) collect all/any interrup request
   2) identify where is the interruption came from
   3) relay the call to another table the user pointed.

If you familiar with interrupts you know if you registers a single function to all interrupt handler there's no way to idenfity the source of the interrupt.
But registering unique interrupt handler that carries the information of the source and calls another function to dispatch call, for each interrupt is a code space wasting. Eg.: the atmega328 has 24 interrupt handlers. Each of the is compiled with the avr-gcc consumes 76 bytes.

But i have and idea how it is possible to register one handler function and identify the source:

00000000 <__vectors>:
   0:   0c 94 34 00     jmp 0x68    ; 0x68 <__ctors_end>
   4:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
   8:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>
   c:   0c 94 51 00     jmp 0xa2    ; 0xa2 <__bad_interrupt>

If i define an interrupt handler (even if it can fit the 4 byte space) a jmp instruction is placed. If it can be replaced to eg.: call 0xa2 (which can fit in 4 bytes), is can be used to identify the interrupt source address.

Because call stores the return address, the function started at 0xa2 can read back that address and therefor idenfity the caller. Then add an extra pop (pop the stack address accumulated by the call at the interrup table) and reti (to return as like from an interrupt handler) after the function body.

If this can work theorically, to achieve this only one question remains:

How can i replace the jmp instructions to call in interrupt table?


texts: How can an Arduino determine the status of a washer or dryer using only vibration data?

texts:
I'm trying to make an IoT washer/dryer device that will text me whenever my load is done. I was initially thinking to make assumptions about what data it should be receiving when the washer/dryer is running. However, I was wondering if there was a library that could analyze the data and "learn" what a cycle typically feels like. Should I:

a) keep it simple: when machine has been vibrating past a threshold for certain amount of time, consider it running. when it stops vibrating past time threshold, consider it done.

or

b) use some kind of learning algorithm to determine whether it has been stopped manually, an error has occurred, or it has successfully completed a cycle

Also, would option b be more practical on a device such as a Raspberry Pi?


texts: How to set maximal execution time of operation

texts:
I'm JSON deserializing output from ESP8266 in  my Arduino UNO, but when it fails (for some reason every time after it deserializes successfully) the program lags for few seconds and I don't want that to happen (at least not for a long time)
#include "SevSeg.h"
#include <ArduinoJson.h>
SevSeg sevseg;

StaticJsonDocument<500> response;

String data;

void setup(){
  Serial.begin(74880);
  Serial.setTimeout(10000);
  while (!Serial) {
     // wait for serial port to connect. Needed for native USB port only
  }
  byte numDigits = 4;
  byte digitPins[] = {2, 3, 4, 5};
  byte segmentPins[] = {6, 7, 8, 9, 10, 11, 12, 13};
  bool resistorsOnSegments = false; // 'false' means resistors are on digit pins
  byte hardwareConfig = COMMON_ANODE; // See README.md for options
  bool updateWithDelays = false; // Default 'false' is Recommended
  bool leadingZeros = false; // Use 'true' if you'd like to keep the leading zeros
  bool disableDecPoint = false; // Use 'true' if your decimal point doesn't exist or isn't connected. Then, you only need to specify 7 segmentPins[]

  sevseg.begin(hardwareConfig, numDigits, digitPins, segmentPins, resistorsOnSegments,
  updateWithDelays, leadingZeros, disableDecPoint);
  Serial.println("running");

}

void loop(){

       if (Serial.available()) {
            Serial.write(Serial.read());
            const auto deser_err = deserializeJson(response, Serial);

            if (!deser_err) {

                if(response["type"] == "num"){
                  sevseg.setNumber(response["data"],response["dot"]);
                }else{
                  sevseg.setChars(response["data"]);
                }
                String data = response["data"];
                Serial.println(data);

            }else{
              Serial.print(F("Failed to deserialize, reason: \""));
              Serial.print(deser_err.c_str());
              Serial.println('"');
            }

      }

  sevseg.refreshDisplay();

}

The response
running  //runs everytime I turn on the arduino
21:43:03.797 -> {null
21:43:03.797 -> :null
21:43:03.797 -> ,null
21:43:03.797 -> :null
21:43:03.797 -> ,null
21:43:03.797 -> :Failed to deserialize, reason: "InvalidInput" // for some reason I have to send request 2 times because for the first time it always fails
21:43:03.797 ->
Uove //correct data received
21:43:04.772 -> // this timestamp isn't right it is like 5 seconds after correct data
Failed to deserialize, reason: "EmptyInput"

What can I do for this not to happen for the first time or in a shorter duration?
I'd be really thankful for any answer.


texts:
I have a project where it would make a lot of sense to generate Arduino compatible source code, compile it and flash it based on some settings in the project software.

Is there any way to do this without having to rely on the user having installed the Arduino IDE/java?

The ideal would be a self-contained library that could be linked to my C/C++ program.


texts:
i am not able to detect any android device on my bluetooth HM-10 module which is connected to arduino. i am able to see my bluetooth module on my android phone. but i want to see android phones on arduino serial monitor for that i used AT+DISC? command. it shows AT+DISCS and than AT+DISCE with a 2 second interval. help me to solve the issue
thanks in advance


texts:
I'm trying to send data from an Arduino to an Android device.

I saw an online guide for that which provided this code:

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

void loop()
{
  byte msg[64];
  int len = Serial.available();
  if (len > 0)
  {
    len = Serial.readBytes((char*)msg, sizeof(msg)); // readBytes seems to need a char* not a byte*
    Serial.write(msg, len);
  }
}

I tried that example and it is working perfectly!

But when I put Serial.write("3");
in the setup loop after Serial.begin(115200);
it appears as question mark on my Android device,
I guess that I'm not sending it as a byte,
I searched online but without any luck.


texts: Arduino - Windows can't find the drivers

texts:
I bought an Arduino UNO R3 Yesterday. It's a Chinese clone. But it has the Atmega328p and MEGA16U2 both.
I've installed the IDE fully. But it can't find the ports. The Tools > Ports option is greyd out, Cannot find The options Named "Ports (COM & LPT)" or "Other Devices" in device manager. Can't upload any sketch to board.
I tried this on my both Win7 SP1(32 BIT) & Win10, which are installed in the same pc but in different partitions. I've roamed accross stackexchange but no successful result.


texts: How can I make FastLED set every 2 LEDs to the same color?

texts:
I'm controlling an WS2812 LED strip in which every 2 leds is controlled together - they are setup as "eyes" in a prop.  I'm looking to control hundreds of these, so in an effort to save RAM I'd like to have each byte in the LED color array represent 2 LEDs.  That is to say that when the FastLED library writes to the data lin I want it to duplicate every byte going out.

I've dug into FastLED code but get lost around the timings deep down in the code.

Any ideas?


texts: How to create real-time WASD control over an Arduino Uno?

texts: I am trying to figure out how to use the WASD keys on my computer, to go through the USB cable and then spin the Arduino servos in real-time. So if I press the “a” key, it should start to move left with little time delay. How do I do this?


texts:
I have just bought a MG90s tower pro servo for my school project and there is a problem. As soon as I connect my servo to the cnc shield or directly arduino, the whole arduino board turns off. I believe the motor is aking very high power. I even tried to power the motor with a 5v 2amps adapter, but still it turns off.I checked the resistance between the input wires and the wires to DC motor which was very high. As soon as I connected motor to external supply, there was a huge voltage drop. The voltage became almost negligible. DC motor was working fine alone. The servo hasn't even rotated for 1 degree. Please give me a quick solution as I am in a hurry for school deadline is coming. Should I buy a new servo or am I doing something wrong?
Please be quick.
Thank you.
Circuit diagram is below...]1

The code is below -

#include <Servo.h>

Servo name_servo;

int servo_position = 0;

void setup() {

name_servo.attach (9);

}

void loop() {

  for (servo_position = 0; servo_position <=180; servo_position +=1){

    name_servo.write(servo_position);
    delay(10);
  }

  for (servo_position=180; servo_position >= 0; servo_position -=1){

    name_servo.write(servo_position);
    delay(10);
  }
}


texts: ESP8266: Client Server Based Home Automation System

texts:
I am working on a home automation project in which I am trying to use Star Topology, where one esp8266 acts as a server and can be accessed from web browser to receive commands from the user, while two or more esp8266 acts as clients which are connected to relays. Upon the request of user, server esp8266 sends command to the respective client to trigger the relay and the client esp8266 replies with the current status of the relay.

Connections isn't a problem so I am keeping those things aside. So far

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

const char *ssid = "AndroidAP";
const char *password = "qvdo2440";

ESP8266WebServer server(80);
String webPage = "";

void handleRoot() {
  server.send(200, "text/html", webPage);
}

void setup() {
  webPage += "
ESP8266 Web Server
";
  webPage += "
Socket #2 <button>ON</button>
&nbsp;<button>OFF</button>
";

  delay(1000);
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  Serial.println();
  while (WiFi.status() != WL_CONNECTED) {
   delay(500);
    Serial.print(".");
  }
  Serial.print("Configuring access point...");
  WiFi.softAP(ssid, password);
  IPAddress myIP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.println(myIP);
  server.on("/", handleRoot);
  server.begin();
  Serial.println("HTTP server started");
}

void loop() {
  server.handleClient();
}

This is the code for server side. I cannot think of how to program for client side. Any help would be appreciable.

And yes. I have been through many articles, tried out many things which i found on the internet. But nothing could help me. So i am here for few more suggestions with better elaboration.


texts: What's the newest way to use C++ stdlibs in Arduino 1.8.2?

texts:
(My Arduino version is 1.8.2.)

For example,if I want to #include <vector> or <string>, <iostream>, <memory> etc, the compiler always complains that such libs are not found.

So what's the newest/most efficient way to use C++ libs in Arduino 1.8.2?


texts: How to keep accurate millis() while using ADC_sleep mode?

texts:
millis() uses timer0 (linked to CPU clock) to count time, but ADC_sleep mode stops the CPU clock, therefore millis() will drift (lag behind) after each ADC conversion performed in ADC_sleep mode.

With the standard number of CPU cycles needed for the ADC conversion (ADC prescaler=128 multiplied by ADC clock cycles=13), and with the standard prescaler for timer0 (64), it would look like millis() loses 13.5 tics (about 0.1 ms) for every ADC conversion performed in ADC_sleep mode.

I could update the timer0 register (TCNT0) by increasing it manually by 14 but first of all I would still have a 0.5 ticks drift (or a bit less, since the update operation would take some cycles), second I would miss the overflow event (the one Arduino uses internally for time tracking) every time the ADC conversion is started with TCNT0 > 230.

How should I proceed to use ADC_sleep mode during ADC conversions but still keep millis() accurate?


texts: Pretty simple question. Is there a microcontroller that can output hdmi? If not, what microcontrollers can output any type of video?


texts: Avoiding false rising and falling edge when using demultiplexer

texts:
I have 8 sets of 8 push buttons. There is a Teensy and a demultiplexer. The demultiplexer has 8 outputs. When an output is selected it is pulled low. Each output is connected to a group of 8 push buttons. The 8 push buttons are then connected to 8 pullup inputs on the Teensy.

Each group of 8 push buttons is connected to a unique demultiplexer output, but all the push buttons are connected to the same 8 inputs on the Teensy. That is, push button #1 in group 1 shares a Teensy input with push button #1 in group 2. The push buttons are isolated from each other with diodes.

I'm using bounce.h for debouncing. It looks for rising and falling edges.

The problem is this:

Push button #1 in group #1 is pressed, pulling that input low, causing a falling edge to be detected. This is good.
The demultiplexer shifts to group #2, where the #1 button hasn't been pressed, and thus is high.
Because both #1 buttons in group #1 and #2 share the same input line, the Teensy sees this change as a rising edge. This is undesired.

What is the better approach to this?

Thanks,

Dan


texts:
I'm trying to run two of my motors through PWM. Here's my code -

#include <Servo.h>
int Lm = 11;
int Rm = 10;
int incomingByte = 0;
int pos = 0;
Servo myservo;
void setup() {
  pinMode(Rm, OUTPUT);
  pinMode(Lm, OUTPUT);
  pinMode(7,OUTPUT);
  pinMode(2,OUTPUT);
  myservo.attach(3);
  Serial.begin(9600);

}

void loop() {
  blinkers();
  if (Serial.available() > 0) {
                incomingByte = Serial.read();
  }
  if(incomingByte == 49){
    analogWrite(Rm, 128);
    analogWrite(Lm, 128);
  }
   else if(incomingByte == 48){
    analogWrite(Rm, 0);
    analogWrite(Lm, 0);
    myservo.write(0);
  }
  else if(incomingByte == 50){
    analogWrite(Rm, 0);
    analogWrite(Lm, 128);
    delay(500);
    analogWrite(Lm, 0);
  }
  else if(incomingByte == 51){
    analogWrite(Rm, 128);
    analogWrite(Lm, 0);
    delay(500);
    analogWrite(Rm, 0);
  }
  else if(incomingByte == 52){
    for (pos = 0; pos <= 180; pos += 10) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for (pos = 180; pos >= 0; pos -= 10) { // goes from 180 degrees to 0 degrees
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);
  }
}
}

void blinkers(){
    digitalWrite(7, HIGH);
    digitalWrite(2, HIGH);
  delay(100);
  digitalWrite(7, LOW);
  digitalWrite(2, LOW);
  delay(100);
}

Now in this code... Lm, and Rm are my motors. The motor Lm runs perfectly fine, but Rm doesn't move at all. When I use digitalWrite instead, both motors work fine.

I tried running the motor in the exact same setup but this time with only the code for running the motor by PWM. The code was -

void setup() {
  pinMode(10,OUTPUT);

}

void loop() {
  analogWrite(10, 128);
  delay(100);
  analogWrite(10, 0);
  delay(100);

}

This code worked perfectly fine.

So clearly there is an issue in the earlier code but I can't figure out what. Everything is correct in that as well but the motor refuses to move...

Can anyone tell why is this happening?


texts: Is there a way to write a custom function which would be the mode/reason to trigger an interrupt. I have an analog joystick connected to my arduino analog pin. It reads a value of 689 on one end and 0 on the other and around 480 in the center. I would like to trigger an interrupt based on these value changes i.e an interrupt when it  more then 600 and another when less then 10. None of the pre-defined modes RISING,HIGH,LOW,FALLING,CHANGE are working satisfactorily.


texts: HC-05 Bluetooth Module - INQ-Command doesn't work

texts:
For a project I need to connect a Bluetooth Remote control with an Arduino Nano.

The Problem

I am trying to setup a connection to said Bluetooth remote Control. This device is visible! (I have confirmed it with a smartphone)

Here are the steps that I am trying to do with the Arduino and HC05 module:

AT <-- confirms, that Command Mode is running successfully
OK

AT+ROLE? <-- 1 For Bluetooth Master Mode
+ROLE:1
OK

AT+CMODE? <-- 1 allows connecting to any BT address
+CMOD:1
OK

AT+INQM? <-- Show Inquiry access values
+INQM:1,1,48
OK

AT+INQ <-- Inquiry Bluetooth Device

After ~60 seconds, it just says "OK", but according to this tutorial  or according to this youtube video it should display all Bluetooth-devices, that are ready to connect.
The BT device is definately visible. (I tried multiple BT devices like smartphones and peripheral devices).

Why is the inquiry not working? What is wrong here?

The circuit is exactly like in this picture:

For setting up the Bluetooth-connection I wire the EN-Pin to +3,3V, which successfully activates AT-Command-Mode
According to this site, you can do it like that.

Here is my code, that I use, to communicate with the module. - It works good!

#include <SoftwareSerial.h>
SoftwareSerial mySerial(2, 3); // RX | TX
// Connect the HC-05 TX to Arduino pin 2 RX.
// Connect the HC-05 RX to Arduino pin 3 TX through a voltage divider.
//

char c = ' ';
int buf[64]; //buffer to store AT commands
int len = 0; //stores the length of the commands

void setup()
{
    Serial.begin(9600);
    Serial.println("Arduino is ready");
    delay(500);
    mySerial.begin(9600);
    Serial.println("BlueTooth is ready");
}

void loop()
{

  if(Serial.available())
  {
    len = Serial.available(); //store number of bytes to read
    for(int i = 0; i<len; i++) //store all bytes into the buffer
    {
      buf[i] = Serial.read();
    }
    for(int i = 0; i<len; i++)
    {
      mySerial.write(buf[i]);
      Serial.write(buf[i]);
    }
  }

  if(mySerial.available())
  {
    len = mySerial.available();
    for(int i = 0; i<len; i++)
    {
      buf[i] = mySerial.read();
    }
    for(int i = 0; i<len; i++)
    {
      Serial.write(buf[i]);
    }
  }

}

Here is a related question but the answer doesn't help.


texts: SIM900A GSM/GPRS Shield Transaction per minute

texts: I'm planning to buy SIM900A GSM/GPRS Shield for Arduino Uno. I wanted to create an application that sends SMS to a list of mobile numbers, let's say 1000 mobile numbers. Is it applicable to use SIM900A GSM/GPRS shield for bulk messaging? Did anyone of you tested the sms transaction sent per second/minute using this shield? I accept any suggestion that would be helpful. Thanks.


texts: Moving average sticks in fictitious zeroes for the first readings. This delays accuracy

texts:
My 9/10 Moving Average inserts zeroes for the first 9 readings. For example, if the first voltage reading is 100, the first moving average given is 10. That is the average of 9 zeroes and one 100. How can I get the moving average to only use actual readings from the adc? Or how can I get the moving average to wait until at least 10 readings are finished before starting its calculations?

#include <SPI.h>
#include <SoftwareSerial.h>
#include <math.h>
#include <ads1262.h>

#define PGA 1 // Programmable Gain = 1
#define VREF 2.50 // Internal reference of 2.048V
#define VFSR VREF/PGA
#define FSR (((long int)1<<23)-1)

ads1262 PC_ADS1262; // class

float volt_V=0;
float volt_mV=0;
float MovingAverage=0;
volatile int i;
volatile char SPI_RX_Buff[10];
volatile long ads1262_rx_Data[10];
volatile static int SPI_RX_Buff_Count = 0;
volatile char *SPI_RX_Buff_Ptr;
volatile int Responsebyte = false;
volatile signed long sads1262Count = 0;
volatile signed long uads1262Count=0;
double resolution;

void setup() {
  // initalize the  data ready and chip select pins:
  pinMode(ADS1262_DRDY_PIN, INPUT); //data ready input line
  pinMode(ADS1262_CS_PIN, OUTPUT); //chip enable output line
  pinMode(ADS1262_START_PIN, OUTPUT);  // start
  pinMode(ADS1262_PWDN_PIN, OUTPUT); // Power down output
  Serial.begin(9600);
  //initalize ADS1292 slave
  PC_ADS1262.ads1262_Init(); // initialise ads1262
  Serial.println("ads1262 Initialised successfully....");
}

void loop() {
  volatile int i, data;
  if((digitalRead(ADS1262_DRDY_PIN)) == LOW) {
    // monitor Data   ready(DRDY pin)
    SPI_RX_Buff_Ptr = PC_ADS1262.ads1262_Read_Data();
    // read 6 bytes conversion register
    Responsebyte = true;
  }
  if(Responsebyte == true) {
    for(i = 0; i <5; i++) {
      SPI_RX_Buff[SPI_RX_Buff_Count++] = *(SPI_RX_Buff_Ptr + i);
    }
    Responsebyte = false;
  }
  if(SPI_RX_Buff_Count >= 5) {
    ads1262_rx_Data[0]= (unsigned char)SPI_RX_Buff[1];
    // read 4 bytes adc count
    ads1262_rx_Data[1]= (unsigned char)SPI_RX_Buff[2];
    ads1262_rx_Data[2]= (unsigned char)SPI_RX_Buff[3];
    ads1262_rx_Data[3]= (unsigned char)SPI_RX_Buff[4];
    uads1262Count = (signed long) (((unsigned long)ads1262_rx_Data[0]<<24)| ((unsigned long)ads1262_rx_Data[1]<<16)|(ads1262_rx_Data[2]<<8)|        ads1262_rx_Data[3]);
    //get the raw 32-bit adc count out by shifting
    sads1262Count = (signed long) (uads1262Count);
    // get signed value
    resolution = (double)((double)VREF/pow(2,31));
    //resolution=  Vref/(2^n-1) , Vref=2.5, n=no of bits
    volt_V = (resolution)*(float)sads1262Count;
    // voltage = resolution * adc count
    MovingAverage = (9*MovingAverage + volt_V)/10;
    Serial.print(MovingAverage,8);
  }
  SPI_RX_Buff_Count = 0;
}

float mapfloat(float x, float in_min, float in_max, float out_min, float out_max) {
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}


texts: Going from arduino & sketch to production

texts:
I've got a little proof of concept thing going here with an arduino & Ethernet shield. The basic idea is for it to ping out much like a heartbeat monitor every so often so I can see if my house still has internet connectivity.

The arduino works nicely and does exactly what I want. I've ordered a board to be made with just the basic components needed and now want to put the code on to it. They gave me an option to load the code (Dragon AVR) during checkout and I'd love to try that out. So, the question is - how on earth do I package up code for something like that? I've seen a number of people ask the same thing for large manufacturing scales / similar setup where they don't fancy using the arduino & IDE as a programmer.

I've asked around on IRC and various other places but nobody seems to be able to give me specific and clear advice on whether it's possible and how to go about doing it.


texts: Reset Button not working + Can't Upload code , What is wrong?

texts:
I was testing and debugging a code I wrote for a robot with 3 stepper motors on  (Arduino Uno + CNCShield V3 + a4988 stepper drivers). I want to disable drivers at will. so I bypassed EN pin on 2 of a4988s to pin12 and pin13 of Arduino. (by defalut all EN pins of drivers are are connected to pin8 ) everything was ok but suddenly the Reset button is not working and I can't upload new codes to Arduino! I get this error:

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x83
.
.
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x83
Problem uploading to board.

but Arduino still is working with the last code that was uploaded to it!!! have I fried my Arduino? and Why is this happening?


texts: How long does it takes for arduino to reach main()?

texts:
I am trying to emulate the behavior of a circuit using an Attiny85

This is the result I got so far:

In the picture above, D2 is VCC, D4, D5 and D6 are outputs of the circuit I am trying to emulate. D7 is the output of Attiny85

The code I am using is:

#define F_CPU 8000000L
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>

int main() {

  DDRB = 0b00001000;

  PORTB = 0b00001000;
  _delay_ms(5);

  PORTB = 0b00000000;
  _delay_ms(5);
  PORTB = 0b00001000;
  _delay_ms(5);

  PORTB = 0b00000000;
  _delay_ms(5);

  _delay_ms(5);

  while(1)
  {
     PORTB = 0b00001000;
    _delay_ms(1);
     PORTB = 0b00000000;
    _delay_ms(1);
  }
    return 0;
}

According to this, it takes roughly 64ms from powerup until it actually run the main program.

Is there any reason for such a delay? How can I reduce it somehow (ideally to 20ms or less)?


texts: Using N mosfet to switch ESC to BLDC phases

texts:
I have an ESC that powers 36v 3 phase BLDC motor. The ESC has limited functionality and can power motor only in one direction. If I switch manually two of the ESC to Motor phase connections, than the motor direction will change. Now, I want to do the same i.e. switching phase to phase connections with 4 power mosfets.

As in scheme, the blue ESC phase will be connected to Mosfet source and the drain will be connected to Motors yellow phase. The next mosfet will connect to ESC yellow at source and motor blue at drain.  Two other mosfets will connect blue to blue and yellow to yellow.

I won't  do the switching while motor is on so I assume it should be safe.

How can I connect MOSFET's gate to Arduino ?
I need no pwm just ON/OFF.


texts: Nordic nRf905 (433MHZ) with arduino receive garbage data

texts:
I am interface Arduino with nRf905 in receive mode use 433 MHZ.

I Have follow this link http://www.electrodragon.com/w/NRF905_Transceiver_433MHz-Wireless_Module.

And for transmitter, I am use RF-Transmitter-Door-Window-Sensor which works on 433MHZ.

Now, Arduino receive garbage data I have attached snapshot of received data.

I am quarry about to set address and 433MHZ.

My config_buffer is:

unsigned char config_info_buf[10]={
      0x4C,
      0x01,                   //output power 10db, resend disable, Current
      0x44,                   //4-byte address
      0x20,0x20,              //receive or send data length 32 bytes
      0x21,0x11,0x11,0x00,
      0x18,
};

Question is there are 0x4C set exactly 433MHZ.

Any help will be appreciated.

Regards,
rajneesh


texts:
I'm trying to flash the repetier Firmware to my Prusa i3 3D Printer, which uses Melzi 2.0 board. I uploaded it successfully 2 days ago with same settings  but now is failing always.

@avrdude -p m1284p -b57600 -c arduino -P COM%x% -e -U flash:w:%filename%.hex
avrdude: AVR device initialized and ready to accept instructions
Reading | ################################################## | 100% 0.02s
avrdude: Device signature = 0x1e9705 (probably m1284p)
avrdude: erasing chip
avrdude: reading input file "newa.hex"
avrdude: input file newa.hex auto detected as Intel Hex
avrdude: writing flash (114266 bytes):
Writing |                                                    | 0% 0.00s
avrdude: stk500_paged_write(): (a) protocol error, expect=0x14, resp=0x64
avrdude: stk500_recv(): programmer is not responding

How do I solve this problem?