texts: Ultrasonic Sensor scanning too often resulting in a whirring noise

texts:
I am using an HC-SRO4 ultrasonic sensor for a wall-avoidance, maze-solving robot. However, I have recently run into an issue where I am getting a whirring noise from the sensor because it is taking measurements way too often.

This is the code I have right now:

const int serialPeriod = 250;       // only print to the serial console every 1/4 second
unsigned long timeSerialDelay = 0;

const int loopPeriod = 20;          // a period of 20ms = a frequency of 50Hz
unsigned long timeLoopDelay   = 0;

// specify the trig & echo pins used for the ultrasonic sensors
const int ultrasonic2TrigPin = 8;
const int ultrasonic2EchoPin = 9;

int ultrasonic2Distance;
int ultrasonic2Duration;

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

    // ultrasonic sensor pin configurations
    pinMode(ultrasonic2TrigPin, OUTPUT);
    pinMode(ultrasonic2EchoPin, INPUT);
}

void loop()
{
    debugOutput(); // prints debugging messages to the serial console

    if(millis() - timeLoopDelay >= loopPeriod)
    {
        readUltrasonicSensors(); // read and store the measured distances

        timeLoopDelay = millis();
    }
}

void readUltrasonicSensors()
{
    // ultrasonic 2
    digitalWrite(ultrasonic2TrigPin, HIGH);
    delayMicroseconds(10);                  // must keep the trig pin high for at least 10us
    digitalWrite(ultrasonic2TrigPin, LOW);

    ultrasonic2Duration = pulseIn(ultrasonic2EchoPin, HIGH);
    ultrasonic2Distance = (ultrasonic2Duration/2)/29;
}

void debugOutput()
{
    Serial.print("timeSerialDelay: ");
    Serial.print(timeSerialDelay);
    Serial.println();

    if((millis() - timeSerialDelay) > serialPeriod)
    {
        Serial.print("ultrasonic2Distance: ");
        Serial.print(ultrasonic2Distance);
        Serial.print("cm: ");
        Serial.println();

        timeSerialDelay = millis();
    }
}

and my wiring:

Link to product

Does anyone know why the scanning is happening constantly? It should only be happening every 1/4 of a second, not constantly. The weird thing is that this wasn't happening earlier before I started using the cable.

I believe it has something to do with the 8.5" extension cable I have (needed because I can't mount three sensors, one facing to each side and one in front, on a single breadboard). This is because when I mounted the sensor directly onto the breadboard, the delay was correct and the whirring was not present. However, as I just mentioned, I need the extension cable to be able to have the three sensors.

Does anyone have a solution for this?

Thanks!


texts: NodeMCU Exception 28 - intermitent problem

texts:
I am SOMETIMES getting exception 28 when running a web upload (over a very unstable rural internet CPE link - wifi is fine, but feed goes on and off):

Decoding stack results
0x40213b8c: dns_gethostbyname at core/dns.c line 1472
0x40204d95: ESP8266WiFiGenericClass::hostByName(char const*, IPAddress&, unsigned int) at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/libraries/ESP8266WiFi/src/ESP8266WiFiGeneric.cpp line 468
0x40208d7c: HardwareSerial::write(unsigned char const*, unsigned int) at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/cores/esp8266/HardwareSerial.h line 159
0x4020519c: WiFiClient::connect(char const*, unsigned short) at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/libraries/ESP8266WiFi/src/WiFiClient.cpp line 98
0x40208fe0: Print::println(char const*) at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/cores/esp8266/Print.cpp line 190
0x402040c4: uploadAgrigis(char const*) at /home/tony/Arduino/sketches/tempo1_vs12b_Master_NodeMCU_Rain_Wind/tempo1_vs12b_Master_NodeMCU_Rain_Wind.ino line 360
0x40208f41: Print::write(char const*) at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/cores/esp8266/Print.h line 60
0x40208f6c: Print::println() at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/cores/esp8266/Print.cpp line 178
0x40204a2b: loop() at /home/tony/Arduino/sketches/tempo1_vs12b_Master_NodeMCU_Rain_Wind/tempo1_vs12b_Master_NodeMCU_Rain_Wind.ino line 258
0x402074f0: TwoWire::endTransmission() at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/libraries/Wire/Wire.cpp line 151
0x40203a04: BH1750_Init(int) at /home/tony/Arduino/sketches/tempo1_vs12b_Master_NodeMCU_Rain_Wind/tempo1_vs12b_Master_NodeMCU_Rain_Wind.ino line 1121
0x40209d3c: loop_wrapper() at /home/tony/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/cores/esp8266/core_esp8266_main.cpp line 125

My code at line 360 is

if (client.connect(serverName,80)) {

My current strategy is to keep the wifi connection open all the time.  Should I test for connection before attempting to connect to the server?


texts: How to send latitude and longitude as text message on mobile?

texts: I want to check speed at certain time interval, if speed is greater than certain (speed) value then send latitude and longitude as text message


texts:
How do I find out the elapsed time from the serial Plotter graph? I am plotting sensor values from the Arduino Nano and would like to know the time scale on the x-axis in order to calculate settling time of oscillations.
I have tried the suggestions here but they do not seem to work in my case.

For example, in the graph below I would like to find out the time it took for the sensors to record their first movement at around point 190.

I am doing the following to print two values:

   //printData1();
   Serial.print(roll_err);
   Serial.print(" ");
   Serial.println(pitch_err);
   Serial.print(" ");

Baud Rate: 9600
Loop Time: 40ms

If my loop time is 40ms then I was thinking that the total time would be 180*40ms. Is this reasoning correct?

Is there a better way to read the time elapsed in the serial plotter?

EDIT: Trying to get a 10ms 'grid'

As per the suggestion in the answer below I have tried running something similar to the following but the loop does not run at a constant time.

I tried to add Serial.print(((millis()/10)%2)*50); but as can be seen, the loop time is not constant.


texts: Cannot display a chr string using Wire.read() and u8g2.drawStr()

texts:
I'm still getting myself acquainted with C++, so I expect this is a very basic issue I'm facing. I've got an OLED screen connected to a Teensy LC and can display text on it just fine. The Teensy receives bytes via I2C, and I want to reassemble those bytes into strings and display them on the OLED.
My relevant code:
#define I2C_ADDRESS 4
char buf[16];

void setup(void) {
  Serial.begin(9600);
  Wire.begin(I2C_ADDRESS);
  Wire.onReceive(receiveData);
  u8g2.begin();
}
void loop(void) {
  // U8G2 setup code snipped
  // This line doesn't output anything on the screen:
  u8g2.drawStr(0, 0, buf);
  // This line does:
  u8g2.drawStr(0, 20, "Foobar!");
  u8g2.sendBuffer();
  delay(1000);
}

void receiveData(int byteCount){
  Serial.print("Data received: ");
  int i;
  for (i=0; i<byteCount; i++)
  {
    buf[i] = Wire.read();
    Serial.println(buf[i]);
  }
  buf[i] = '\0';
  Serial.println(buf);
}

In the receiveData() function, the Serial.println() within the for loop prints out each letter of the payload as it's received, one after the other - but the Serial.println() below the for loop, which in my estimation should print out the whole message, prints out a blank line. I presume that's related to the fact that the received string doesn't show up on the OLED display.


texts: Reading text from sd card is returning weird characters?

texts:
I have an ebook which is converted to a .txt file saved on an sd card which is connected to the arduino. I'm trying to display the words from the book on a 16x2 lcd display on word at a time. It works mostly except when it reads a word that has an apostrophe or a pipe symbol it does not display correctly to the lcd display or the serial output.

For example the word "author's" will be displayed as "authorâs" (edit: there is actually two boxes between the "â" and the s that is not displaying on this forum) on both the lcd display and serial output.

I've spent an entire day now with this one problem hopefully there is a mistake someone can pick up on :/

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

const int chipSelect = 53;

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

char nextChar;
String wordBuffer = "";

void setup() {

  lcd.begin(16, 2);

  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

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

  // see if the card is present and can be initialized:
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    // don't do anything more:
    while (1);
  }
  Serial.println("card initialized.");

  // open the file. note that only one file can be open at a time,
  // so you have to close this one before opening another.
  File dataFile = SD.open("datalog.txt");

  if (dataFile) {
    while (dataFile.available()) {

      nextChar = dataFile.read();

      if (isWhitespace(nextChar)){

        lcd.print(wordBuffer);

        Serial.println(wordBuffer);

        lcd.display();

        delay(500);

        wordBuffer = "";
        lcd.clear();

      }
      else{

        wordBuffer = wordBuffer + nextChar;
        wordBuffer.trim();
      }

    }
    dataFile.close();
  }

  // if the file isn't open, pop up an error:
  else {
    Serial.println("error opening datalog.txt");
  }
}

void loop() {
}


texts: Problem I²C Communication between Arduinos

texts:
My Problem seems to be that my I²C slave randomly disconnects.
I have an Arduino Due communicating with a Arduino Chestnut board (bought hardware).
I now measure data with the Due and then send the data via an I²C interface to the Chestnut. No other devices are on the I²C bus.

The problem is that I randomly receive the error code "2" from the endTransmission method which seems to imply that the slave device disapeared from the bus. The connection sometimes works fine, and then sometimes right after startup or some time later this error occurs. I measured the signals with an oscilloscope and the clock signal then is always low.

Has someone an Idea what could be the problem?


texts: Arduino Ethernet Shield 2 stuck on EthernetServer::begin()

texts:
I am currently trying to get the Ethernet Shield working on my Mega. I was trying to run the Webserver example but the program seems to stuck at one point, so I tried to start from scratch.

This is my test code:

#include <Ethernet.h>
#include <SPI.h>

byte mac[] = {
  0x90, 0xA2, 0xDA, 0x0F, 0xF6, 0x3D
};
byte subnet[] = { 255,0,0,0 };
byte gateway[] = { 2,0,0,1 };
IPAddress ip(2, 0, 0, 1);

EthernetServer server(80);

void setup() {
  Serial.begin(9600);
  Ethernet.begin(mac, ip, gateway, subnet);
  Serial.println("Ethernet started");
  server.begin();
  Serial.println("Server started");
}

void loop() {
  // put your main code here, to run repeatedly:
  Serial.println("Loop");
}

The output I get from the serial console is:

Etrted
Ethernet started

So I think the program gets stuck inside the EthernetServer::begin() function.
I am aware that there are earlier versions of ethernet shields which are not compatible to the mega, but the vendor of my shield says it is.

Also I don't understand, why it outputs the first line.

Thanks for your hints!


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

Can u guys edit the Sketch? Cuz if u try It on tinkercad with adding a potentiometer+ a button u will see he does the average after each value we acquired but i need to do that at the end...
I dont need explaining of how i should i do It cuz the teacher did that already but these are my skills D: if u guys can edit the sketch and solve this problem would be cool thx


texts: MQTT - Can lastwill be sent to multiple topics?

texts:
I'm using an ESP8266 as an IOT device, with MQTT to send status messages.
Each device have its own availability topic, to state its online or offline state ( needed for Home Assistant indication on web GUI )

Since multiple devices are present- I was wondering if a lastwill status can be sent for a joint topic to be monitored ( for example :"device_id:offline" )

my relevant part of the code defining a lastwill for devices topic is : mqttClient.connect(deviceName, user, passw, availTopic, 0, true, "offline")

EDIT1:
using PubSubClient.h


texts: Build a timer that starts and stops timing when 2 wires are broken

texts:
I need to build a timer that uses the breaking of copper strips to trigger its starting and stopping. The intention is to measure the speed of a rocket with this - it will break the first wire, starting the timer, and then break the second, stopping it.

I am using an Arduino Uno, and a couple of lengths of wire for now.

I can plug one wire into the 1st 5V power supply on the board, and the other end into one of the analog pins (AO), (and then the second wire into the 2nd 5v supply and A1) so that when it is pulled out of the pin socket, it is 'broken'. Is this the correct method to go about this, and if so, how do I tell the Arduino to look for those signals as its 'start' and 'stop' and then record the time difference accordingly?

So far, I have managed to read a signal from the wire using the Analog Read Signal tutorial on Arduino.cc (https://www.arduino.cc/en/Tutorial/AnalogReadSerial). I noted whilst watching the printed data that once the wire is removed from the pin, the voltage value slowly decreased, and held at around 290 (starting at 1023, as per the tutorial). Is this simply a side effect of not using a grounded potentiometer, but a wire?

void setup() {
  // set up comms:
  Serial.begin(9600);
}

void loop() {
  // check and read value of input:
  int sensorValue = analogRead(A0);
  Serial.println(sensorValue);
  delay(1);
}

I am new to Arduino, so please explain in detail, or point me to a thread that will! Thanks in advance for help!

UPDATE
Having played around with analogWrite some more, I have managed to get a situation where I can output the relative value from both A0 and A1. However, I am still struggling to make it operate as a timer.

// declare variables
unsigned long startTime, stopTime;
unsigned long totalTime = (stopTime - startTime);

void setup() {
  Serial.begin(9600);   // set up comms
}

void loop() {
  // check and read value of input:
  int sensorValue1 = analogRead(A0);
  int sensorValue2 = analogRead(A1);

  if (sensorValue1 < 1023) {
    startTime = micros();
    Serial.println(sensorValue1);
  }
  if (sensorValue2 < 1023) {
    stopTime = micros();
    Serial.println(sensorValue2);
  }

  Serial.println("Time: ");   // prints "Time: "
  Serial.println(totalTime);  // prints time value
    delay(1000);
}

I have also tried to convert this to use digitalRead rather than analogRead but have not had much success - I am still failing to get a time. I know my method is wrong, but have struggled to find guidance on how to correct it.

    // declare variables
boolean timingFinished = false;
unsigned long startTime, stopTime;

String strTime = "Time:";

void setup() {
  Serial.begin(9600);   // set up comms
  pinMode(7, INPUT);   // set up pin 7
  pinMode(6, INPUT);   // set up pin 6
}

void loop() {
  // check and read value of input:
  int sensorValue1 = digitalRead(7);
  int sensorValue2 = digitalRead(6);
  Serial.println(sensorValue1);
  Serial.println(sensorValue2);

  if (sensorValue1 = HIGH) {
    startTime = micros();
    Serial.println(sensorValue1);
  }
  if (sensorValue2 = HIGH) {
    stopTime = micros();
    Serial.println(sensorValue2);
  }
  unsigned long totalTime = (sensorValue1 - sensorValue2);
  String strPrint = strTime + totalTime;
  Serial.println(strPrint);      // prints "Time"

}


texts:
I have this code, in which I try to "glue" four bytes in order to construct an unsigned int. I shift left the bytes and "add" them using the OR operator.

unsigned long number1;
unsigned long number2;
unsigned long number3=0;

byte byte0 = 1;
byte byte1 = 40;
byte byte2 = 107;
byte byte3 = 238;

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

void loop(){
  number1 = byte1 <<8 | byte0 ;  //(=10.241 O.K.)

  //(should be 4.000.000.001, it produces 10.241)
  number2 = byte3 <<24 | byte2 <<16 | byte1 <<8 | byte0;

  //(should be 4.000.000.001, it produces 4.016.777.217)
  number3 = number3 | byte3;
  number3 = number3<<8;
  number3 = number3 | byte2;
  number3 = number3<<8;
  number3 = number3 | byte1;
  number3 = number3<<8;
  number3 = number3 | byte0;

  Serial.print("number1 = ");Serial.println(number1);
  Serial.print("number2 = ");Serial.println(number2);
  Serial.print("number3 = ");Serial.println(number3);
  Serial.println(" ");
}

The problem is that the OR operator applies only to byte1 <<8 | byte0 and ignores the rest. That is number1 and number2 appear to have the same value (10241).

I also tried "adding" them up separately, as shown with number3, but it also produces a wrong result as well.

I tried the same code in python, and it works fine.

byte3, byte2, byte1, byte0 = 238, 107, 40, 1
print byte1 <<8 | byte0
print byte3 <<24 | byte2 <<16 | byte1 <<8 | byte0

number3 = 0;
number3 = number3 | byte3;
number3 = number3<<8;
number3 = number3 | byte2;
number3 = number3<<8;
number3 = number3 | byte1;
number3 = number3<<8;
number3 = number3 | byte0;
print number3

So, the question is:

Why both number2 and number3 produce a false result?


texts:
I am trying to build a calculator with an Arduino, an LCD display, and a keypad. Getting inputs from the keypad is not the issue. Before I can add, subtract, multiply, or divide any two numbers, I want to make sure the calculator registered the given number. I am trying to program it (so far) so that I type in a number and press enter (the @ sign I assigned to my keypad) and the LCD prints out that number. As you will see, I attempted to devise a logic mechanism for the Arduino to recognize the typed number.

I thought since as you type more numbers the value of the first number typed increases by 10 fold each time (if you start by pressing 4 then if you press another number such as 5 following it, that 4 will become 40, and 400 if another number is pressed, etc...) I could multiply that number (and every following number) by 10, 100, 100, etc...

But it doesn't work and I need help so that the number can be collected by the Arduino.

Here's my attempt at it:

    #include <LiquidCrystal.h>
    #include "Arduino.h"
    #include "Keypad.h"

    int count = 0;
    int row = 0;
    int column = 0;

    //const int buzzer = 0;

    int value1;
    int value2 = 0;

    int spot1 = 0;
    int spot2 = 0;
    int spot3 = 0;
    int spot4 = 0;
    int spot5 = 0;
    int spot6 = 0;
    int spot7 = 0;
    int spot8 = 0;

    LiquidCrystal lcd(1, 2, 3, 4, 5, 6 );

    const byte ROWS = 4; //four rows
    const byte COLS = 3; //three columns
    char keys[ROWS][COLS] = {
      {'1','2','3'},
      {'4','5','6'},
      {'7','8','9'},
      {'%','0','@'}
    };
    byte rowPins[ROWS] = {10, 9, 8, 7}; //connect to the row pinouts of the
    keypad
    byte colPins[COLS] = {13, 12, 11}; //connect to the column pinouts of
    the keypad
    Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS
    );

    void setup() {
      //pinMode(buzzer, OUTPUT);
      lcd.begin(16,2);
      lcd.print("---Calculator---");
      delay(2000);
      lcd.clear();
      lcd.print("Value1: ");
      lcd.blink();

    }

    void loop() {
char key = keypad.getKey();

if(key != NO_KEY){
  lcd.print(key);
  if(key != '%' && key != '@'){
    count++;
  }
  else if(count == 1){
    spot1 = key;
  }
  else if(count == 2){
    spot2 = key;
  }
  else if(count == 3){
    spot3 = key;
  }
  else if(count == 4){
    spot4 = key;
  }
  else if(count == 5){
    spot5=key;
  }
  else if(count == 6){
    spot6=key;
  }
  else if(count == 7){
    spot7=key;
  }
  else if(count == 8){
    spot8=key;
  }

  if(key=='@'){
    if(count == 1){
      value1 = spot1;
    }
    else if(count == 2){
      value1 = (spot1*10)+(spot2);
    }
    else if(count == 3){
      value1 = (spot1*100)+(spot2*10)+spot3;
    }
    if(count == 4){
      value1 = (spot1*1000)+(spot2*100)+(spot3*10)+spot4;
    }
    if(count == 5){
      value1 = (spot1*10000)+(spot2*1000)+(spot3*100)+(spot4*10)+spot5;
    }
    if(count == 6){
      value1 = (spot1*100000)+(spot2*10000)+(spot3*1000)+(spot4*100)+(spot5*10)+spot6;
    }
    if(count == 7){
    }
    if(count == 8){
    }
    lcd.print(value1);
  }

  if(key  == '%'){
    count = 0;
    lcd.clear();
    lcd.print("Value1: ");
    lcd.blink();
  }
}

}

PS: If you know any better way to accomplish this goal, I would love to hear it.


texts: Find a time server for NTP to get the current time (EtherCard library)

texts:
There are lots of examples around how to connect with an NTP server, but I do not see how to find such an IP-address. From the examples I conclude I need to find it on for example pool.ntp.org, but I do not even see how to get IP-addresses out of there myself, let alone to let my Arduino do it. Of course I looked at the How do I use pool.ntp.org page, but it doesn't seem to say anything about finding IP-addresses.

Questions

  Is it possible to let my Arduino find a working NTP server (using the EtherCard library), and if so, how?
  All the examples I saw have an NTP server IP address hard coded, isn't that a bad practice and also a bad idea for a longer running project?

The code I currently find the easiest to understand is from the Arduino forum, and has an IP address hard coded.

I have an Arduino Nano ATmega328 with a ENC28j60 ethernet shield, and therefore use the EtherCard libray. I do know of existence of RTC devices but I would prefer NTP.


texts: Is the arduino hackable when using communication shields?

texts:
Let's say I have an arduino Uno connected to a W5100 ethernet shield. The arduino communicates with the ethernet shield using the tx0 and rx0 pins. When I upload a new script to the arduino using USB, it uses the same tx0 and rx0. So that made me think.

What if I run a script on my arduino that fetches some data from a webpage using HTTP requests but someone manages to hack into my server. Is it possible for the hacker to upload some kind of code to my server, which will erase (when fetched by the arduino) the old script and upload a new arduino script, by making the arduino think it's uploading a new script while it's getting data from the ethernet shield (or other communication shields?)

EDIT: Let's expand the question a bit.. How can I add security to my code to prevent this situation from happening?


texts: SIM900 + GPS Module making http rest calls

texts:
I am wondering if its possible to program a board that is developed using SIM900 and GPS module to make http rest calls.

I found this library. My question is, will I need a microcontroller for this ?


texts:
A byte stores an 8-bit unsigned number, from 0 to 255.

I can understand the following line:

byte b = B10010;  // "B" is the binary formatter (B10010 = 18 decimal)

But I also saw a use such as:

volatile byte state = LOW;

What does the last line mean here? Is that special for Arduino?
I mean LOW is not a 8 bit unsigned number. LOW is not a number here.


texts: (Arduino Uno) Is my code for a follow the sun project valid? We want the motor to stop when both photoresistors have the same amount of light

texts:
int RlightPin=0;  //pin for right Photoresistor
int LlightPin=1;  //pin for left Photoresistor
int TranslateAnalogR=0;
int TranslateAnalogL= 1;
#include <Servo.h> //Servo library.
int pos=90; //Declare and initialize the variable pos.
int servoPin=9; //Servo connected to pin 9
int servoDelay=10; //Time motor waits before working again.
Servo myArms; //Servo object called myArms

void setup() {
Serial.begin(9600); //Start serial communication.
pinMode(7,OUTPUT);
pinMode(servoPin,OUTPUT);
myArms.attach(servoPin);

}

void loop() {

Serial.println(analogRead(RlightPin));   //Write the value of the right photoresistor to the serial monitor.
TranslateAnalogR=analogRead(RlightPin); //Read the right photoresistor value

Serial.println(analogRead(LlightPin));    //Write the value of the left photoresistor to the serial monitor.
TranslateAnalogL=analogRead(LlightPin);  //Read the left photoresistor value

if(TranslateAnalogR=TranslateAnalogL){        //If Photoresistor Value is above 355 the motor will stop
myArms.write(pos); // sets the servo position according to the scaled value
delay(servoDelay);// waits for it to get to the position

}

if(TranslateAnalogR=!TranslateAnalogL && TranslateAnalogR>TranslateAnalogL) { //If Photoreistor R is not equal to L and higher than L move until equal
for (pos=0; pos>=40; pos=pos+1)  {
  myArms.attach(servoPin);
  myArms.write(pos); //send servo to pos
  if(TranslateAnalogR=TranslateAnalogL){
  myArms.detach();}
}
}

if(TranslateAnalogL=!TranslateAnalogR && TranslateAnalogL>TranslateAnalogR){    //If Photoresistor L is not equal to R and higher than R move until equal
for (pos=0; pos>=40; pos=pos-1){
   myArms.attach(servoPin);
   myArms.write(pos); //send sevo to pos
   if(TranslateAnalogL=TranslateAnalogR){
   myArms.detach(); }

}
}

}


texts: Are there documented Arduino class or file name restrictions?

texts:
I ran into a strange problem were the compiler could not find a header file that I knew existed.

The problem was I created a class called ArduinoEvent and put it in ArduinoEvent.hpp,  but when I tried to include it in a client file, the compiler complained that the file did not exist.

In file included from sketch/NetworkConnection.hpp:4:0,
                 from /home/john/development/arduino/esp_pump_monitor/app.ino:4:
sketch/MyEvent.h:5:28: fatal error: ArduinoEvent.hpp: No such file or directory
 #include "ArduinoEvent.hpp"
                            ^

After realizing that the compiler copies the files into another directory,  I took a look and found that it had copied the ArduinoEvent.hpp file to
ArduinoEvent.hpp.cpp.  Since all the other files were copied fine, I simply renamed the file to BrduinoEvent.hpp and then everything was fine.

After searching I could not find anything that would imply that I could not name a class / file ArduinoBlah, so I was going to open an issue, but wanted to see if this restriction was documented somewhere and I just could not find it.

Update

I originally assumed the problem was due to the file being called ArduinoXxxx, but I hit this again with another file.  I think the issue is related to the files being in the "top" folder.  I noticed the process copies the xxx.ino files to xxx.ino.cpp,  so I think that's what is happening and somehow it thinks various files are .ino files while they are not.  As a workaround I moved all my class files to a lib folder and include them from there #include "./lib/xxx.hpp" for example.  This seems to be working.


texts: Store floats in and reading them from flash

texts:
How do I store floats in flash and how do I read them from there? (I need a look-up table for pairs of float values.)

The storing part doesn't seem to be so difficult as this compiles:

PROGMEM float value1 = 1.23456;

But how do I read them? Do I need to copy them byte by byte to a float variable, or is there a better way? (I am using an Arduino ATmega 328p with 4-byte floats.)


texts:
I'm generating a square wave with my Arduino UNO using the following:

#define pin 10 // data pin to control servo

// pulse width (in microseconds)
int pulsewidth = 2500; // 400 Hz

// wave period in microseconds
int period = 20000; // 50 Hz

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

void loop() {

  // turn pulse on for pulsewidth duration
  digitalWrite(pin, HIGH);
  delayMicroseconds(pulsewidth);

  // turn pulse off
  digitalWrite(pin, LOW);
  delayMicroseconds(period - pulsewidth);

}

When I check the wave freq on the scope it's reading something like 115Hz instead of 50Hz; however, the pulsewidth is correct (4Hz).

Why is this exactly?  Is it because digitalWrite() is slow?


texts: OTA mDNS issues with ESP8266 and PlatformIO?

texts:
The common useage of the OTA library for this MCU is to have it connect to a network, and to then use a computer on that network to upload firmware across that network. Due to either issues with PlatformIO (my IDE of choice right now) or my router (administrated by my ISP) blocking discovery (mDNS does NOT work here either way, and getting the IP is very hard as a result*), I would like to use the SoftAP class to make an access point that I can connect to directly when uploading firmware.

However, I have attempted this, and it does work IF I specify an IP address. This is a bit more convenient, but it fails if I try using mDNS again (via upload_port = myesp8266.local). (As an aside, this means that OTA over SoftAP does work, at least to this degree. I'm sure some will find this useful.)

Has anyone else confirmed either of these issues? I understand that they may be unrelated (since problem one is (Network || PIO) and the second is (PIO || SoftAP) as the cause), but any information as to why this might fail in both cases would be useful.

So, for the first case, can someone who uses that IDE and has an ESP8266 board test if mDNS works with the IDE?
For the second, assuming that mDNS does work with the IDE in the first case (and it's thus the MCU's fault), can anyone determine why the SoftAP class either halts or fails to work with mDNS?

This will really help my abilities to easily get firmware onto the board, and also tell me if I need to get a new router that allows mDNS (if it's not PlatformIO in the first case).

*Since the ISP administrates the router, I am unable to log in and view the IP addresses currently connected. My only option is printing it via UART, which renders this pointless, or attaching a OLED or LCD screen to every single device I build, or get a new router, which is its own issue right now. I've now run the web server test again, and not only does OTA not work with mDNS, but apparently I can't access it at all unless I know its actual IP address.


texts: Arduino Nano and SIM300 module for http calls for location

texts:
I am new to Arduino and SIM300/900 world. But I see that there is a possibility of building a vehicle tracker (approximate locality since I will use GPRS network location) using just these 2 boards.

My question is, is my assumption correct ? Can I build a vehicle tracker using just Arduino Nano and SIM300 mobule ? Is there a board that has both of them on one board so that I dont have to buy them separately ? Cost is a major factor on the decision.


texts: DC motor makes noise but does not rotate

texts:
i am following Jeremy blum's tutorial on youtube. link i have done the exact same circuit design as he has.

but the dc motor just makes a continuous beep sound when i run this code.

int motorPin = 9;

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

void loop()

{
    for(int i = 0; i <= 255; i++)
    {
        analogWrite(motorPin, i);
        delay(10);
    }

    delay(500);

    for(int i = 255; i >= 0; i--)
    {
        analogWrite(motorPin, i);
        delay(10);
    }

    delay(500);
}

I am clueless as to why this is happening. would be glad if someone could help me out here.


texts: Lowering delay when sending multiple SMS

texts:
I would like to use Arduino for bulk SMS sending. Right now, when I'm sending an SMS with 160 characters, I have to delay the sending of the next one for 9500 milliseconds. If I don't do that, some of the messages do not get sent. Is it possible to somehow lower that delay (by changing my code, using a different Arduino or SIM model, etc)?  I am using Arduino Uno and SIM800L (external power supply). This is my code.

#include <SoftwareSerial.h>

#define SIM800_TX_PIN 11
#define SIM800_RX_PIN 10

//Create software serial object to communicate with SIM800
SoftwareSerial serialSIM800(SIM800_TX_PIN,SIM800_RX_PIN);

void setup() {
  int a;
  String b =  "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam eu eleifend nunc. Suspendisse eget eros metus. Nunc ut nunc vel enim placerat egestas. Sed molestie, sapien sit amet bibendum --";
  String d = "";
  int textLen;

  Serial.begin(9600);
  while(!Serial);

  serialSIM800.begin(9600);

  for (a =1; a < 5; a++) {
    textLen = b.length()+2;
    char c[textLen];
    d = "";
    d = b + a;
    d.toCharArray(c,textLen);
    serialSIM800.write("AT+CMGF=1\r\n");
    delay(200);

    serialSIM800.write("AT+CMGS=\"+381*******\"\r\n");
    delay(200);
    //Send SMS content
    serialSIM800.write(c);
    delay(200);

    //Send Ctrl+Z / ESC to denote SMS message is complete
    serialSIM800.write((char)26);
    delay(9500);

    Serial.println("SMS Sent!");
  }
}

void loop() {
}


texts: How to fix baud rate when hardware capacity has a low limit?

texts:
I have a transmitter(simple 433 MHz transmitter) connected via digital pins on the Arduino. The receiver is connected to another arduino.
Now, I kept that pin on HIGH for 1 second, and it transmits only 1000 ones.
But I've seen different example transmitter sketches having baud rates of 1200, 9600, etc.
So the situation is, when the transmitter is transmitting at maximum capacity(just HIGH for a whole second), it can only transmit 1000 ones.

I am able to read that it only transmits 1000 ones because my receiver just has a simple read function that reads and prints the data. and it prints 1000 ones every second. Give or take one or two.
So when you specify a baud rate of 1200, is it useless? how will it transmit 1200 bits/sec?
Does the baud rate actually increase the hardware limit or what exactly is going on? Can someone please provide me some insight into this? I'd be glad to clarify this question more if need be.


texts:
Program reads rotary encoder correctly without bouncing in this code:

int val = 0;
byte clkPin = 3;
byte dtPin = 2;
bool lastClk;
bool lastDt;
void setup() {
  pinMode(clkPin,INPUT);
  pinMode(dtPin,INPUT);
  lastClk = digitalRead(3);
  lastDt = digitalRead(2);
  val = 0;
  attachInterrupt(digitalPinToInterrupt(clkPin), clkRise, RISING);
  Serial.begin(9600);
}

void loop() {
}

void clkRise(){
      lastClk = HIGH;
      lastDt = digitalRead(dtPin);
      if(lastDt == LOW){
        val--;
        Serial.println(val);
        }  else{val++; Serial.println(val);}
        }

but when i use lcd to show the result, i get massive bounces (i think) in this code:

#include <LiquidCrystal_I2C.h>

#include <Wire.h>

LiquidCrystal_I2C lcd(0x27,20,4);
int val = 0;
byte clkPin = 3;
byte dtPin = 2;
bool lastClk;
bool lastDt;
void setup() {
  lcd.begin();
  pinMode(clkPin,INPUT);
  pinMode(dtPin,INPUT);
  lastClk = digitalRead(3);
  lastDt = digitalRead(2);
  val = 0;
  attachInterrupt(digitalPinToInterrupt(clkPin), clkRise, RISING);
  Serial.begin(9600);
  lcd.home();
}

void loop() {
  lcd.print(val);
}

void clkRise(){
      lastClk = HIGH;
      lastDt = digitalRead(dtPin);
      if(lastDt == LOW){
        val--;
        Serial.println(val);
        }  else{val++;}
        }

it increases and decreases by random numbers between 0-5.I use KY-040 R.E. it has built-in 10k pull up resistors.

This is what i use to debounce:

A or B pin of R.E--10k R----------------------------------Arduino INPUT PIN
                         |
                         |
                         =0.1uF C
                         |
                         ---------------------GND


texts: Converting between NEC and HEX values from IR receiver

texts:
I jacked one of the IR receivers from my LED strip and hooked it up to my ESP8266 NodeMCU (running Arduino code). I found a great library called IRremoteESP8266. With this library, I can basically receive and send IR signals. However, the HEX values I get in are different from the NEC values I have to send out.

Here's what I've got:

Serial.println((uint32_t) (results.value & 0xFFFFFFFF), HEX);

When I compile this and I open the Serial Monitor, I get D7E84B1B when I press the button on my remote. I searched for it on Google, and I found a site that shows this:

‘real’ decode: FF02FD, hash decode: D7E84B1B

So naturally I tried doing:

irsend.sendNEC(0x00FF02FD, 32);

and it works just fine. The code example for receiving and sending can be found on the repository.

How do I make a conversion between what I receive and what I send, so I can basically mirror what I do?

EDIT:

According to the website I got the real NEC value from, they simply do:

Serial.print(results.value, HEX);

However, when I try to do that, I get this error:

  call of overloaded 'println(uint64_t&, int)' is ambiguous

I know they are different projects, but the ESP8266 project I use is based off the IRremote library, which they seem to use.


texts:
Hardware- ESP8266 Based NodeMCU
I am using NTP Client for time in my alarm project.
I am facing an issue where NTP client is not returning proper values, in the sense that it works properly for the first few hours- returning the time every second, however after some time the values go haywire.
First few hours:-
21:00:45
21:00:46
21:00:47
21:00:48

After sometime:-
06:00:02
06:00:45
06:00:49

What could be the cause of this and how do prevent it?


texts: I have multiple components that are lagging

texts: I have multiple components such as LED's, Servos, ultrasound, and a photoresistor. For context, certain LED's light up and a buzzer makes a certain sound depending on the range of distance the ultra sound picks up and the servo moves based on the photoresistor data etc. They work just fine but they do not work at the same time. Data is collected one after the other but not at the same time like I want them to. Is there any way I can make them collect data at the same time?


texts:
I'm using an ESP8266 so I'm limited to 3.3v.  I've found a number of inductive proximity sensors but they require 5v or more.  Does a 3.3v sensor exist?

I recently dropped some tiny screws on dark carpeting and would like to find them instead of just vacuuming them up.  Stupid project?  Maybe.  But a good excuse to buy another sensor.


texts:
I am currently a first time Arduino user. I decided to get one and start prototyping basic types of circuits.

I have built various basic circuits with the Arduino Uno prototype board and it worked completely fine. I am using the Arduino board to source power to my circuit (5V). However, after building the following circuit, everything stopped working:

simulate this circuit – Schematic created using CircuitLab

I don't get output from any of the Arduino pins and I cannot upload programs to the board. The yellow LED still blinks, and the green power LED remains green and active.

I cannot figure out how I managed to burn the board. The current is around 22.72mA, which is pretty far of the 40mA absolute rating.


texts: Installing Ports for Arduino Nano on Mac OS X Yosemite

texts:
Just starting with Arduino and have gotten stuck at the first hurdle: trying to connect an Arduino Nano with my Mac Book Pro which runs 10.10. I can't seem to find the right port as all suggestions have bluetooth in the name and none with USB anything. Also the post list does not change when I plug/unplug the Arduino. Looking at http://arduino.cc/en/guide/macOSX#toc3 it says that I need to install FTDI software to get the USB port to show, however, having done this it still does not work. Any suggestions?

Thanks,
Calum


texts:
In Fast.Led lib for arduino there is a code to turn off all leds

FastLED.clear ();

Is there also a shortcut to turn all LEDs ON, and with a specific color


texts: I have read other posts regarding ArduinoJson that recommend using a library version no later than 5.14.3.  That recommendation is more than a year old - is it still the recommended library version?


texts: How can I communicate Raspberry Pi and Arduino (in both ways) using a 10-15m distance wires?

texts:
I am starting a personal project of home automation and I have a raspberry pi and an arduino Uno board.

I want communicate raspberry pi and my arduino where my raspberry should be able to write and read signals to and from arduino.

The distance between them I think its going to be something around 10 to 15 meters.

What do I need for it? what kind of wires or other components I'll need to achieve my goal? I repeat: I do not want to communicate raspberry pi and arduino wirelessly.

Thanks!


texts: make servo stay at the current position when attach() is called

texts:
I use a small SG90 servo with arduino.
When I call attach() servo moves to its default position or whatever I set with write() before it.

I’d like to make servo stay at the current position when I call attach() in setup().

How can I achieve it?

I believe I can simply store last position in EEPROM. It’ll help a little. However, I’m afraid that EEPROM won’t last long.


texts: Calling external function from a class function

texts:
I'll try to explain my need:

I have a generic library I created, called myIOT.h.
This class have a pre-configured  MQTT and wifi setup.
Inside this library there is a mqtt_callback function, for all generic commands, such as boot_time and connection_status.
BUT, this library serves in several of my iot device's code, that each one has a few more mqtt commands, that is tailored just for s specific device, and I looking for a way that iot.mqtt_callback(ext_mqtt_func) will get as parameter a local ( which belong to the sketch and not to the library ), that will have the additional code needed.

I'll try to explain more clearly:

void myIOT::mqtt_callback(ext_mqtt_func){
if (a == true ) {
do something

};

else {

ext_mqtt_func()); // calling another fucntion that belongs to sketch and not library

}


texts:
I've been trying to simulate a PID using Brett Beauregard's PID library in order to understand it better. Here is my code.

#include <PID_v1.h>

const unsigned int numReadings = 500;
double analogVals[numReadings];
unsigned int i = 0;
int angle = 0;
//Define Variables we'll be connecting to
double Setpoint, Input, Output;
//Specify the links and initial tuning parameters
PID myPID(&Input, &Output, &Setpoint,2,5,1, DIRECT);
void setup()

{
  //turn the PID on
  myPID.SetMode(AUTOMATIC);
  Serial.begin(115200);
  Setpoint = 300;
  myPID.SetOutputLimits(-2,2);
  myPID.SetSampleTime(100);
  Input = random(292, 302) ;
}

void loop()
{
  if (i % 2 == 0) {
  Input += random(-2,3);
  }
  angle += 1 % 360;
  Input += sin(angle*355/(113*180));
  myPID.Compute();
  Input += Output;
    analogVals[i] = Input;
    i++;
    if (i>= numReadings)
    {
      for (int j = 0; j < i; j++) {
      Serial.println(analogVals[j]);
      }

      i = 0; //reset to beginning of array, so you don't try to save readings outside of the bounds of the array
    }
}

Even if I restrict the output of the PID to a very small value, I get huge nonsense results of this code. It oscillates like -1000 to 1000. I've read this https://robotics.stackexchange.com/questions/167/what-are-good-strategies-for-tuning-pid-loops
and tried to adjust my parameters, but they're just shots in the dark really, I can't even damp these massive oscillations. How would I tune a PID to cancel out a sin error ?

Thanks in advance


texts: How can a DC motor (toy) be run with only an Arduino and transistor without an external power source?

texts:
I'm trying to understand this circuit found here.

I understand that the Arduino cannot directly run a DC motor because it can only supply 40mA of current and also due to the back EMF which can damage it. I can also understand this circuit if they used an external power supply and used the transistor as a switch to drive the DC motor. But, I do not understand this configuration shown in the pic where the power supply is the arduino itself.


texts: Soldering Arduino Pro Mini's disaligned pins

texts:
I have a couples of Arduino Pro Minis (original from sparkfun) that have those 4 disaligned pin. Unfortunetely, I need to use 2 of them, A4 and A5, because they are the I2C pins and I want to solder them onto a perf board.

Now, I really want to use headers and I do not want to solder any wire directly to it. I also do not want to add headers facing up on the board because I am trying to minimize space. Last, I am not willing to change Arduinos so please do not suggest me to use an Arduino Nano or Pro Micro.

So I would like to know if there is a way to connect those 2 pin to the perf board via headers or is there any alternative pins that I can use to connect and use the I2C interface.


texts: String(int) function stopping the Arduino

texts:
Well I am trying make an application with arduino leonardo and GSM Shield. There are conditions if, else if, else .. etc
  if (smsMetni.indexOf("DURUM") != -1) {
    Serial.println("SMS income");
    String temp= String(analogRead(LM35_pin) * 0.48828125);
    String temp2 = "Hava " + temp + " derece.";
    char tempSMS2[] = "";
    temp2.toCharArray(tempSMS2, 30);
    Serial.println(tempSMS2);
    Kapadokya.smsGonder(gonderilecekTelNumarasi, tempSMS2);
  }

After the last line "Kapadokya.smsGonder(gonderilecekTelNumarasi, tempSMS2);" program stopping I watching serial monitor there is no notification or error. just stopping.
If I change those lines and remove String(analogRead(LM35_pin) * 0.48828125) :
    String temp= String(analogRead(LM35_pin) * 0.48828125);
    String temp2 = "Hava " + temp + " derece.";

and just write like this, it works very well.
String temp2 = "Hava  derece.";

maybe you think there is a problem with LM35, even if I change it String(analogRead(LM35_pin) * 0.48828125); with String(30);, it doesn't work again. after the last line it is not continue.
only one sollution I've found if add delay(500) after each line it works but my codes looks ugly with this. are there any solution.


texts: programming attiny88 & attiny828 with arduino

texts:
I found some information that the attiny88 and attiny828 can be programed from an arduino, similar to the programing of the attiny85/45, simply connecting the right pins. https://electronics.stackexchange.com/questions/98970/how-to-program-atmel-attiny88-not-45-or-85

However, what I have not been able to find out are the arduino cores (drivers) for the attiny88 and attiny828.
I wonder if the cores (or drivers) to program the attiny88 and attiny828 from an arduino are available somewhere or would they have to be constructed?.


texts:
I am sending some data over an NRF24 link, using the RF24Network  library. So far I have only sent numbers, now I also want to send a string, so I have set up my payload struct as

struct payload_t {                  // Structure of our payload
   unsigned long data;
   unsigned long datatype;
   char sensorid[20];
   unsigned long counter;
};

As far as I do understand, I can not use string here, since I need to know the length of the data I am sending.

At the moment I am using sensors without an internal ID, so in loop(), I am calling:

 writeToNetwork(voltage,'v',"nosid",packets_sent++);

My writeToNetwork function is defined as

 bool writeToNetwork(unsigned long data,unsigned long type,char sid[20],unsigned long package){

and within that, I am setting up the payload with

 payload_t payload = { data,type,sid, package };

Which gives me an

 error: invalid conversion from ‘char*’ to ‘char’ [-fpermissive]

Clearly, I have no interest of the address the pointer is referencing, so I need to somehow dereference the sid - pointer to get my array into the struct. How can I do that?

Or am I barking up the wrong tree? I tried to transfer the id as a string:

#include <string.h>
bool writeToNetwork(unsigned long data,unsigned long type,String sid,unsigned long package){
char sidchar[20];
sid.toCharArray(sidchar,20);
payload_t payload = { data,type,sidchar, package };

Which gives me the error

array must be initialized with a brace-enclosed initializer

Which I do not understand. Doing

char sidchar[20]={0};

gives me the same error.


texts:
I have a variable timeInSec which records the time as loop begins. It is defined as timeInSec = millis();. I have two conditions. If (timeInSec - lastRun)< 5 (that is 5 sec) , the first condition is executed(the if statement).Otherwise if (timeInSec - lastRun)>5 the second condition is executed(else statement). Here is the code:

void loop(){
  timeInSec = millis();  // Records time in seconds
  // if(lastRun > 0) {   // if i run this, only else statement is executed
  // delay(10000);
  // }
  if((timeInSec - lastRun) < 5000){  // Treshold time (if condition which runs when timeInSec is less than 5 seconds)
    // Some code
  }
  else{ // If treshold time exceeds (executes when timeInSec is > 5seconds)
   delay(10000);  // if i run this, only else statement is executed
   lastRun = timeInSec;
  }
}

Here the else statement executes once and control goes back if statement again. I want to pause the control at else statement for 10 seconds and then go back to if statement for further execution. Everytime  the control should pause at else statement for 10 seconds. I have used delay in the else statement and in this case only else statement is being executed. The same happens if I use delay at the start of loop (as in code). I have tried without using delay but didn't succeed.

Thanks for the help!


texts: I've been tinkering for quite a while and I'm looking to try out an arduino to control an automated small garden project for growing seeds. I've never done any coding before and am looking for some advice on what hardware/software I should use that's easy to learn and will work for my application. My idea is to have an arduino control a lighting and sprinkler system that would work on timers to be on or off at specific intervals with the potential to be upgraded in the future to run off moisture sensors when I feel more confident in my coding abilities. I'm trying to keep this project on a budget so the Arduino nano is tempting because of its price point but could it do everything I want? Any advice or recommendations are welcome, thanks.


texts: display pixel data on serial monitor using ov7670

texts: i am trying to get the image data pixel by pixel from ov7670 to serial monitor and to store it into arduino memory which i can access later. i am using arduino mega and the camera is configured to 160x120 resolution. Any suggestions or code from which i can get help from?


texts: How send method POST with JSON? Arduino UNO R3 + SIM900

texts:
Why is the server side of php not loading any data from arduino? What did I do wrong?

  String reading="{\"latitude\": 12.983027,  \"longitude\": 80.2594}";
  mySerial.println("AT+HTTPINIT");
  toSerial(1000);

  mySerial.println("AT+HTTPPARA=\"CID\",1");
  toSerial(1000);

  mySerial.println("AT+HTTPPARA=\"URL\",\"http://gerro.usermd.net/updateData.php\"");
  toSerial(1000);

  mySerial.println("AT+HTTPPARA=\"CONTENT\", \"application/json\"");
  toSerial(1000);

  mySerial.println("AT+HTTPDATA=" + String(reading.length()) + ",100000");
  toSerial(5000);

  mySerial.println(reading);
  toSerial(1000);

  mySerial.println("AT+HTTPACTION=1");
  toSerial(15000);

  mySerial.println("AT+HTTPREAD");
  toSerial(1000);

  mySerial.println("AT+HTTPTERM");
  toSerial(500);

Result:

AT+HTTPINIT

OK
AT+HTTPPARA="CID",1

OK
AT+HTTPPARA="URL","http://gerro.usermd.net/updateData.php"

OAT+HTTPPARA="CONTENT", "application/json"

OK
AT+HTTPDATA=46,100000

DOWNLOAD

OK
AT+HTTPACTION=1

OK

+HTTPACTION:1,200,55
AT+HTTPREAD

+HTTPREAD:55
array(0) {
}
array(0) {
}
nic ciekAT+HTTPTERM

OK

EDITING

void toSerial(int delay_ms)
  {
    delay(delay_ms);

    while(mySerial.available())
    {
       Serial.write(mySerial.read());
    }
  }

PHP

<?php
var_dump($_POST);
if (isset($_POST['latitude']) && isset($_POST['longitude']) && $_SERVER['REQUEST_METHOD'] === 'POST') {
//code
} else {
echo 'nic';
}


texts: Problem in bootloading my ATmega32U4 chip

texts:
I have developed my own development board using ATmega32U4. I want to bootload my ATmega32U4 and hence I used Arduino Uno to bootload it. I have given the connections as per
https://www.arduino.cc/en/Tutorial/ArduinoISP
 and I followed this instructions:

Open the ArduinoISP firmware (in Examples) to your Arduino board.
Select the items in the Tools > Board and Serial Port menus that correspond to the board you are using as the programmer (not the board being programmed).
Upload the ArduinoISP sketch.
Wire your Arduino boards..
Select the item in the Tools > Board menu that corresponds to the board on which you want to burn the bootloader (not the board that you're using as the programmer). See the board descriptions on the environment page for details.
Select the Arduino as ISP in the Tools>Programmer menu.
Use the Burn Bootloader command.

But I am getting the error message as

avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

I am using 16Mhz crytsal oscillator along with 22pf

What might be the problem?


texts: Does the position in which you mount an IMU matter?

texts:
Forgive me, I'm sure this is a total noob question, but I have never seen it actually addressed in any example or demo.

When using something like a MinIMU-9 board (https://www.pololu.com/product/2738/), does it matter what position you mount the board on your project?  I mean, does it have to be positioned so the proper axes line up with the axes of your vehicle, or is there some calibration to set that alignment?

For a ground vehicle where I will concerned primarily with only one axis, are all axes interchangeable?


texts: Which battery should I use to power arduino+motor shield + two 200 RPM (3.6V/1.5A)motors

texts:
I am using two motors ( from old two drill machines - same kind, these are 3.6v motors ), connected to arduino + arduino motor shield seeed studio v2.

When I measured the both motors (indvidually) using a multimeter in series with your motor and an about 3.6V power supply, I found that the both are varying from 1.46A-1.47A, (I supposed it as 1.5A)

I tried to use 18v/1.2a battery that was laying at home (from old machine ) what I have noticed is that motors are running for 3-5 seconds than stop, one of the red lights start blinking in the motor shield, then it stops for 3-5 seconds then it works again and loop.

Notes:
- The motors are working when I connect them directly to 4.5 or 6v battery. But when I try to assemle everything , it doesn't work (I am adding this just to say that motors are in good health).

I tried 14v battery I noticed the same thing.
The drill machine is small one (as big as a human hand). Motors from electric drills are designed as high-speed high-torque motors, but I don't think it's too high in my case to be a huge problem. It's 200 RPM DC motor
I spent a week looking for answer before posting this thread, I tried every single solution I came across on the web.

What are things that I should consider here, any thoughts.

What did I miss? And what kind of battery should I use ??


texts:
My operating system : OS X EL CAPITAN

Please help I was trying to do project 05 Mood cue of the arduino starter kit. I completed setting up my board and writing the code and when I tried to upload I got this error message:

Arduino: 1.7.10 (Mac OS X), Board: "Arduino Uno"

Sketch uses 1,030 bytes (3%) of program storage space. Maximum is 32,256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.
avrdude: ser_open(): can't open device "/dev/tty.usbmodem1411": Device not         configured
ioctl("TIOCMGET"): Inappropriate ioctl for device
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

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

Can someone please help me?


texts: Transferring stuff from the Uno to the Lilypad

texts:
So I have a project midprogress using the Uno and I need to move it to the Lilypad.
My questions are:

Will the code mostly work the same?

I'm currently using this IMU chip to get data about my user, how do I take the data gathered from this and transmit over bluetooth. (Chip recommendations, and how does having multiple RX/TX work?) Can't find any documentation on that.

Thank you.


texts: ESP32 + distance sensor only works when disconnecting & reconnecting cable after code upload

texts:
I'm trying to set up my ESP32-WROOM-32D to use an AJ-SR04M ultrasonic sound distance sensor but am having some difficulties.
Using Arduino IDE with NewPing and the below code, distance measurements work fine, but only when I connect power of the AJ-SR04M after code upload:
#include <NewPing.h>

#define TRIGGER_PIN 4
#define ECHO_PIN 0
#define MAX_DISTANCE 400

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

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

void loop() {
   delay(50);
   unsigned int distance = sonar.ping_cm();
   Serial.print(distance);
   Serial.println("cm");
}

When the distance sensor is connected at the time of code upload, nothing happens (no output on serial console, no LED on the sensor).
When I perform a code upload and afterwards connect +5V, then all works fine.
I tried on an Arduino Uno as well; there this limitation does not apply.
What's going on - how can I get this to life without the need to disconnect/connect my sensor every time?


texts:
I want to create a Wi-Fi hotspot and redirect all connections to a custom login page.

I would like to know if the Arduino Yún is a good choice in this case?


texts: ILI9341 backlight flickers when using USB power from Laptop

texts:
I've developed a project using am ILI9341, ESP12F and Arduino. Everything works fine except a very annoying issue. The LCD flickers when I use the laptop's USB. But when I use a USB charger it's much better.
I use https://github.com/Bodmer/TFT_eSPI library for SPI driver and AMS1117 as regulator (with 1uf in the input, and 10uf in output).
I don't think the software has a problem because I don't refresh anything on the display (just draw something in the setup function, not in loop) and also it changes with different power sources. The problem is the backlight.
When I move the USB cable it goes crazier sometimes. I've checked it with many different cables and computers. Is this because of noise or something from the USB port? How can I fix this?
It's very important for me to be able to use the USB port as the power source.
Update
When I'm uploading the code to the ESP8266 (using TXD & RXI), the LCD doesn't flicker event a little bit! And immediately after finishing the upload, the LCD brightness decreases and starts flickering!
The circuit is pretty simple and LCD pins are connected directly as listed here


texts: Programmer only uploading with its own power source

texts:
Can anyone explain to me why the following occurs (See image below)?

When I connect the pins according to situation 1, everything works fine and I am able to upload my project. However when I connect the pins according to situation 2 it gives me the following error:

  wrong direction/command: 0x00 0x08, expected 0x01 0x08 esp8266

Both supply the same constant 3.3V and after the project is uploaded it runs with the pins connected as in both scenarios.

(All the other factors are constant in both scenarios. Think of pulling down IO0 etc.)


texts:
TARGET

The task I have taken as a challenge is to make a GPS-guided robot incorporated with features like Arduino for programming, ultrasonic sensors for obstacle avoidance and a GPS module to specify the way points location (from starting point to end point).

This robot should be able to avoid both static and moving obstacles while moving to its end point assigned from the GPS. I have found the robot  manoeuvring around both static and moving obstacles to be a bit challenging. I was wondering if there is an effective obstacle avoidance algorithm that I can use.

I will appreciate it if I could get some helpful suggestions and insights.


texts: Replacement crystal on Uno for cold temperatures

texts:
I want to run an arduino out in the cold (-40), and use the serial communication - I believe that the crystal is the weakest link (the one for the serial chip) - however I don't see any drop-in (through-hole) replacement crystals that would work in such cold, so would a SMT version work instead? if so, which one would be possible to solder (package?), and do I need to change the caps to match?

P.S. - Yes, I could heat it/insulate it, but that comes at a fairly high power/complexity cost


texts: Arduino LED flashes with one button press

texts:
I want the LED to flash when I press the switch once, but it keeps flashing. I tried the idea of just lighting the LED and keeping it lit with just one button press, so I wrote:

int led=13,button=12;
void setup() {
pinMode(led,OUTPUT);
pinMode(button,INPUT);
}
void loop() {
if (digitalRead(button)==HIGH)
  digitalWrite(led,HIGH);
}

and this worked; it stayed on after I pressed the button once, so for the flashing LED I wrote:

int led=13,button=12;
void setup() {
pinMode(led,OUTPUT);
pinMode(button,INPUT);
}
void loop() {
if (digitalRead(button)==HIGH)
{
  digitalWrite(led,HIGH);
delay(1000);
 digitalWrite(led,LOW);
 delay(1000);

} }

but this didn't work. It stops flashing after I remove my hand from the switch. Why is this happening?


texts: Is there a good Arduino enclosure for that works with the Olimex MIDI shield

texts:
I have a MIDI project I put together using an Arduino UNO R3 and the Olimex Shield-MIDI.

I want to install the project permanently in my Guitar rack so I want a decent enclosure, but there doesn't seem to be anything that would support the extra height that the MIDI ports have, relative to the Arduino + Ethernet enclosures.

Has anyone come up with a good solution for Arduino + MIDI projects?  A metal enclosure would be a plus.


texts: How to read high voltage (40-65v) from a Solar Battery bank

texts:
I would like to monitor the battery voltage of a 48v solar battery system. The expected voltage range is 40-65v.

I have tried creating a voltage divider with 2 resistors but with all values I have tried one resistor almost melts as soon as you connect to battery.

Also, using a voltage divider creates a (small) drain which I would like to avoid.

Can anyone suggest a way of reading high DC voltage (40-65v) with and Arduino (really I'm using an ESP8266)?

If Voltage Divider

please suggest resistor types (e.g. 1/4watt or 1-2% etc, I'm new here but know there are many types) and values that I could read with A0 (analog pin, max 5v)

Can I use a MOSFET to connect the voltage divider just before reading the voltage? How?

or another way

like a circuit (from AliExpress) or using some other component that would be greatly appreciated.

So far this article has been helpful, it talks about a voltage divider with a opamp to get more accuracy, but I need a bit more advice from someone that knows more than myself.

https://openenergymonitor.org/forum-archive/node/11011.html

Thanks in advance for any help.


texts: nRF2401 communication (extended vs normal)

texts:
Communicating to the antenna-less version from an extended range nRF2401 seems to produce some strange results...

At a distance, the receiver seems to receive a number of values instead of one. For example, if I send a 1, I will receive a 1, but 30 times.

Has anyone had experience communicating across the two models, or is it just best practice to stick to communicating across same models? (Short range <-> short range, long range <-> long range)?


texts: Problem with serial connection. Data garbled

texts:
I have a hardware device that sends data over the serial port and over a socket connection.

I have the TX of the device connected to the RX of the ESP8266, RX of the device to TX of the ESP8266.

Comm speed is set to 115200 on both.

Code is nothing more than

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
}

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

I listen on the socket and on the serial port at the same time. On the socket port i get correct data (ASCII characters). On the serial monitor of the Arduino i get garbled data. Also, it looks like the Arduino IDE cannot cope with the volume of data. I am sending appx 100 char/sec.

Any ideas?

Update Aug 13 '18

Ok, I found out that I was trying to hook up an RS232 to an UART and that, to accomplish this, I need a RS232 to TTL converter like the max3232. I will go that road and update the question if I have it.

Ok, i found out that i was trying to hook up an RS232 to an UART and that, to accomplish this, i need a RS232 to TTL converter like the max3232.
I will go that road and update the question if i have it.


texts:
XRPM_COUNTERS.h:15:5: error: expected unqualified-id before string constant

     ISR(PCINT0_vect) {

     ^

In file included from C:\Documents and Settings\SAM\Desktop\automation_1_A_NEW_AAA\automation_1_A_NEW_AAA.ino:10:0:

XRPM_COUNTERS.h:72:1: error: expected ';' after class definition

 }

 ^

sketch\XRPM_COUNTERS.h: In function 'void XRPMLoop()':

XRPM_COUNTERS.h:77:19: error: 't' was not declared in this scope

   if ((millis() - t) > 300) rpm = 0;

                   ^

XRPM_COUNTERS.h:77:29: error: 'rpm' was not declared in this scope

   if ((millis() - t) > 300) rpm = 0;

                             ^

XRPM_COUNTERS.h:79:17: error: 'ot' was not declared in this scope

   else if (t != ot) {

                 ^

XRPM_COUNTERS.h:81:5: error: 'rpm' was not declared in this scope

     rpm = 60000.0 / (float)(t - ot);

     ^

XRPM_COUNTERS.h:87:13: error: 'rpm' was not declared in this scope

   lcd.print(rpm);

             ^

XRPM_COUNTERS.h:93:14: error: 'printVu' was not declared in this scope

   printVu(rpm);

              ^

sketch\XRPM_COUNTERS.h: At global scope:

XRPM_COUNTERS.h:97:1: error: expected declaration before '}' token

 };

 ^

exit status 1
expected unqualified-id before string constant


texts: Servos not working properly with joystick

texts:
So, I was working with a project in which I used a joystick module to control two servos at the same time. The joystick controls the servos in a way that when the joystick is moved along x-axis, both servos move in the same direction but when joystick moves in y-axis, the servos move in different directions. I have this program:

#include <Servo.h>
Servo servo1;
Servo servo2;
int joyx = 0;
int joyy = 5;
int joyval;
int joyvalx;
int joyvaly;
void setup() {
    Serial.begin(9600);
    servo1.attach(3);
    servo2.attach(5);

}

void loop() {
    Serial.println(joyvalx + "," + joyvaly);
    int x = analogRead(joyx);
    int y = analogRead(joyy);
    if(x != joyvalx){
        joyval = map(x, 0, 1023, 0, 180);
        servo1.write(joyval);
        servo2.write(joyval);
    }
    if (y != joyvaly){
        joyval = map(y, 0, 1023, 0, 180);
        servo1.write(joyval);
        servo2.write(1023-joyval);
    }
}

However, the servos don't seem to work properly. One servo works fine but the other just gets stuck. Also, if I use the code for only one direction (x-axis or y-axis) by removing the code for the other, then both servos work good. I can't understand the problem. If anyone does, please help me.


texts: Digispark green led being the only one to turn on

texts:
I was doing some tests with an ATtiny85 Digispark module using Arduino IDE on my Windows PC. I was testing some stuff with the DigiKeyboard library from Digistump.
Everything was going fine until suddenly the Digispark stopped working and wasn't able to upload code through the module anymore. Now when I plug it in my PC, the only thing that the module does is turn on the green led; besides, Windows doesn’t recognize the module when I plug it in anymore and doesn’t even appear in Device Manager as an unknown device or something.
I reinstalled the drivers but nothing changed. I also tried to reinstall Micronucleous into the ATtiny85 using Zadig, but wasn’t able to do it because Windows doesn’t recognize the module when I plug it in, so Zadig won't see it either.
Since I’m not very familiar with electronics, I’m not sure if there is any way to fix this or if it’s due to some physical damage, so any help or direction with how to deal with this would be really appreciated.


texts: is it possible to backup an uploaded program?

texts:
I have a cute robot built on Arduino Uno and Ardumoto, and I am trying to reverse engineer it first, and to add some new sensors afterwards.

I am stuck at how to deal with its program. I don't have the source code but I do not want to loose the program, yet in order to reverse engineer it I must write my own code and see if I can make it work.

Beware, I am a n00b to microcontrolers, and pretty lame to electronics (full of enthusiasm though).


texts: bit_is_clear(ACSR, ACO) Instead of digital_read(1)==LOW

texts:
I am attempting to create a program for the atmega328P which will enable the aux input of a Toyota Corolla stereo. In order to do this, I'm bitbanging AVC LAN. Nearly all of my research comes from this site:
https://github.com/halleysfifthinc/Toyota-AVC-LAN

In this example, Frigon has wired his Atmega8 in a peculiar way. Instead of connecting the + terminal directly to a single pin of his Atmega8, he's connected it to a pulldown resistor, resisted it to the - terminal (presumably for bus termination) and a digital pin as well as an analog pin. The - terminal has been given similar strange treatment.

In his function ReadBits(), he waits for a physical 1, then sets a timer and waits for a physical 0 to measure the length of the pulse. But when he does this, he uses the equivalent of

while ( bit_is_clear( ACSR, ACO ) );

That's completely Greek to me. Does this have something to do with something called in Internal Analog Comparator?

I attempted to create something similar using

while( digitalRead( 2 ) );

but I'm reading static as well as honest-to-goodness pulses. I assume that, anyways, because I'm getting pulses of length 2-7 ticks when many are closer to 20-40 ticks (measured using TCNT0 with no custom prescaler).

So... what exactly is he doing with ACSR and ACO? Why is his + and - terminals connected to more than one pin? Why are his diodes there?

=========================EDIT=======================

Following Edgar's advice, I've reworked my schematic and code to closely match Frigon's work. Below is my code:

#include <avr/wdt.h>

#define fwVer       "v0.1"
#define fwDt        __DATE__
#define DATAPIN     2

//====================================================================================COPYPASTED
#define DATAIN_PIN              ACSR
#define DATAIN                  ACO

#define INPUT_IS_SET            ( bit_is_set( DATAIN_PIN, DATAIN ) )
#define INPUT_IS_CLEAR          ( bit_is_clear( DATAIN_PIN, DATAIN ) )
//===================================================================================WHAT DOES THIS MEAN

byte data[255];

void setup() {
  LedOff();

  Serial.begin(9600);

  pinMode(3,OUTPUT);
  pinMode(2,OUTPUT);
  digitalWrite(3,HIGH); //"leave the pins tri-stated" according to Frigon
  digitalWrite(2,LOW);
  pinMode(LED_BUILTIN,OUTPUT);

  //two second watchdog
  wdt_enable( WDTO_2S );

  Serial.println("Firmware "+String(fwVer)+", compiled on "+fwDt);
  LedOff();
}

void LedOff() {
  digitalWrite(LED_BUILTIN, LOW);
}
void LedOn() {
  digitalWrite(LED_BUILTIN, HIGH);
}

void loop() {
  wdt_reset();
  if (INPUT_IS_CLEAR) LedOff();
  else LedOn();
}

Schematic: https://imgur.com/a/PIkad
(mistake on the schematic - I connected 5v to vcc and ground to ground)
If it matters, I'm powering the head unit and the arduino from the 12v and 5v rails of an ATX power supply. They both take the same ground.

My code should theoretically only turn on my led whenever the head unit broadcasts bits, but it's just sort of erratically blipping on and off or fading gently at random. I've triple checked my wiring (breadboard if that matters). Why is this happening? Is there something about bit_is_clear(ACSR,ACO) that I don't understand?


texts: Can we control other servos with common servo code Arduino

texts:
I am trying to control MG996R using code for a typical servo (SG90)
I used an external power supply, 5V,2A
I connected the servo signal line to Arduino slot 7,
servo positive to external power supply positive,
servo ground to external power supply ground,
while leaving the Arduino power supply and ground unconnected.
I tried the below code.
it works for SG90, while MG996R is not moving at all.

#include <Servo.h>
Servo myservo;

void setup()
{
  myservo.attach(7);  //pin 7 is the one control servo

}

void loop()
{

  for (int pos=0; pos<=60; pos++)
  {
    myservo.write(pos);
    delay(15);
  }

}

Is it because the different servos need different code?


texts: Can't create a RTC_DATA_ATTR var inside a class

texts:
I'm trying to create a deepSleep class for my ESP32 project, but I get this error : section attribute not allowed for 'clock_beforeSleep' The only place it compiles, is outside the class.

How should I declare it ?

EDIT1: Add Code

#include "EEPROM.h"
#include "time.h"
#include "WiFi.h"

RTC_DATA_ATTR long clock_expectedWake = 0;
RTC_DATA_ATTR int bootCounter = 0;
RTC_DATA_ATTR int driftRTC = 0;
RTC_DATA_ATTR long clock_beforeSleep = 0;

class esp32Sleep
{
#define EEPROM_SIZE 16
#define DEV_NAME "ESP32lite"
#define uS_TO_S_FACTOR 1000000ULL /* Conversion micro seconds to seconds */

private:
  char sleepstr[250];
  // RTC_DATA_ATTR long clock_expectedWake = 0;
.
.
.


texts: Bluesmirf Mate Silver (RN-42) enter command mode when in HID mode

texts:
I am having problems getting the Bluesmirf Mate Silver (RN-42) into command mode once I have switched to HID mode. I have bought a second new Bluesmirf Mate Silver to confirm my issue.

I soldered the Bluesmirf and connecting to Arduino Uno. I used the ‘Example code: Using Command Mode’ from https://learn.sparkfun.com/tutorials/using-the-bluesmirf to successfully enter command mode.

I then entered the following commands in command mode (leaving out the comments):

SM,5   // Mode = 5, (any) Auto reconnect
SA,2   // Authentication Mode 2 (SSP, "just works" mode)
S-,myName  // // Set BT Name, This short name with no spaces is Picked up ok on windows
S~,6   // Enable HID on reboot
R,1    // Reboot to lock in perameters

Next I use a PC and pair with the bluetooth ‘keyboard’ I have created above. I am able to use the Bluetooth and Arduino sketches to write into notepad on the bluetooth connected PC.

However now I cannot get back into command mode to make changes to the Bluesmirf config. Trying to use the example code above I can see ‘$$$U,9600,N’ typed into notepad on the connected PC each time I load the sketch, rather than being used to enter command mode.

How do I get back into command mode after HID mode has been triggered.


texts: How do I solve error 516 : Broken Pipe with HC-05 and arduino?

texts:
I am doing an LED project from howtomechatronics.com . It is to control and LED by pressing the on and off buttons on an Arduino Bluetooth terminal app. I am using the app made by the howtomechatronics writer. When I press either on, or off, it shows

error 516:broken pipe


texts: Does the Node MCU v3 (LoLin) not have a builtin led?

texts:
Trying a simple led blinking program I could not get the builtin led on a LoLin Node MCU v3 working. The LED_BUILTIN constant is set to pin 16 / GPIO16 / D0.

Reading several articles and QA I think that the Node MCU boards are supposed to have a the on-board led on pin 16. However, if I address this port nothing happens.

With the same code I can blink the data led which is on a RX pin, pin 2.

Is the builtin led missing on the LoLin Node MCU v3, or could it be that the led on my board is broken?


texts: What is the difference between a motor driver and a motor shield?

texts:
what is the difference between a motor driver(like L293D) and a motor shield?

what are the advantage?disadvantages of both?

And which one do you suggest ?


texts:
While this board (listed on ebay as D1 Mini NodeMcu Lua WIFI ESP-12F ESP8266 WeMos 4M Bytes Development Board Kit) was powered by usb, I accidentially shorted between the gnd (G) and 5v pins on the left, and some magical smoke escaped.

I can no longer power the device from usb, but it works nicely if I supply it with the right voltage on either the 5V on the left or the 3V3 on the right.

So something has burned between the 5V on the usb and the 5V on the regulator.
I have tried measuring the components with an ohmmeter, and compared it to a working board, but I can measure no difference.

Is one of these tiny components a fuse, or a diode to prevent backwards voltage from board to pc, if the board is powered on the pins?

Or could the short between 5V and GND have caused a track to burn?


texts: How to calculate illuminance from the output of a TCS34725 color sensor?

texts:
I am using Arduino UNO with the sensor with the following programm.

#include <Wire.h>

// TCS34725 I2C address is 0x29(41)
#define Addr 0x29

void setup()
{
  // Initialise I2C communication as MASTER
  Wire.begin();
  // Initialise Serial Communication, set baud rate = 9600
  Serial.begin(9600);

  // Start I2C Transmission
  Wire.beginTransmission(Addr);
  // Select Wait Time register
  Wire.write(0x83);
  // Set wait time = 2.4 ms
  Wire.write(0xFF);
  // Stop I2C Transmission
  Wire.endTransmission();

  // Start I2C Transmission
  Wire.beginTransmission(Addr);
  // Select Atime register
  Wire.write(0x81);
  // Atime = 700 ms, max count = 65536
  Wire.write(0x00);
  // Stop I2C Transmission on the device
  Wire.endTransmission();

  // Start I2C Transmission
  Wire.beginTransmission(Addr);
  // Select control register
  Wire.write(0x8F);
  // AGAIN = 1x
  Wire.write(0x00);
  // Stop I2C Transmission
  Wire.endTransmission();

  // Start I2C Transmission
  Wire.beginTransmission(Addr);
  // Select enable register
  Wire.write(0x80);
  // Power ON, RGBC enable, wait time disable
  Wire.write(0x03);
  // Stop I2C Transmission
  Wire.endTransmission();
  delay(800);
}

void loop()
{
  unsigned int data[8];

  // Start I2C Transmission on the device
  Wire.beginTransmission(Addr);
  // Select data register
  Wire.write(0x94);
  // Stop I2C Transmission on the device
  Wire.endTransmission();

  // Request 8 byte of data from the device
  Wire.requestFrom(Addr, 8);

  // Read 8 bytes of data
  // cData lsb, cData msb, red lsb, red msb, green lsb, green msb, blue lsb, blue msb
  if (Wire.available() == 8)
  {
    data[0] = Wire.read();
    data[1] = Wire.read();
    data[2] = Wire.read();
    data[3] = Wire.read();
    data[4] = Wire.read();
    data[5] = Wire.read();
    data[6] = Wire.read();
    data[7] = Wire.read();
  }

  // Convert the data
  float cData = (data[1] * 256.0) + data[0];
  float red = (data[3] * 256.0) + data[2];
  float green = (data[5] * 256.0) + data[4];
  float blue = (data[7] * 256.0) + data[6];

  // Calculate the final lux
  float luminance = (-0.32466 * red) + (1.57837 * green) + (-0.73191 * blue);

  // Output data to serial monitor
  Serial.print("Red color Luminance   : ");
  Serial.print(red);
  Serial.println(" lux");
  Serial.print("Green color Luminance : ");
  Serial.print(green);
  Serial.println(" lux");
  Serial.print("Blue color Luminance  : ");
  Serial.print(blue);
  Serial.println(" lux");
  Serial.print("IR Luminance          : ");
  Serial.print(cData);
  Serial.println(" lux");
  Serial.print("Ambient Light Luminance : ");
  Serial.print(luminance);
  Serial.println(" lux");
  delay(500);
}

Is the output really in lux or is it counts? If it's counts, how can I calculate the illuminance in lux?


texts: I have trouble with my laser sensor it doesn't work properly. When I connect all pins its doesn't work, when I remove GND and connect just the signal pin and VCC it works but the laser light is dim(I saw the light when I look at the sensor carefully ). Can someone help me?


texts: Can the "Arduino Create" chrome extension be used to program an arduino nano clone?

texts: I was wondering if the Arduino Create app for the chrome browser can be used to program an atmega328 based arduino nano clone.(I need that app so that the arduino can be programmed using a chromebook). When I researched the compatible boards, I found that the official arduino nano(atmega328 based)is supported, but I was wondering if the software(see first link) can also work with the nano clone(see second link). A thing that caught my eye was that in the second link, it says that the clone uses a different driver because it doesn't have an FT232R chip, so would this cause a problem with the Arduino Create software?


texts: ESP8266MOD programing using Arduino uno?

texts:
I want to make a very simple webserver who sends welcome message to anyone who joins it using WiFi.

I have a ESP8266MOD module, I want to program it using arduino ide and arduino uno board.
How I can use arduino uno to program this WiFi module without using urat USB serial board?

SoftwareSerial.h is not working with esp.write() command, I believe it is because of low power, can anyone suggest me on power supply too?

Thanks in advance,

Mohan


texts:
Using the delay function inside of an ISR is frowned upon when programming in an Arduino. The general response to solve this desire is to design the program to delay in a more cleanly way outside of the interrupt.

My question is simply why. Why does putting a delay() inside of an ISR cause wonky behavior with the Arduino. Whats going on under the hood?


texts: attachInterrupt for mega 2560 not triggering

texts:
I recently bought a mega 2560 to toy around with as a hobby. It's pretty fun so far, but I've recently gotten stuck while trying to use attachInterrupt with a button. I'm using the CHANGE mode, and have read the documentation pretty thoroughly ( I think ).

I've looked up multiple questions and tried to fix my setup and I still can't seem to make it work.

Here's my code:

int buttonPin = 18;
int ledPin1 = 11;
int ledPin2 = 9;
int ledPin3 = 5;

int value = 0;

void setup() {
  //declare inputs and outputs
  pinMode(buttonPin,INPUT_PULLUP);
  pinMode(ledPin1,OUTPUT);
  pinMode(ledPin2,OUTPUT);
  pinMode(ledPin3,OUTPUT);

  //create interrupt for button
  attachInterrupt(digitalPinToInterrupt(5),count,CHANGE);

  Serial.begin(9600);
}

void loop(){
  if(value == 0){ digitalWrite(ledPin1,HIGH);}
  else{ digitalWrite(ledPin1,LOW); }

  if(value == 1){ digitalWrite(ledPin2,HIGH);}
  else{ digitalWrite(ledPin2,LOW); }

  if(value == 2){ digitalWrite(ledPin3,HIGH);}
  else{ digitalWrite(ledPin3,LOW); }

  delay(500);
  Serial.print(digitalRead(buttonPin));

}

//count occurs when button is pressed
void count(){
  //incremement a counter
  value++;
  //reset counter from 3 to 0
  if(value >= 2){ value = 0; }
}

It's a pretty simple sketch. I'd attach a picture of my current setup but I don't really think It's needed. The button is indeed working as I'm debugging using serial.print().

If not clear, the objective of the sketch is to change the LED lit when the button is pressed. Currently, the variable value is stuck at 0.


texts: How can I connect an ultrasonic sensor to my Arduino motor driver shield l239D when I don't have any space left?

texts: Can you tell me how many sensors I can connect to the l239D motor driver shield? I want to put an ultrasonic sensor and two infrared sensors. Is it possible?


texts: ATtiny85 (Sparfun Clone/Trinket), detect/read operation voltage

texts:
I just started with Arduino programming and currently I'm using this Sparkfun clone board:

o http://nl.aliexpress.com/item/Digispark-kickstarter-Micro-development-board-ATTINY85-module-for-Arduino-usb/32584975067.html

It's really nice and like the way to program it and 'burn' it, it's easy to do. For the first project, I came along this instructable, an USB volume knob:

o http://www.instructables.com/id/Digispark-Volume-Control/

I'm using the Sparkfun Arduino programming IDE with added AdaFruit Trinket USB library (Trinket is also ATtiny85), download source, tweak it a bit to my needs and it's working perfectly. Had some programming question though, see also:

o https://stackoverflow.com/questions/37740026/change-override-trinket-attiny85-usb-identification-name-device-name/37743886#37743886

o  https://stackoverflow.com/questions/37769451/arduino-make-a-library-more-optional-by-project?lq=1

o https://stackoverflow.com/questions/37824336/arduino-trinket-attiny85-usb-possible-to-read-the-state-of-all-keys

Anyway, optimized the source code (original not really a beauty), play with it and added also a fade-In/fade-out idle feature to the LED on PIN 1 and it blinks when turning the dial encoder.

I want to add add some more features to this knob, such as pushbuttons to change some internal modes. For example:

Toggle button for knob sensitivity (3-modes: slow (default), normal, fast)
A mute button

I want to that device 'remember' the state of the toggle button but there is no option (flash memory) to save the state. So I came with the idea to use a backup button cell to keep the device 'alive' when disconnected from USB (or computer turned off). A Button cell is 3V and USB is 5V so maybe is possible to 'test' the input voltage. If this is possible you can put the device in sleep mode (low power mode) directly after detecting USB connection lost and this voltage drop.

I have read already an article how to put the device into sleep mode (and awake from it):

o https://bigdanzblog.wordpress.com/2014/08/10/attiny85-wake-from-sleep-on-pin-state-change-code-example/

Question is:

Can I measure somehow the voltage is used to power the device? Any ideas (code example please if it is possible)?


texts: Is it possible to specify a pin upon which the data sent over i2c can act?

texts: A master will send fan speed values to the slave. The slave will then read the fan speed values and change the speed value for the relevant pwm pin. However I am not sure how I can tell the slave which pin the data is for.  Should I send two packets of data in quick sucsession and then have a loop system wherby the first peice of data out of two is always for specifying the pin? Any help in tackling this would be greatly appreciated.


texts: Pre-heat time required for MQ-5 gas sensor

texts: The datasheet of MQ5 sensor says, it requires a pre-heat of 24 hours. Does this mean that it needs to be powered on for 24 hours consecutively before usage? Some other websites (e.g. http://www.circuitstoday.com/interfacing-mq5-lpg-sensor-to-arduino) say that 15 minutes pre-heat would suffice. Could someone clarify this issue? Thanks.


texts: Baudrate is set to 9600 automatically even if specifying a different value

texts:
You initialize the serial communication via USB with

Serial.begin(baudrate);

where baudrate is a long specifying the number of symbols you want to send over the connection per second. You can put pretty much any number in there, but not every number makes sense.

One thing that I found odd though is that I can't seem to actually use a different baudrate than 9600. The sketch compiles and uploads just fine, but if I check the actual speed of the serial port via

setserial -ag port

where port is the port of my Teensy 4.0 board (that command is something you can use in the terminal of Linux) or with

Serial.baud();

directly in the sketch it always says 9600. I suspect that this is caused by something inside the code behind Serial.begin() since I can manually set the baudrate via the terminal in Linux using

stty speed baudrate < port > port

where (again) baudrate is the speed I want to use and port is the port of my board (checking it with the first terminal command: it works). But when restarting the program on the board the baudrate reverts to 9600.

Does anyone know why this is and how to fix this?


texts: Link to an project for remotely turning off light switch?

texts: I want to build a contraption using an arduino that allows me to turn off my light from across the room. I plan to use a solenoid to move the lights switch up and down. I'm sure I'll have some specific questions later on but to start with, has anybody made or seen a similar project? All I'm really looking for is a link to a project (unless you're willing to give advice/suggestions). Thanks!


texts:
I'm trying to send a POST request to IFTTT from a Node MCU. Instead of writing the code from the scratch, I've tweaked an already existing code (for GET request). It does not seem to work, what am I doing wrong? Needless to say, I replaced the WIFI ssid, the password and the IFTTT token. When testing the POST request with CURL, it works perfectly. Here's how the request should look like:

https://maker.ifttt.com/trigger/{event_name}/with/key/my_super_secret_token

...and the code:

#include <ESP8266WiFi.h>

const char* ssid     = "mywifi";
const char* password = "mywifipassword";

const char* host = "maker.ifttt.com";

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

  // We start by connecting to a WiFi network

  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

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

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

int value = 0;

void loop() {
  delay(5000);
  ++value;

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

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

  // We now create a URI for the request
  String url = "trigger/{trigga}/with/key/IFTTT_token";
  Serial.print("Requesting URL: ");
  Serial.println(url);

  // This will send the request to the server
client.print(String("POST ") + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" +
               "Connection: close\r\n\r\n");

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

  Serial.println();
  Serial.println("closing connection");
}


texts: Can I use ATtiny48 as a board in Arduino?

texts:
I have seen people using ATtiny45 and other boards and there are hardware configurations files for them. Can we use ATtiny48 as a processor for Arduino?

If so where can I get a boards.txt file that supports it? Alternatively how can I write such a file?


texts: Reading from EEPROM and writing to addressable LED with limited connections

texts:
UPDATE
Clock speed code has been tweaked as per the suggestion from @timemage due to inability for Wire library to reduce to below 30304Hz. Unfortunately problems still persist:
Nothing printed out to serial and LED working only after disconnecting and reconnecting the circuit(stops updating after reseting arduino)..
UPDATE
Thanks for all replys. I have left the circuit the same and have used the following code where i have tried to reduce the i2c clock speed to 1khz but unfortunately having no luck.The EEPROM returns nothing and the pixel fails to work initially, only when i disconnect the circuit(this is simple because i am using a magnetic USB connector) it seems to work fine(until i restart the arduino).
If the consensus is that i may have more luck if I alter the library then i may look into it although it sounds a bit out of my depth...
#include <Wire.h>

#define disk1 0x50    //Address of eeprom chip
unsigned int address0 = 0; //address to store the data

#include <Adafruit_NeoPixel.h>

//pixels pin
#define sda_pin A4
#define scl_pin A5

Adafruit_NeoPixel strip(1, sda_pin, NEO_GRB + NEO_KHZ800);

void setup() {

  Serial.begin(9600);

  Wire.begin();

  ////UPDATED CODE TO REDUCE I2C CLOCK SPEED TO 1KHZ////
  TWSR |= 0x03; // chose divide-by-64 prescaler
  TWBR  = 0x80; // closest to 1 kHz from below at 16 MHz with /64 prescaler.

  Serial.println(readEEPROM(disk1, address0), DEC);
  Wire.end();
  pinMode(scl_pin, INPUT);

  strip.begin();           // INITIALIZE NeoPixel strip object (REQUIRED)
  strip.show();            // Turn OFF all pixels ASAP
  strip.setBrightness(100); // Set BRIGHTNESS to about 1/5 (max = 255)

}

void loop() {
  rainbow(10);
}

void rainbow(int wait) {

  static unsigned long timer = 0;
  static long firstPixelHue = 0;

  if (millis() - timer > wait) {
    timer = millis();

    for (int i = 0; i < strip.numPixels(); i++) { // For each pixel in strip...

      int pixelHue = firstPixelHue + (i * 65536L / strip.numPixels());

      strip.setPixelColor(i, strip.gamma32(strip.ColorHSV(pixelHue)));
    }
    strip.show(); // Update strip with new contents

    if (firstPixelHue < 5 * 65536) { //incrememnt
      firstPixelHue += 256;
    } else firstPixelHue = 0; //reset

  }
}

byte readEEPROM(int deviceaddress, unsigned int eeaddress )
{
  byte rdata = 0xFF;

  const uint8_t i2c_base_address = 0x50;
  const uint8_t upper_three_eeprom_adress_bits = (eeaddress >> 8) & 0x7;
  const uint8_t i2c_address = i2c_base_address | upper_three_eeprom_adress_bits;
  Wire.beginTransmission(i2c_address);
  Wire.write(eeaddress & 0xFF); // address LSB

  Wire.endTransmission();

  Wire.requestFrom(deviceaddress, 1);

  if (Wire.available()) rdata = Wire.read();

  return rdata;
}

ORIGINAL POST:
I have created a circuit which includes an AT24C16 EEPROM which I only need to read from and an addressable LED (WS2812 IC), which I will be talking to (Using an Arduino Nano).
My original intention was to attach the LED's DIN pin to either SCL or SDA. I thought that since I only needed to read the EEPROM once (and then control the LED), I would be able to share the connection. After creating the circuit, it proved an incorrect assumption.
I am limited to 4 (nets?) total due to the adapter I am using between the Arduino Nano and the rest of the circuit (repurposed magnetic 4 wire USB cable). Could anyone propose a setup which would allow me with only these 4 connections, to read from the EEPROM and write to the LED? As I mentioned, I only need a single read from the EEPROM to identify it and then I will only be writing to the pixel. Many thanks!
Attached is the schematic.


texts: RPM_COUNTER.h:11:33: error: invalid use of non-static member function attachInterrupt(0,count,RISING);

texts:
class RPM_COUNTER {

  private:

volatile int counter = 0;

  public:

      void RPMSetup() {
        lcd.begin(16,2);
  attachInterrupt(0,count,RISING);
      }
void RPMLoop() {
  delay(999); // Delay almost 1 second.
lcd.setCursor(8, 1);
  lcd.print(counter*60); // Counter/2 * 60 seconds.
  lcd.println("rpm.");
  counter = 0;
}

void count()
{
 counter++;
}
};
RPM_COUNTER RPM;


texts: Why AnalogRead shows value (395) when its on HIGH State ? why not shows 1023 when its high State

texts:
I Took a output from ESP8266 and Connected it with Arduino Nano Analog input A0
i use BLYNK app to on/off D0 pin in ESP8266 , and i connected ESP8266 D0 pin with Arduino Nano A0 analogPin.
when esp8266 D0 in high state , the analogRead value in arduino nano serial monitor it show the value 395.
why not 1023 on high state .


texts:
I'm trying to get my Arduino GSM shield working with the example "Send SMS" code provided. However, when I upload and compile the program, the serial monitor displays "SMS Messages Sender" and nothing else occurs.

Would greatly appreciate it if someone can tell me where I could have gone wrong.

EDIT : I'm currently using the Arduino Mega. The shield I'm using is the Arduino GSM Shield. I'm following the guide provided by the Arduino's website with the code part of the example that comes with the Arduino program, see Sending a SMS message. Attached is what is shown on the monitor.

I am using both a USB cable and an external power supply. I have performed the jumper wire modification required for the Mega to work with the shield as well.


texts: avr-g++ (or avr-gcc) and LiquidCrystal library

texts:
I'm trying to run a simple Hello World program from Arduino 1.6.5 from terminal. When I run it in Arduino IDE, it works good. When I'm trying to get it by avr-g++ I have hard way to figure out how to include all libraries - so far I got this script:

avr-g++ -Os -DF_CPU=16000000UL -mmcu=atmega328p -c -o main.o main.cpp
-I"../arduino-1.6.5-r5/libraries/LiquidCrystal/src/"
-I"../arduino-1.6.5-r5/hardware/arduino/avr/cores/arduino/"
avr-g++ -mmcu=atmega328p main.o -o main
avr-objcopy -O ihex -R .eeprom main main.hex
sudo avrdude -F -V -c arduino -p ATMEGA328P -P /dev/ttyACM1 -b 115200 -U flash:w:main.hex

First line (with both -I flags) compiles, but after running second line, I get:

main.o: In function `main':
main.cpp:(.text.startup+0xa): undefined reference to `LiquidCrystal::begin(unsigned char, unsigned char, unsigned char)'
main.cpp:(.text.startup+0x16): undefined reference to `Print::print(char const*)'
main.o: In function `_GLOBAL__sub_I_lcd':
main.cpp:(.text.startup+0x3a): undefined reference to `LiquidCrystal::LiquidCrystal(unsigned char, unsigned char, unsigned char, unsigned char, unsigned char, unsigned char)'
collect2: error: ld returned 1 exit status

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