texts: Ultrasonic sensors with 12v motors will not work! (ADRUINO)

texts:
ok... so I am using four 12V motors and one ultrasonic sensor with a motor shield... and I am getting some odd results...
in my code I have it so when the distance to a object is less than 4 cm it will go backwards and when something is not 4 cm in front of the robot it will go forwards... simple!
but the wheels on the left side of my robot will stop! and just do nothing!

The weirdest part about it is when I make some code JUST moving the wheels back and forth the wheels will work PERFECTLY fine. and when I use some code JUST for the sensors... it works fine! but together... it does all that weird stuff.

this is the shield I am using: https://www.pololu.com/product/2507

if there is any information I missed that you need let me know and I will get back with you. I am new to Arduino so I am extremely confused...

the code.

#include "DualVNH5019MotorShield.h"
DualVNH5019MotorShield md;

#define trigPin 7
#define echoPin 8

void setup() {
    md.init();  //setting up wheel code
    Serial.begin (9600);
    pinMode(trigPin, OUTPUT);
    pinMode(echoPin, INPUT);
}

void loop() {
    long duration, distance;
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);
    distance = (duration/2) / 29.1;

//This is the sensor testing if somthing is in range!
if (distance < 4){
        Serial.println("in range");
        md.setM1Speed(100);
        md.setM2Speed(-100);
}
else {
        Serial.println("not in range");
        md.setM1Speed(-100);
        md.setM2Speed(100);
}

if (distance >= 200){
        Serial.println("!");
}
else {
        Serial.print(distance);
        Serial.println(" cm");
}
    Serial.println(distance);
    delay(500);
}


texts: How to decrease delay for String concatenation + Arduino Due

texts:
In my project I need to add a delimiter between integer numbers. In the following code. I add a "," between integer numbers obtained from inputsig matrix. The problem is that concatenation of these numbers with concat() command for a Matrix with 100 rows and 9 columns takes 10 ms.  Is there any efficient way to decrease this delay?

#include <CStringBuilder.h>

int Max_pack_size = 100;

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

  while (!SerialUSB) ;

}

void loop() {

  String  datas1;
  String  inputsig[Max_pack_size][9];
  char buff[((8+1)*Max_pack_size+1)*9];
  CStringBuilder sb(buff, ((8+1)*Max_pack_size+1)*9);

  for (int i = 0; i < Max_pack_size; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      inputsig[i][j] = 16777215;

    }
  }

  int t0 = micros();

  for (int i = 0; i < Max_pack_size; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      //datas1.concat(inputsig[i][j]);
      //datas1.concat(",");
  sb.print(inputsig[i][j]);
  sb.print(F(","));
    }
  }

 SerialUSB.println(float(micros() - t0));
 delay(1000);

 SerialUSB.println(buff);

}


texts:
I am using Dust Sensor GP2Y1010AU0F

I downloaded the code from the manufacturer here:
http://www.waveshare.com/wiki/Dust_Sensor

/*********************************************************************************************************
*
* File                : DustSensor
* Hardware Environment:
* Build Environment   : Arduino
* Version             : V1.0.5-r2
* By                  : WaveShare
*
*                                  (c) Copyright 2005-2011, WaveShare
*                                       http://www.waveshare.net
*                                       http://www.waveshare.com
*                                          All Rights Reserved
*
*********************************************************************************************************/
#define        COV_RATIO                       0.2            //ug/mmm / mv
#define        NO_DUST_VOLTAGE                 400            //mv
#define        SYS_VOLTAGE                     5000

/*
I/O define
*/
const int iled = 7;                                            //drive the led of sensor
const int vout = 0;                                            //analog input

/*
variable
*/
float density, voltage;
int   adcvalue;

/*
private function
*/
int Filter(int m)
{
  static int flag_first = 0, _buff[10], sum;
  const int _buff_max = 10;
  int i;

  if(flag_first == 0)
  {
    flag_first = 1;

    for(i = 0, sum = 0; i < _buff_max; i++)
    {
      _buff[i] = m;
      sum += _buff[i];
    }
    return m;
  }
  else
  {
    sum -= _buff[0];
    for(i = 0; i < (_buff_max - 1); i++)
    {
      _buff[i] = _buff[i + 1];
    }
    _buff[9] = m;
    sum += _buff[9];

    i = sum / 10.0;
    return i;
  }
}

void setup(void)
{
  pinMode(iled, OUTPUT);
  digitalWrite(iled, LOW);                                     //iled default closed

  Serial.begin(9600);                                         //send and receive at 9600 baud
  Serial.print("*********************************** WaveShare ***********************************\n");
}

void loop(void)
{
  /*
  get adcvalue
  */
  digitalWrite(iled, HIGH);
  delayMicroseconds(280);
  adcvalue = analogRead(vout);
  digitalWrite(iled, LOW);

  adcvalue = Filter(adcvalue);

  /*
  covert voltage (mv)
  */
  voltage = (SYS_VOLTAGE / 1024.0) * adcvalue * 11;

  /*
  voltage to density
  */
  if(voltage >= NO_DUST_VOLTAGE)
  {
    voltage -= NO_DUST_VOLTAGE;

    density = voltage * COV_RATIO;
  }
  else
    density = 0;

  /*
  display the result
  */
  Serial.print("The current dust concentration is: ");
  Serial.print(density);
  Serial.print(" ug/m3\n");

  delay(1000);
}

My results seems rounded or always returning in certain 'steps'.
(below are my results)
Is there a rounded error in the code or something else that could be going on?

The current dust concentration is: 134.84 ug/m3
The current dust concentration is: 134.84 ug/m3
The current dust concentration is: 134.84 ug/m3
The current dust concentration is: 134.84 ug/m3
The current dust concentration is: 134.84 ug/m3
The current dust concentration is: 134.84 ug/m3
The current dust concentration is: 134.84 ug/m3
The current dust concentration is: 124.10 ug/m3
The current dust concentration is: 124.10 ug/m3
The current dust concentration is: 124.10 ug/m3
The current dust concentration is: 113.36 ug/m3
The current dust concentration is: 113.36 ug/m3
The current dust concentration is: 124.10 ug/m3
The current dust concentration is: 124.10 ug/m3
The current dust concentration is: 113.36 ug/m3
The current dust concentration is: 113.36 ug/m3
The current dust concentration is: 113.36 ug/m3
The current dust concentration is: 124.10 ug/m3
The current dust concentration is: 124.10 ug/m3
The current dust concentration is: 124.10 ug/m3
The current dust concentration is: 134.84 ug/m3
The current dust concentration is: 134.84 ug/m3
The current dust concentration is: 124.10 ug/m3


texts: How to reduce noise when using 80Hz mode?

texts:
I have 4 hx711 and each one reads 1 cell, i was using the 10hz mode, however, this was making my application very slow, as I needed to take 5 readings and take the average of these, when I put the 15 RATE in 1, it is having a lot of noise, despite having speeded up the reading of the weights, sometimes the variation is up to 3 digits at the end. See the code for reading the modules where I already show the weights in Kg:

n=6;
for(int x=0;x<n;x++){

v1[x] = CELL1.read();

v2[x] = CELL2.read();

v3[x] = CELL3.read();

v4[x] = CELL4.read();
}
v1m=0;
v2m=0;
v3m=0;
v4m=0;

for(int x=1;x<n;x++){ // sum of array
v1m=v1m+v1[x];
v2m=v2m+v2[x];
v3m=v3m+v3[x];
v4m=v4m+v4[x];
}
//mean array
v1m=v1m/(n-1);
v2m=v2m/(n-1);
v3m=v3m/(n-1);
v4m=v4m/(n-1);

p1=p;
p=((v1m-v10)/(M[1]) +(v2m-v20)/(M[2]) +(v3m-v30)/(M[3]) +(v4m-v40)/(M[4]))/2.5; // show the
weight in Kg
p=p*.7+p1*.3; // convert to kg
// ... i print the p (weight in Kg) now...


texts:
Executing the following code always gives -511 as a result, I performed many tests, and it seems that results are correct from 0 * 0 to 181 * 181, beyond that, results are abnormal, I tried many types for the z variable (int, long, float) without success, any idea? I'm using the Arduino Uno.

long z = 0;

void setup() {

Serial.begin(9600);

}

void loop() {

  z = 255 * 255;
  Serial.println(z);
  delay(200);

}


texts: How shiftOut function works internally? (explanation on source code)

texts:
I were examining shiftOut() function code in wiring_shift.c and I didn't quite understand what is going in digitalWrite function. I see !!(val & (1 << i)) is taking the bit value from val but how exactly it works?

The whole function is below.

void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val)
{
    uint8_t i;

    for (i = 0; i < 8; i++)  {
        if (bitOrder == LSBFIRST)
            digitalWrite(dataPin, !!(val & (1 << i)));
        else
            digitalWrite(dataPin, !!(val & (1 << (7 - i))));

        digitalWrite(clockPin, HIGH);
        digitalWrite(clockPin, LOW);
    }
}


texts: How to access the member of union in loop?

texts:
Trying to get the address of receiving XBee's data in the loop in API mode with escape.
Sent data can be received properly. However, in order to identify XBee, I need the address in the loop. In other words I need those address1 to 7 which is in union XbEE_FRAME. How to get the address in main loop. Following is the code. Appreciate your help.

#include <SoftwareSerial.h>

struct SENSOR_DATA{
   char rpm;   // worked
  //float rpm;
  //float strain;
  //unsigned long sampling_interval;
};

boolean xbee_rx(struct SENSOR_DATA *ret) {
  union LEN_FRAME{
    byte len_array[2];
    word len;
  }lenlen;
  static int len_i = -1;

  union XbEE_FRAME{
    byte buf[25]; // 30
    struct {
      byte frame_type;
      byte frame_id;
      byte address1;
      byte address2;
      byte address3;
      byte address4;
      byte address5;
      byte address6;
      byte address7;
      byte reserved1;
      byte reserved2;
      byte recieve_options;
      struct SENSOR_DATA sensor_data;
      byte checksum;
    } frame;
  } xbee;
  static int buf_i = -1;
  static bool escape = false;
  static byte sum;

  while (Serial.available() > 0) {
    byte b = Serial.read();

    //Serial.print(b, HEX);

     //b = Serial.read();
    if (
      b != 0x7e &&
      buf_i == -1 &&
      len_i == -1
      ) {
      continue;
    } else if (b == 0x7e){
      buf_i = 0;
      lenlen.len = 0;
      len_i = 0;
      sum = 0;
      escape = false;
      continue;
    } else if (b == 0x7d){
      //Serial.print("es: ");
      //Serial.println(b,HEX);
      escape = true;
      continue;
    }

    if (escape){
      b = b ^ 0x20;
      escape = false;
    }

    if (len_i < 2){
      lenlen.len_array[1 - len_i] = b;
      len_i++;
    } else {
      xbee.buf[buf_i++] = b;
      sum += b;
    }
    if (
      len_i == 2 &&
      buf_i >= sizeof(xbee.buf)
      ){
      len_i = -1;
      buf_i = -1;
      // frame recieved !!
      if (sum == 0xff){ // check sum!
        *ret = xbee.frame.sensor_data;
        return true;
      }
    }
  }
  return false;
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);   // 38400
  Serial.println("overover");
}

void loop() {
  //mySerial.println("work");
  // put your main code here, to run repeatedly:
 struct SENSOR_DATA data;
  if (xbee_rx(&data)){
    //Serial.print(data.rpm);

     // if(b == 0x40 )  //&& b == 0xd5 && b == 0xaa && b == 0xac
  }
}


texts: Cannot ping ESP8266's IP address from a computer on the same network

texts:
I have an ESP8266 module connected to my Arduino Mega 2560. I sketched a simple code to pass whatever command I typed from the Serial Monitor to ESP8266 and vice versa:

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

void loop() {
  if (Serial.available())
  {
    Serial2.write(Serial.read());
  }

  if (Serial2.available())
  {
    Serial.write(Serial2.read());
  }
}

So from here on I just type my AT commands inside Serial Monitor and receive the output also inside Serial Monitor. Managed to connect into a wifi network using the command:

AT+CWJAP="SSID","password"

And obtain my ESP8266 module's IP address using the command:

AT+CIFSR

+CIFSR:APIP,"192.168.4.1"
+CIFSR:APMAC,"5e:cf:7f:c2:ce:30"
+CIFSR:STAIP,"192.168.1.103"
+CIFSR:STAMAC,"5c:cf:7f:c2:ce:30"

OK

Problem is, whenever I run CMD and "ping 192.168.4.1" or "ping 192.168.1.103" from my PC which is connected to the same network, I will get "request timed out". Pinging my own PC's IP gets me a reply. What is wrong here? Totally clueless... :-/

EDIT My PC's IP address is 192.168.56.1


texts: Problem: char string not working with SoftwareSerial.h

texts:
I am creating a program to display text on an OLED display and then have it sent to a thermal printer.

The issue is my second char string: word_buffer

When I try to use word_buffer for any reason it crashes the program and nothing will work (the OLED display will not refresh upon uploading the sketch and typing on the keyboard will not update the display).

The program works fine when you omit the code needed for the thermal printer (Adafruit_Thermal.h, SoftwareSerial.h, and other setup).

The sample code is below, I've commented out the section where I try and utilize word_buffer.
If I remove the thermal printer setup code and uncomment that section, the program will run just fine.

Let me know what you think, I've been stuck on this for a while now :/

#include <Adafruit_SSD1306.h>
#include <Adafruit_GFX.h>
#include <Adafruit_Thermal.h>
#include <PS2Keyboard.h>
#include <MemoryFree.h>

#include <SPI.h>
#include <Wire.h>

#define LED_PIN 13

// OLED display
#define OLED_MOSI  A4
#define OLED_CLK   A3
#define OLED_DC    A2
#define OLED_CS    A0
#define OLED_RESET A1
Adafruit_SSD1306 display(OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);

// printer
#include "SoftwareSerial.h"
#define GND_PIN 7
Adafruit_Thermal printer(&Serial, 4);

// keyboard
const int DataPin = 8;
const int IRQpin =  3;
PS2Keyboard keyboard;

#define HIDDEN_BUF 21
#define VIS_BUF 168
#define WRD_BUF 32

char line_buffer[HIDDEN_BUF + VIS_BUF + 1];
int line_start = HIDDEN_BUF;
int line_len = 0;
int word_len = 0;
char word_buffer[WRD_BUF + 1];

void setup() {
  keyboard.begin(DataPin, IRQpin);

  pinMode(GND_PIN, OUTPUT);
  digitalWrite(GND_PIN, LOW);

  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, HIGH);

  for (int i = 0; i < HIDDEN_BUF + VIS_BUF; i++)
    line_buffer[i] = ' ';

  line_buffer[HIDDEN_BUF + VIS_BUF] = 0;

  for (int i = 0; i < WRD_BUF; i++)
    word_buffer[i] = ' ';

  word_buffer[WRD_BUF] = 0;

  display.begin(SSD1306_SWITCHCAPVCC);
  display.clearDisplay();
  display.setTextSize(1);
  display.setTextColor(WHITE);
  display.setCursor(0, 0);
  display.println(line_buffer + HIDDEN_BUF);
  display.display();

  Serial.begin(9600);
  printer.begin();
}

void loop() {

  if (!keyboard.available()) return;

  char c = keyboard.read();

  boolean newline = false;

 if (c == PS2_DELETE) {
    if (line_len > 0) {
      line_len--;
      line_buffer[line_start + line_len] = ' ';
      if (word_len > 0)
      word_len--;
    }
  }

//  if (word_len > 0)
//  line_buffer[188] = word_buffer[1];

  if (c >= 33 && c <= 126) {
    word_len++;
    line_buffer[line_start + line_len] = c;
    word_buffer[word_len] = c;
    line_len++;
     }

  if (c == 32) {
    line_buffer[line_start + line_len] = c;
    line_len++;
    for (int i = 0; i <= 32; i++)
      word_buffer[i] = ' ';
    word_len = 0;
  }

  display.clearDisplay();
  display.setCursor(0, 0);
  display.println(line_buffer + HIDDEN_BUF);
  display.display();
}


texts:
I'm trying to send SMS using Arduino Uno v3 and Sony Ericsson K700i. I have a function that converts a text and a number to pdu format but I'm unable to deliver the message. I don't get any error after posting the serial data to phone. Could someone please quide me?
Here is the function that I use

void send_sms(String message, String phone_nr )
{
 byte original_byte;
byte newbyte;
int pdu_length;
int counter;
String newphone_nr;
int numlength;

 delay(1000);
  Serial.begin(9600);
  delay(1000);
  numlength=phone_nr.length()-1;
  if (numlength% 2 != 0 ) {
    phone_nr += "F";
  }
  for(int x = 0; x < numlength; x = x+2){
    newphone_nr.concat(phone_nr.charAt(x+2));
    newphone_nr.concat(phone_nr.charAt(x+1));
  }

  //start sending SMS
  Serial.println("AT");  //optional: say hello to the modem
  delay(3000);
  Serial.println("AT+CMGF=0"); //set pdu mode
  delay(3000);
  int textlength= message.length()*7/8;   // text message length: number of characters*7/8
  if (message.length()*7%8 != 0) {
    textlength++;
  }
  if (numlength%2 != 0) {   //if the length of phone number was uneven, it now increases by 1 because of the added "F"
    pdu_length = (8 + (numlength+1)/2 + textlength);
  }
  else { //8 bytes of parameters + (length of phonenumber)/2 + number of bytes in the text
    pdu_length = (8 + numlength/2 + textlength);
  }

  Serial.print("AT+CMGW="); //message will be stored in the mobile phone - AT+CMGS will send it off.
  //delay(3000);
  Serial.println(pdu_length);
  //delay(100);
  Serial.print("001100");  //these are some parameters which we don't need to bother about
  //delay(100);
  if (numlength<16){       //now we have to send the byte containing the length of the phone number in HEX format
    Serial.print(0);
  //delay(100);
  }        //the byte in HEX format needs to be 2 characters long; if needed we add a 0 in front, e.g. "C" will become "0C"
  Serial.print(numlength,HEX); //length telnr - this time any additional F is not to be considered
 // delay(100);
  Serial.print("91");     //international format of phone number //81 for national format
  //delay(100);
  Serial.print(newphone_nr); //now we send the rearranged phone number
  //delay(100);
  Serial.print("0000AA"); //some more parameters
  //delay(100);
  if (message.length()<16){
    Serial.print(0);
    //delay(100);
  }       //a byte in HEX format indicating the length of the text. Again the byte needs to be made of 2 characters
  Serial.print(message.length(),HEX);
  //delay(100);

  counter=0;
  newbyte=0;
  for (int j=0; j<message.length(); j++) {
    original_byte = message.charAt(j); //one by one we take each byte out of the original text

    for (int i=0; i<7; i++) {
      newbyte=newbyte|bitRead(original_byte, i)<<counter;  //take the bits 0 to 6 of the old byte, shift as required for the new byte and add to the new byte
      counter++;
      if (counter==8) {
        counter=0;          //if a new byte is complete, set the counter to 0
        if (newbyte<16){
          Serial.print(0);
         // delay(100);
        } //each byte in HEX format should consist of 2 characters, if necessary add 0 in front
        Serial.print (newbyte, HEX); //when the new byte is finished, send it to the mobile phone
        //delay(100);
        newbyte=0; // the next new byte will start again from 0
      }
    }
  }
  if (message.length()*7%8!=0) {    //if there were remaining bits (not enough to form a new byte), these are sent out as the last byte
    if (newbyte<16){
      Serial.print(0);
      //delay(100);
    } //each byte in HEX format should consist of 2 characters, if necessary add 0 in front
    Serial.println (newbyte, HEX);
    //delay(100);
  }
  delay (3000);
  Serial.write(26); //this is a command telling the mobile phone that the end of the transmission has been reached

}

Q1: Is there any way I can add service message center as a parameter?
Q2: How can I make this functionshow the phone response to the commands I give?

Thanks a lot!


texts: How many 5.5v solar panel should i use to power arduino uno and 9v water pump?

texts:
I want to create a solar powered automatic plant watering system using arduino uno, 9v water pump and soil moisture sensor.
I saw a cheap solar power online and it says  5.5v 50MA. How many of these should I buy to sufficiently supply power to my materials?
Thank you!


texts: arduino flexbot drone connected in a wrong way

texts:
I have an arduino flexbot, I was making some test and accidentally I connected the battery in the opposite way. The drone turned on the six motors when I connected the battery, but any led turned on to see if the processor was working. I disconnected the battery and connected it in the wrong way again same thing happened the six motors turned on again. Then I realize that the battery was connected in a wrong way and connected it in the right way. The LED's turned on as always, and also the blue-tooth module was working I could detect the device using the control-application. I tried to fly the drone but the motors didn't turn on, I could hear little click and I saw a little movement of a motor.

I connected my drone to my PC using the micro USB connection, also I connected the battery. I tried to turn on the drone and in this way it looks to work fine.

But when I disconnect the USB port and I tried to fly it the same thing happens, the click and the little movement. Any idea of what can I do to fix this drone?


texts: Send Arduino data to Database using ESP8266

texts: My project is to receive data from Bluetooth (HC-05) sensor and storing it in the database. I have successfully received data from Bluetooth sensor and stored it in a String variable. Now i have to store this data to the database. I want to use the sensors as standalone (not connecting to the PC - operated on battery). Can I store the data to the database using ESP8266.


texts: The IDE says my (brand new) Arduino UNO is on COM 1

texts:
I recently bought an Arduino Uno and installed everything necessary. I tried it on both USB ports on my computer. However, the Ports menu only shows COM1. There is a line on the bottom of the IDE which says Arduino Uno on COM1.

Any program I try fails to upload to the board. When I tried the Blink example, the following error message appeared:

Arduino: 1.6.3 (Windows 7), 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: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x43

avrdude: stk500_recv(): programmer is not responding

avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x43

and so on. Until,

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

I have a Windows 7 64 bit desktop.

Any help will be appreciated.


texts: Stepper Motor is not working with A4988 board

texts:
So, I have been following this tutorial on how to run a stepper motor with Arduino using an A4988 Stepper Driver. This is the tutorial: How To Control a Stepper Motor with A4988 Driver and Arduino. I have connected the wires according to this schematic:

I have connected the wires exactly like this and triple-checked it! The problem is the stepper motor is not turning. This is the code(it's simple):

// defines pins numbers
const int stepPin = 3;
const int dirPin = 4;

void setup() {
  // Sets the two pins as Outputs
  pinMode(stepPin,OUTPUT);
  pinMode(dirPin,OUTPUT);
}

void loop() {
  digitalWrithe(dirPin,HIGH); // Enables the motor to move in a particular direction
  // Makes 200 pulses for making one full cycle rotation
  for(int x = 0; x < 200; x++) {
    digitalWrite(stepPin,HIGH);
    delayMicroseconds(500);
    digitalWrite(stepPin,LOW);
    delayMicroseconds(500);
  }
  delay(500); // One second delay
}

One weird thing:

  When I connect the sleep and reset pin on the A4988 board the stepper motor starts turning. Like why?

NOTE: I replaced the MEGA with a UNO because at the moment I'm just testing.


texts: I'm writing the code for my Arduino board using Code::Blocks editor. When I create a new project, there is AVR Project and Arduino Project under Projects category. Which one do I select?


texts: Error 1,603,0 when http post request using arduino and sim900a by Json format

texts:
I want to send HTTP post requests to a server in JSON Format using a SIM900 module. But the code is not posting the data and have an error.Can someone help me to solved the error 1,603,0 since I cannot solve , I already try to use http instead of https cause I read from other QnA channel that AT+HTTPPARA="URL can only be read in http .. But nothing happen the error still there. I know the error is about the DNS but I do not know how to solve it.. Sorry it was my first time to use the sim900a
Here is my code:
#include <SoftwareSerial.h>
#include <ArduinoJson.h>

SoftwareSerial SIM900(10, 11);
StaticJsonBuffer<200> jsonBuffer;

char t[32];
char deviceID[12] = "TESTING";
char Name[12] = "Irsyad";
char Place[12] = "JB";

void setup()
{
  SIM900.begin(9600);       // the GPRS baud rate
  Serial.begin(9600);
  Serial.println("Initializing..");

  DynamicJsonBuffer jsonBuffer;

}

void loop()
{
  Serial.println("");
  Serial.println("START");

  Serial.print("Device ID: ");
  Serial.println(deviceID);

  delay(1000);

  if (SIM900.available())
  Serial.write(SIM900.read());

  SIM900.println("AT");
  delay(3000);

  SIM900.println("AT+SAPBR=3,1,\"Contype\",\"GPRS\""); // untuk cek  GPRS
  delay(6000);
  ShowSerialData();

  SIM900.println("AT+SAPBR=3,1,\"APN\",\"\"");//APN mobile phone (cek dekat phone)
  delay(6000);
  ShowSerialData();

  SIM900.println("AT+SAPBR=1,1");
  delay(6000);
  ShowSerialData();

  SIM900.println("AT+SAPBR=2,1");
  delay(6000);
  ShowSerialData();

  SIM900.println("AT+HTTPINIT"); // jika keluar error means gagal
  delay(6000);
  ShowSerialData();

  SIM900.println("AT+HTTPPARA=\"CID\",1"); //parameters untuk HTTP session
  delay(6000);
  ShowSerialData();

  StaticJsonBuffer<200> jsonBuffer;
  JsonObject& object = jsonBuffer.createObject();

  object.set("deviceID",deviceID);
  object.set("Name",Name);
  object.set("Place",Place);

  object.printTo(Serial);
  Serial.println(" ");
  String sendtoserver;
  object.prettyPrintTo(sendtoserver);
  delay(4000);

  SIM900.println("AT+HTTPPARA=\"URL\",\"http://gas-api.smartcp.app/api/ttn/uplink\""); //Server address // tukar pakai lain https://
  delay(4000);
  ShowSerialData();

  SIM900.println("AT+HTTPPARA=\"CONTENT\",\"application/json\""); //json format
  delay(4000);
  ShowSerialData();

  SIM900.println("AT+HTTPDATA=" + String(sendtoserver.length()) + ",100000"); // size bytes untuk hantar data dalam masa 10 seconds
  Serial.println(sendtoserver);
  delay(6000);
  ShowSerialData();

  SIM900.println(sendtoserver);
  delay(6000);
  ShowSerialData;

  SIM900.println("AT+HTTPACTION=1"); // Post the data (1 means post)
  delay(6000);
  ShowSerialData();

  SIM900.println("AT+HTTPREAD");
  delay(6000);
  ShowSerialData();

  SIM900.println("AT+HTTPTERM");
  delay(10000);
  ShowSerialData;
}

void ShowSerialData()
{
  while (SIM900.available() != 0)
    Serial.write(SIM900.read());
  delay(1000);

}


texts: Can't burn Bootloader on Atmega328P Using Arduino Uno

texts:
I'm trying to create an Arduino Uno following the circuit described in the diagram below which I'd based from here.

I'd tried this circuit on an Atmega328 PDIP version (with the correct connections since the PDIP has different pinouts from this TQFP) and I was successful in creating and using my own Arduino.

However, when I've used the TQFP version and had this circuit layout and printed on a pcb, I can't burn the bootloader using an Arduino UNO.

I've double checked the pinouts from the Atmega328P datasheet and they are correct. Using a tester, I've also verified that the connections are there.

By the way, I've used the following connections.

Arduino Digital Pin 13 to SCLK
Arduino Digital Pin 12 to MISO
Arduino Digital Pin 11 to MOSI
Arduino Digital Pin 10 to RESET
Arduino 5V to VCC
Arduino GND to GND

I've also burned the ArduinoISP program on th Arduino UNO, selected Arduino as ISP and chosen Arduino UNO as board.

When I press 'Burn Bootloader', I'm getting this error message.

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

I've looked at different forums and they are only saying to check the connections which I'd already checked that there is.


texts:
I have an Arduino Mega2560 configured to Hiduino, which makes the Arduino a driverless class-compliant MIDI interface.

I am currently converting RS232 serial I/O data to midi data using the 'hairless midi-serial' software running in the background. I am hoping that I can utilize this Hiduino interfacing to send and receive this data in the same fashion, just through the Arduino instead.

I am lead to believe this would require the MIDI library to be used to program the 2560 to understand the serial bytes coming from the controller and converting to the appropriate midi bytes into my program, and vice versa.  I am just getting into programming. Could someone could give an example of how a program could be written to send and receive this data through the Arduino?


texts:
When I try to upload an example code from the Arduino_LSM9DS1 Library it either jumps ports so the upload cannot complete or spits out some red text and never completes the upload, just gets stuck on uploading.
The red text is:
processing.app.debug.RunnerException
    at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:152)
    at cc.arduino.UploaderUtils.upload(UploaderUtils.java:77)
    at processing.app.SketchController.upload(SketchController.java:732)
    at processing.app.SketchController.exportApplet(SketchController.java:703)
    at processing.app.Editor$UploadHandler.run(Editor.java:2047)
    at java.lang.Thread.run(Thread.java:748)
Caused by: processing.app.SerialException: Error touching serial port 'COM5'.
    at processing.app.Serial.touchForCDCReset(Serial.java:107)
    at cc.arduino.packages.uploaders.SerialUploader.uploadUsingPreferences(SerialUploader.java:136)
    ... 5 more
Caused by: jssc.SerialPortException: Port name - COM5; Method name - openPort(); Exception type - Port busy.
    at jssc.SerialPort.openPort(SerialPort.java:164)
    at processing.app.Serial.touchForCDCReset(Serial.java:101)
    ... 6 more

I'm not that new to Arduino but I've never looked into uploading (I guess I should) and am struggling to get it to work.
Any help is appreciated, thanks


texts: Can I use and external power supply and USB at the same time on my Arduino?

texts:
Can I use the Arduino with an External wall-wart and the USB at the same time?  I need to power more LEDs, and the USB on my computer can only supply so much.  But, I didn't want to destroy my computer because I had the USB and the external plugged in.
I saw this,
External power supply?
But I am still unsure.  The reason I want to at all is because when I connected this circuit, the Arduino would cease to be recognized on the USB.  I don't know if it is because there wasn't enough power to the LED, if I short-circuited something, or something else.  I do not wish to break my laptop though.
What happens if I power the Arduino with both the USB and external power voltage simultaneously?
These all seem to indicate you don't just "plug in" with both, and you need some other kind of regulator or something.  But in that same answer, one person says,
https://arduino.stackexchange.com/a/896/69706
And that indicates when the power is plugged in the USB is cut off.  Again, my fear is breaking my laptop, and that is the main question.  Especially in light of this,
Is supplying 5V from both external 5V and USB harmful?
The external power is this,
9 VDC 1000mA regulated switching power adapter


texts: JSON Parser fails because number of bytes is being sent

texts:
Sorry I am new with this.
I am trying to read a JSON response from my website using an ESP8266, but it keeps failing.  I am using the following code:
WiFiClientSecure httpsClient;    //Declare object of class WiFiClient
httpsClient.setInsecure();
httpsClient.setTimeout(15000); // 15 Seconds

if (httpsClient.connect(host, httpsPort)) {

  String Data ="/IOT/Device_Setup.php?MAC="+deviceMAC;

  httpsClient.print(String("POST ") + Data + " HTTP/1.1\r\n" +
   "Host: " + host + "\r\n" +
   "Connection: close\r\n\r\n");

  while (httpsClient.connected()) {
    String line = httpsClient.readStringUntil('\n');
    Serial.println(line);
    if (line == "\r") {
      Serial.println("headers received");
      break;
    }
  }
  String payload = "";
  while (httpsClient.available()) {
    char c = httpsClient.read();
    payload=payload+c;
  }

  Serial.println(payload);

  // Allocate JsonBuffer
  // Use arduinojson.org/assistant to compute the capacity.
  const size_t capacity = JSON_OBJECT_SIZE(3) + JSON_ARRAY_SIZE(2) + 60;
  StaticJsonDocument<200> jsonBuffer;
  // Parse JSON object
  DeserializationError error = deserializeJson(jsonBuffer, payload);
  if (!error) {

    const char* Switch = jsonBuffer["Switch"];
    const char* LED = jsonBuffer["LED"];
    const char* DHT = jsonBuffer["DHT"];

    // Decode JSON/Extract values
    Serial.print("Switch = ");
    Serial.println(Switch);
    Serial.print("LED = ");
    Serial.println(LED);
    Serial.print("DHT = ");
    Serial.println(DHT);
  }
}

When I print out the payload after the header I receive the following output:

22
{"Switch":"0","LED":"0","DHT":"1"}
0

I know the 22 is the hex value for the number of bytes being sent.  Is there a way of ignoring the numbers and just using the JSON code?


texts: Replace 6 pin on/off switch on Power Bank with 3pin or 2pin?

texts:
I'm looking to finish up my project in a box and i'm using a battery bank to power the Leonardo micro pro and other components. The bank has a little on/off which on it which has 6 pins underneath.

To make the project neater I wanted to fit an on/off rocker switch to the project box making it look better and providing a more substantial switch. Mostly the on/off rocker switches come in 3 pin or 2 pin connections though. Is it possible for me to join it the 6 pin combining some of the pins in some way or not? I can also pick up another battery shield which has a 3 pin switch, again could I combine that with a 2pin if required or do I need to use a 3 pin rocker with it?

Some pictures of what i'm (or could be) using

(Current power bank, on/off switch on the right side in the middle, 6 pins)

Possible smaller power bank for my project with 3 pins on the on/off switch (bottom left side)

Two pin rocker switch

Three pin, two way rocker switch


texts: Cant's code against Yun Wireless Section

texts:
Just got my Yun today.  Successfully connected to my home wireless, installed YunSysUpgrade_v1.5.1,
and divied up my Micro SD card for Linino and Windows file system with YunDiskSpaceExpander,
and got files serving on the native file server from the SD card.

But I can't seem to touch the wireless section from a sketch.

I'm running a mod of the example ScanNetworks sketch - here's the relevant part:

void loop() {
  delay(1000);
  String fv = WiFi.firmwareVersion();
  Serial.println("Version: ");
  Serial.println( fv );
  Serial.println("Status: ");
  Serial.println( WiFi.status() );
  // scan for existing networks:
  Serial.println("Scanning available networks...");
  listNetworks();
}

Here is the ouptut: no version and a status of 255 (which I cannot find documentation on....)

  Version:

  Status:
  255
  Scanning available networks...
  ** Scan Networks **
  number of available networks:0

I looked at installing wifi_dnld.elf, but could not find jumper 3 on my Yun, so assumed it was for the 'true shield'.

What am I doing wrong, or do I need to return this to amazon?


texts: How to digital read and send the data through serial to PC with speed around 2 MHz?

texts:
I would like to read analog data with frequency sampling around 2 MHz and send it to PC to be processed with python for digital oscilloscope. I use Arduino Nano. I have found ADC (AD9057, PDF) that can handle up to 40 MSPS, but i still face some problems

How could I read digital pin quickly around 2-4 MHz? I read that it is possible using direct port manipulation
How could I send the data to PC with that sampling rate? I know that the maximum baud rate of arduino is around 2.000.000 or let say 2 MegaBytes/s, so for 2 MHz sampling, i could only send one character per micro second, could it be more faster?

Thank you


texts: Esp8266 Not showing in Arp table of router

texts:
So I'm working on my senior project which is a smart irrigation system based on an esp8266 NodeMCU.
Everything is fine but I can't bind the IP of the esp8266 on my router's ARP table since it is not showing in any way in the router's table.
Knowing that the esp8266 has an IP 192.168.0.107 // which is not showing in the router.
And I've entered the mac address correctly trying to bind it manually but didn't work.
Any help please?


texts: Arduino Mega 2560 interrupt pins and port mapping with rotary encoder

texts:
I am trying to use port manipulation in interrupts to read a rotary encoder. I found code for a Uno, so the port call for pins 2 and 3 are different. I think on the Mega they are PORTH3 and PORTH4 respectively. My code is not working. Do I have my ports wrong? I've tried reading up on this and I'm not fully understanding the Bxxxxxxxx part. I think that might be what's incorrect. Here is part of my code with one of the interrupts.

static int pinA = 2;
// Our first hardware interrupt pin is digital pin 2
static int pinB = 3;
// Our second hardware interrupt pin is digital pin 3
volatile byte aFlag = 0;
// let us know when we're expecting a rising edge on pinA to signal that the encoder has arrived at a detent
volatile byte bFlag = 0;
// let us know when we're expecting a rising edge on pinB to signal that the encoder has arrived at a detent (opposite direction to when aFlag is set)
volatile byte encoderPos = 0;
//this variable stores our current value of encoder position. Change to int or uin16_t instead of byte if you want to record a larger range than 0-255
volatile byte oldEncPos = 0;
//stores the last encoder position value so we can compare to the current reading and see if it has changed (so we know when to print to the serial monitor)
volatile byte reading = 0;

void setup () {
  pinMode(pinA, INPUT);
  // set pinA as an input, pulled HIGH to the logic voltage (5V or 3.3V for most cases)
  pinMode(pinB, INPUT);
  attachInterrupt(0, PinA, RISING);
  // set an interrupt on PinA,
  //looking for a rising edge signal and executing the "PinA" Interrupt Service Routine (below)
  attachInterrupt(1, PinB, RISING);
  // set an interrupt on PinB,
  //looking for a rising edge signal and executing the "PinB" Interrupt Service Routine (below)
}

void PinA() {
  //CCW
  cli();
  //stop interrupts happening before we read pin values
  reading = PORTH & 0xC;
  // read all eight pin values then strip away all but pinA and pinB's values
  if (reading == B00001100 && aFlag) {
    //check that we have both pins at detent (HIGH) and that we are expecting detent on this pin's rising edge
    encoderPos --; //decrement the encoder's position count
    bFlag = 0; //reset flags for the next turn
    aFlag = 0; //reset flags for the next turn
  } else if (reading == B00000100) bFlag = 1;
  //signal that we're expecting pinB to signal the transition to detent from free rotation
  sei(); //restart interrupts
}


texts: HID communication between Arduino Uno and computer

texts: I used some firmware I found online to turn the UNO into an emulated HID device. The Arduino is no longer connected to a Serial COM port so I can't send serial data from my computer to the device. Is there a way that the Arduino can receive data from the computer in order to drive a function while in the HID emulated state?


texts: Using Flexinol Or Muscle Wire To Control Paper Flower Petal With Arduino

texts: I am relatively new to Arduino and I am looking to use flexinol or muscle wire to control flower petals. I think I will need to control 4 sets of the wire. I have totally no idea of how to wire the components together, if I will need to get additional parts like a transistor or battery, and what type/thickness of wire I should get.


texts: what is a servo motor shield in arduino? what is the key purpose for using it? I'm newbie in arduino and I've seen some briefings in websites which I couldn't understand, can somebody elaborate it to me?


texts:
I've been racking my head trying to start programming in a library organized method. My code works, but the translation and split to a .h and .cpp file is riddled with errors.

It's gotta be stupidly simple all I'm asking for is a review:

Header File

# ifndef _INITIALIZE_H
#define _INITIALIZE_H

#if (ARDUINO >= 100)
# include <Arduino.h>
#else
# include <WProgram.h>
#endif

//-Extra Includes-
#include <config.h> //Provides baud...
#include <SSC32.h>

#define STANDARD 0
#define DEBUG    1
#define VIRTUAL  2

class Initialize {
    private:
        int _mode;
    public:
        Initialize();
        void begin();

};

#endif

associated .cpp file:

//Comments
#include <Initialize.h>
SSC32 SSC;

Initialize::Initialize()
{
    _mode = STANDARD;
}

void Initialize::begin()
{
    SSC.begin(baud);
    if(Serial.available() > 0){
        if(sscReturn == 1){
            Serial.println("ver");
        }
    }
}

The error from the compiler:

D:\Github\Project-Onyx-Quadruped\code\HostControllerFirmware\Onyx-HostFirmware-Initial-7-2-15\libraries\Initialize\Initialize.cpp: In member function 'void Initialize::begin()':
D:\Github\Project-Onyx-Quadruped\code\HostControllerFirmware\Onyx-HostFirmware-Initial-7-2-15\libraries\Initialize\Initialize.cpp:9:12: error: expected primary-expression before '=' token
D:\Github\Project-Onyx-Quadruped\code\HostControllerFirmware\Onyx-HostFirmware-Initial-7-2-15\libraries\Initialize\Initialize.cpp:9:16: error: expected primary-expression before ')' token
D:\Github\Project-Onyx-Quadruped\code\HostControllerFirmware\Onyx-HostFirmware-Initial-7-2-15\libraries\Initialize\Initialize.cpp:9:16: error: expected ';' before ')' token
D:\Github\Project-Onyx-Quadruped\code\HostControllerFirmware\Onyx-HostFirmware-Initial-7-2-15\libraries\Initialize\Initialize.cpp:11:7: error: expected primary-expression before '=' token
D:\Github\Project-Onyx-Quadruped\code\HostControllerFirmware\Onyx-HostFirmware-Initial-7-2-15\libraries\Initialize\Initialize.cpp:11:7: error: expected ')' before ';' token
D:\Github\Project-Onyx-Quadruped\code\HostControllerFirmware\Onyx-HostFirmware-Initial-7-2-15\libraries\Initialize\Initialize.cpp:11:17: error: expected primary-expression before '==' token
D:\Github\Project-Onyx-Quadruped\code\HostControllerFirmware\Onyx-HostFirmware-Initial-7-2-15\libraries\Initialize\Initialize.cpp:11:21: error: expected ';' before ')' token
Failed compiling libraries


texts:
Hello guys ,
             I want to perform a mesh network between 3-4 modules using ESP8266 . Any one have idea how to do it?


texts: Visibility of #define between sketch and library

texts:
I want to have a define from my sketch be picked up by a library.
Here is a similar question for references: Using #define and multiple classes

I have a CI server that compiles my arduino sketchs on commmit. It pulls all my personal libs from an other repository and compiles the sketch using arduino-builder.

Now i want it to also make a debug build. (Some of my library's have debugstatments in them i enable using a #define debugsomething.

Is there any way i can get the compiler to pickup the #define in the sketch or am i better off making a very complex build script that modifies the headers between builds?


texts: Connecting an Ultrasonic Sensor to Arduino (4-Wire)

texts:
I have an ultrasonic sensor that came with a couple of images about the pin-out and wiring diagram.

I am used to the popular ultrasonic sensors that have lots of documentation about how to connect to an Arduino - but I am wondering about to connect this sensor to an Arduino.

The Power Supply is 5V DC, with an operating current less than or equal to 12mA.

Any support or similar tutorials that will help me connect this to an Arduino, to see the output in the Serial monitor, would be great!

VCC and GND are self-explanatory, but how should I connect the Output 1 and Output 2 to the Arduino?

Thanks!


texts: I'm trying to use a E18-D80NK but the output is always 1

texts:
i'm trying to use a E18-D80NK sensor with arduino but the output is always at 1, i really don't understand why
This is my code :

int irPin2 = 8;// define pint 2 for sensor

void setup() {
  Serial.begin(9600);// setup Serial Monitor to display information
  pinMode(irPin2, INPUT);// define pin as Input  sensor
}

void loop() {
  int out = digitalRead(irPin2);// read the sensor

    Serial.println(out);

  delay(250);
 // E18-D80NK Obstacle Sensor
}

and circuit:


texts: How to read code from Arduino Uno to Arduino IDE?

texts: we can upload a code into Arduino UNO from our computers, but how about reading code? Can we read and get C codes from compiled codes from Arduino hardwares? My second question is that will we read these compiled codes on Arduino ZERO's debug port, which will be a new product for us as developers?


texts: Arduino Micro: 69 is supposed to show up when I press 1 on the keypad, however some weird number (15 in this case) is showing up

texts:
// **I AM ALSO GETTING WEIRD CLUELESS DELAYS WHEN I PRESS BUTTONS ON THE MODE MENU**

/*
   Jebediah's Launch Control System for Kerbal Space Program
   Alpha Build 0.70
   An Open-Source Project by John Seong
*/

#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <Keypad.h>

const byte ROWS = 4;
const byte COLS = 3;

char keys[ROWS][COLS] = {
  {'1', '2', '3'},
  {'4', '5', '6'},
  {'7', '8', '9'},
  {'*', '0', '#'}
};

int timeV, thrustV, massV, gravityV;

byte rowPins[ROWS] = {12, 11, 10, 9};
byte colPins[COLS] = {8, 7, 6};

Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);

bool keyDetect = false;
bool menuKeyDetect = false;
bool goHomeDetect = false;

bool countDownDetect = false;
bool countDownOutput = false;
bool twrCalDetect = false;

String timeValue, thrustValue, massValue, gravityValue;

LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

void setup() {
  Serial.begin(9600);
  lcd.begin(16, 2);
  lcd.clear();

  Startup();

  timeV = constrain(timeV, 15, 120);
}

void loop() {
  PressKey();

  if (menuKeyDetect == true) {
    PressMenuKey();
  }

  if (goHomeDetect == true) {
    GoHome();
  }

  if (countDownDetect == true) {
    CountDownSequence();
  }

  if (countDownOutput == true) {
    CountDownOutputSequence();
  }
}

// Pages & Sections
void Startup() {
  lcd.print("Jeb's Launch");

  lcd.setCursor(0, 1);
  lcd.print("Control System");

  delay(3000);

  lcd.clear();
  lcd.print("Alpha Build 0.70");

  lcd.setCursor(0, 1);
  lcd.print(" STUDIO HORIZON");

  delay(3000);

  lcd.clear();
  lcd.print("Welcome, Kerman");

  lcd.setCursor(0, 1);
  lcd.print("Press any key...");

  keyDetect = true;
}

void ModeMenu() {
  menuKeyDetect = true;

  lcd.clear();
  lcd.print("1. Countdown");

  lcd.setCursor(0, 1);
  lcd.print("2. TWR");
}

void CountDown() {
  lcd.print("Time (sec): ");

  lcd.setCursor(0, 1);
  lcd.print("# to continue...");

  goHomeDetect = true;
  countDownDetect = true;
}

void TwrCal() {
  lcd.print("Thrust: ");

  lcd.setCursor(0, 1);
  lcd.print("# to continue...");

  goHomeDetect = true;
}

// Actions & Behaviours
void PressKey() {
  char key = keypad.getKey();
  if (key) {
    Serial.println(key);
    if (keyDetect == true) {
      lcd.clear();
      ModeMenu();
      keyDetect = false;
    }
  }
}

void PressMenuKey() {
  char key = keypad.getKey();
  if (key == '1') {
    Serial.println(key);
    if (menuKeyDetect == true) {
      lcd.clear();
      CountDown();
      menuKeyDetect = false;
    }
  } else if (key == '2') {
    Serial.println(key);
    if (menuKeyDetect == true) {
      lcd.clear();
      TwrCal();
      menuKeyDetect = false;
    }
  }
}

void GoHome() {
  char key = keypad.getKey();
  if (key == '*') {
    lcd.clear();
    ModeMenu();
  }
}

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

  if (key == '0') {
    timeV = timeV + 0;
  }

  if (key == '1') {
    timeV = 69;
  }

  countDownDetect = false;
  countDownOutput = true;
}

void CountDownOutputSequence() {
    lcd.setCursor(13, 0);
    Serial.println(timeV);
    lcd.print(timeV);
}


texts: Serial Port configuration with asio C++ library

texts:
I've made a small interface using the asio C++ library to open serial ports and do I/O from/to them.
It works with my Arduino Uno and other hardware as well (industrial weighing machines), but I only specify the port and baud rate.

The following code is run in the client application, which runs both on my Windows 10 Student Edition x86_64 machine, and on old 32 bit  Win XP machines that communicate with the weighing machines:

/*this is inside a constructor*/
/*iosvc gets passed by reference, port_ is a member variable of type asio::serial_port,
 npuerto is the name of the port (e.g. "COM3") */

port_(iosvc_, npuerto),

/*...*/

port_.set_option(asio::serial_port_base::baud_rate(baudios));

The Arduino is programmed to do a serial echo of whatever is sent to it, for testing purposes. This is the echo code:

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

void loop()
{
  while(Serial.available())
  {
    Serial.write(Serial.read());
  }
}

It works fine with my Arduino until I unplug it and plug it back in. After replugging it all the values returned are garbage, specifically some sort of '?' character inside a black box, don't know the bit value though, but it's constant. The problem gets fixed when I open an arduino IDE Serial Port monitor.
If I close it, and once again use my own software to open up the serial port, all the values are fine.

From this I concluded that the Arduino IDE Serial Port monitor is doing something when it opens up the port that I'm not doing.

Any clues? Flow control? Handshake?
Thanks


texts: Now at IDE 1.0.5, should I upgrade to 1.0.6 or 1.5.7 Beta for Pro mini and ATMega2560 use?

texts:
Do I need to re-install many libraries (or similar 'house keeping' works)? Is the upgrade straight forward?

Apparently, from Arduino web, one need 1.5 BETA series for use with Due. For Pro Mini, UNO and ATMega2560, should one use 1.5 BETA or 1.0.6 (no beta, presumable stable)?

I am running out of code space. Wonder if the upgrade will install a newer gcc compiler and smaller code size?


texts:
I'm looking for a way to wait for a response from an AT command to return OK or CONNECTED or whatever the command returns when it's true.

I can check if the serial is available, but that means I have to manually guess what time between commands to give them time to connect or start.

Function:

void ModemCommand(String command) {
  //Send command to modem
  mySerial.println(command);
  Serial.println(command);
  delay(100);
  while (!mySerial.available()) {
    //Wait for Response from modem
    Serial.println(F("No response yet"));
    delay(1000);
  }
  while (mySerial.available()) {
    Serial.write(mySerial.read());
    //Print response from modem
  }
  Serial.println("");
  //Linefeed after reponse
  delay(10);
}

Code example:

ModemCommand(F("ATE0"));
//Turn on echo
ModemCommand(F("AT+CFUN=1"));
//Turn modem functions on
waitSec(8,F("turning on Modem functions"));
ModemCommand(F("AT+CGREG?"));
//GSM attached?
ModemCommand(F("AT+CSQ"));
//Signal Quality
ModemCommand(F("AT+CSTT=\"internet\""));
//Set APN
ModemCommand(F("AT+CIICR"));
//Connect to APN GPRS
waitSec(8,F("connecting to APN GPRS"));
ModemCommand(F("AT+CIFSR"));
//Get IP

Does anybody know how to do this?


texts:
Question completely rewritten

Trying to assess an Arduino project feasibility. New to Arduino... but did a lot of controller programming (assembly), Roboteq (C) and Phidgets (C++) , using various kinds of motors and sensors ; and reading the Arduino documentation makes me feel confident interfacing and programming shouldn't be an issue.

However, before investing time (and some money) in the project, I thought it'd be better to ask here if Arduino is the right choice, considering

a non-latching Hall sensor is to be connected to Analog 0, analogRead() to return a [0,1023] value, used as a proximity sensor. This should be straight forward.

Question →

while the Arduino runs my program, and is still connected to the PC (USB), is it possible to synchronously or asynchronously send commands from the PC to the Arduino. I.e. can the Arduino poll if there is something coming from USB (synchronous), or is there a way for the PC via USB to have Arduino do something (asynchronously)?

Thank you.


texts: To know the state of USB (Serial) connection (connected or not connected)

texts:
if (Serial.available()) {
        digitalWrite(7, HIGH);
} else {
        digitalWrite(7, LOW);
}

It doesn't seem to be so simple.
My testing LED turns on when the USB connection with another program is established, but it doesn't turn off (LOW) when that program exits.


texts: Random data sending integers between two Arduinos

texts:
I'm trying to do something seemingly simple, but I'm running into difficulties. I want to send about 5 separate integers between two Arduinos over software serial. I have written the following, but I rarely get the two numbers on the receiving end - they're usually garbled or in the wrong order. I'm sure that I'm missing something obvious, but I can't work it out no matter how hard I try. Any help would be greatly appreciated.

Sender:

#include <SoftwareSerial.h>

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

int val, val2;

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

void loop()
{
  val = 123;
  val2 = 456;
  if(mySerial.read()=='#')
  {
    mySerial.write(highByte(val));
    mySerial.write(lowByte(val));
    delay(3);
  }
  if(mySerial.read() == '~')
  {
    mySerial.write(highByte(val2));
    mySerial.write(lowByte(val2));
    delay(3);
  }
}

Receiver:

#include <SoftwareSerial.h>

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

byte val;
byte low, high;

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

void loop()
{
  mySerial.write('#');
  byte h = mySerial.read();
  byte l = mySerial.read();
  int y = word(h, l);
  delay(2);
  mySerial.write('~');
  byte h2 = mySerial.read();
  byte l2 = mySerial.read();
  int z = word(h2, l2);

  Serial.println(y);
  Serial.println(z);
  Serial.println();
}


texts: Fried two Arduino Nano's but works when powered

texts:
It took me about 4 hours to desolder an Arduino Nano I fried and solder on the new one. I'm not exactly sure how but I shorted it somehow while trying to install the nano onto my robot. I could smell a fait burning and the nano no longer powered on or allowed me to upload code via USB.

When I put the second nano on, before properly insulating exposed wire, I fried it again!! This time I actually saw a little smoke and quickly unplugged it. The nano no longer responds to the USB, but...

I have this nano also being powered by an Arduino Uno. When I turned on the battery connected to the Uno, the Nano turned on and everything was working fine!! I was pretty relieved after a short spout of depression! I plugged in the USB to the Nano and I was able to upload code... only with the nano being powered from the Uno. If I turn off the battery to the Uno the Nano doesn't work with USB.

I have no idea what happened exactly and I'm not sure what fried on my Nano but I sure am glad I have this work around instead of replacing the Nano again!

Does anyone know why it's doing this? What did I see smoking? Is it repairable?


texts: My motor shield is not working while feeding codes to rotate motors. Now making my own motor shield. May anyone help me how to make one???


texts: Pro Micro HID freezes during computer boot or resume from standby

texts:
I am using a Pro Micro as a HID touchpad, connected to a laptop running Ubuntu 17.04. Everything works, except that the board freezes or hangs while the computer boots or resumes from standby, requiring me to disconnect and reconnect it every time.

The board is definitely hanging, not resetting; I have programmed the on-board LEDs to flash in sequence during the setup and loop stages and have determined that the board hangs at random points in the program and does not reset. This suggests to me that the problem lies with the computer or the connection rather than the Arduino.

The hangs occur at specific points during the computer's boot sequence. If I boot with the Arduino connected, it will hang very early in the boot while the manufacturer's logo is visible on screen. If I connect the board at GRUB, the board will hang during Ubuntu's boot sequence, somewhere among the commands to initialize hard disk buses. Less predictably, the board will hang about 75% of the time just after logging in or when resuming from standby (just before the login manager appears).

I wonder whether the power supply may be dropping by some amount sufficient to halt execution, but not enough to reset the board, but I don't know if that's a realistic hypothesis. I don't know how to investigate further.

What could be causing this issue? What steps could be taken to determine and solve the problem?

Edit - February 2018

I have updated my operating system to Ubuntu 17.10, which uses GNOME Display Manager for the login prompt instead of LightDM, and the problem no longer occurs when resuming from suspend. So it appears the communication that froze the Arduino was triggered by LightDM, not the BIOS.


texts: ESP8266 on WiFi without password, possible?

texts:
Is it possible to connect to an SSID that does not require a password?
My project using ESP8266-01 modules will sometimes be used in non-password protected guest networks.


texts: Arduino Pro Micro, get data out of Tx pin?

texts:
I have a Sparkfun Arduino Pro Micro with an ATmega32u4 on it and a Roving Networks RN32 Bluetooth Module

Theoretically, I should be able to solder the Rx of the Bluetooth to the Tx on the arduino and vice versa and I should get serial communication over the Bluetooth.

Of course, I do not. However, as a first question: How do I get my Arduino to transmit data over the Tx pin?

I uploaded this to the Arduino with no hiccups:

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

void loop(){
  Serial.print("HelloWurld");
}

However, when I plug up my o-scope, I see no signal over the Tx line. Nada. I see data coming over the USB into the COM port on my computer, but nothing over the Tx pin.

How do I get the Arduino to put out serial data on the Tx pin?


texts: Arduino OBD library and software serial library

texts:
Can I use Arduino OBD library with "custom" software serial or it needs to be used with hardware UART only? For example if I have D5 and D6 pin as RX and TX in my code hooked on OBD board, how do I initialize OBD library from there?

This is the OBD library that I'm referring to.

And I'm using this Allpro OBD board.

Update
Actually I would be satisfied with a answer how to know when entire response from the board is received, because this way is way too messy:

void getResponse(void){
 while(obdSerial.available()){
   Serial.write(obdSerial.read());
  }
}

Here I don't know when the message is received. And if I try to use example from Sparkfun obd-ii-uart-hookup-guide (different board doe) I ended up in infinite-loop since the board never return \r, if I send ELM command to use \n as terminator, and if I disable ELM to echo the command so that I use just one getResponse call I get some readings, but not all the time, I ended up in infinite-loop again.


texts:
I am trying to make a smart lock for bicycles. This lock can be controlled with the help of smartphones. For the purpose, I am using an Arduino interfaced with HC-05 Bluetooth Module which receive commands from an Android smartphone.

The overall project is almost over, except the actual lock. I want to create a lock with a pin which can be slide between the spokes of the wheel to cease the motion of the wheels. I can't find any product in the Indian market. Can you please suggest any product available or how to make one myself?

  I've seen the solenoid locks but their stroke is too small to make a meaningful lock out of it.

Your help will be well appreciated.


texts: Problem with simple sound detection circuit using a microphone

texts:
I am very new to this community. My first project with Arduino was using a LDR (light dependent resistor) in a circuit like this:

The input I got was as expected between 0 - 1023.

I then tried a similar project this time using a sound sensor like this:

My circuit is as follows:

A0 on mic to A0 on Arduino
GND to GND
+ve to 5V
LED along with resistor to digital pin 9 on Arduino

My program is as follows:

const int analogInPin = A0;
int sensorValue = 0;

void setup() {
  pinMode(analogInPin, INPUT);
  pinMode(9, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  sensorValue = analogRead(analogInPin);
  Serial.print("sensor = ");
  Serial.print(sensorValue);
  Serial.print("\n");
  if(sensorValue > 900)
    digitalWrite(9,HIGH);
  else
  digitalWrite(9,LOW);
}

The problem is the serial monitor gives a weird reading, randomly giving 1023 and 0 after regular intervals.

sensor = 124
sensor = 0
sensor = 1023
sensor = 39
sensor = 352
sensor = 1023
sensor = 142
sensor = 0
sensor = 1023
sensor = 44
sensor = 338
sensor = 1023
sensor = 163
sensor = 0
...
...

I can't figure out the problem myself so I came here.


texts:
I've tried to copy CH340G from other schematics and existing Arduino Uno Clones...
Searched online & StackExchange but no good :/ My problem is almost the same as this one

Here is my schematic

I can read & send data from the serial monitor

OS: Win 10 64 Bit
USB Driver: 3.5.2019.1

Upload Options:

Arduino IDE version: 1.8.12
Board: Arduino Uno (also tired nano & nano old bootloader options)

What I've tried:

With & without the driver
Rebooted the computer
Tried different ports
Different cables
In case of IC not working, I've desoldered IC from working UNO
Changed RX, TX vice versa
Without R1 & R2
Different capacitors on C6 and C3
Buuut results are always the same as below

avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

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

         Using Port                    : COM3
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xf3
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xf3
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xf3
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xf3
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xf3
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xf3
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xf3
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xf3
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xf3
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xf3

avrdude done.  Thank you.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

I appreciate any help, idea, suggestion
Regards


texts: Undefined reference to Class::function()

texts:
I have three files:

main.cpp
RotaryEncoder.h
RotaryEncoder.cpp

Note that the RotaryEncoder class acts as a wrapper to the Encoder library. I am getting the following build report and I haven't been able to find the bug for the past couple days:

Build output from PlatformIO on VS Code

Processing uno (platform: atmelavr; board: uno; framework: arduino)
--------------------------------------------------------------------------------------------------------------------------------------------------------------------
Verbose mode can be enabled via `-v, --verbose` option
CONFIGURATION: https://docs.platformio.org/page/boards/atmelavr/uno.html
PLATFORM: Atmel AVR 1.15.0 > Arduino Uno
HARDWARE: ATMEGA328P 16MHz, 2KB RAM, 31.50KB Flash
PACKAGES: toolchain-atmelavr 1.50400.190710 (5.4.0), framework-arduinoavr 4.1.2
LDF: Library Dependency Finder
LDF Modes: Finder ~ chain, Compatibility ~ soft
Found 7 compatible libraries
Scanning dependencies...
Dependency Graph
|-- <Encoder>
Building in release mode
Compiling .pio/build/uno/src/main.cpp.o
Linking .pio/build/uno/firmware.elf
/var/folders/t1/fyh283nd1m7dxbrjlkjtf_kc0000gn/T//ccZN56Tq.ltrans0.ltrans.o: In function `main':
<artificial>:(.text.startup+0x2dc): undefined reference to `RotaryEncoder::getCount()'
collect2: error: ld returned 1 exit status
*** [.pio/build/uno/firmware.elf] Error 1

Explicit Error

  In function 'main':
  :(.text.startup+0x2dc): undefined reference to 'RotaryEncoder::getCount()'.

main.cpp

#include <Arduino.h>
#include "RotaryEncoder.h"

#define cartEncoderPhaseA 3
#define cartEncoderPhaseB 4
#define pendulumEncoderPhaseA 2
#define pendulumEncoderPhaseB 5

// Initialize encoders
const double ENCODER_PPR = 2400.0;
RotaryEncoder cartEncoder(cartEncoderPhaseA, cartEncoderPhaseB, ENCODER_PPR);
RotaryEncoder pendulumEncoder(pendulumEncoderPhaseA, pendulumEncoderPhaseB, ENCODER_PPR);

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

void loop()
{
  long cartCount = cartEncoder.getCount();
}

RotaryEncoder.h

#pragma once

#include <Encoder.h>

class RotaryEncoder
{
private:
    Encoder encoder;
    double encoderPPR;
    double angleLowerBound;
    double angleUpperBound;

    double convertEncoderCountToRadians(long encoderCount);
    double normalizeAngle(double angle);

public:
    RotaryEncoder(int phaseA, int phaseB, double encoderPPR);
    long getCount();
    double getRadiansAndOffsetBy(double angleOffset);
    void setAngleLowerAndUpperBounds(double lowerBound, double upperBound);
};

RotaryEncoder.cpp

#include "RotaryEncoder.h"

RotaryEncoder::RotaryEncoder(int phaseA, int phaseB, double encoderPPR)
: encoder(phaseA, phaseB), encoderPPR(encoderPPR)
{}

inline long RotaryEncoder::getCount()
{
    return encoder.read();
}

inline double RotaryEncoder::getRadiansAndOffsetBy(double angleOffset)
{
    long encoderCount = getCount();
    double angleInRadians = angleOffset + convertEncoderCountToRadians(encoderCount);
    angleInRadians = normalizeAngle(angleInRadians);

    return angleInRadians;
}

inline double RotaryEncoder::convertEncoderCountToRadians(long encoderCount)
{
    return ((double)encoderCount / (encoderPPR)) * (2.0 * PI);
}

inline double RotaryEncoder::normalizeAngle(double angle)
{
    // Constrain an angle between [-pi, pi). Output is in radians
    // see: https://stackoverflow.com/questions/11498169/dealing-with-angle-wrap-in-c-code

    angle = fmod(angle + PI, 2 * PI);

    if (angle < 0)
        angle += 2 * PI;

    return angle - PI;
}

inline void RotaryEncoder::setAngleLowerAndUpperBounds(double lowerBound, double upperBound)
{
    angleLowerBound = lowerBound;
    angleUpperBound = upperBound;
}


texts: How to build circuit to switch to other power source if primary source dies?

texts:
I would like to have a backup battery connected to a device that requires an uninterrupted power supply, like an Arduino or Raspberry Pi, so that if my primary power source (USB plug) gets pulled, the device will switch to being powered by the battery.

I need a solution that I can either build on a breadboard or buy for only a couple dollars. Does anyone know a solution? I'm assuming this is a common need and think I perhaps am not searching with the correct key words.

Edit:

I would like to add that I may also use 4AA batteries and a DC-DC step down module to produce 5V exactly to power a 5V device, so I'm looking for a solution that accepts 5V. Assume the device, let's say Raspberry Pi, takes 5V, the power supply is 5V, and the battery backup is 5V.


texts: How to control the power of attiny13a via pin change interrupt?

texts:
I'm trying controll the power of attity13a and turn off/turn on the led.
I'm going to goals:

After to click on the button0
led will blicking 5 second nad then the attiny13a going to sleep.
After to click on the button1 then wake attiny13a up and then led will shane.

The button0 to sleep and blink the led.
the button1 to wake up and turn on the led.
Could you explain what is wrong in this sketch, please?
thank you for your answers.

code:

    #define F_CPU   1200000UL
    #define LED     PB2 // PB2
    #define BUTTON1 PB1 // PCINT1
    #define BUTTON0 PB0 // PCINT0

    #define HIGH         1
    #define LOW          0
    #define INPUT        0
    #define OUTPUT       1
    #define INPUT_PULLUP 2
    #define FALSE        0
    #define TRUE         1
    #define _BV(bit)    (1 << (bit))

    #include <avr/io.h>
    #include <avr/interrupt.h>
    #include <avr/sleep.h>
    #include <util/delay.h>

    void pinMode(uint8_t pin, uint8_t mode)
    {
        if(mode == OUTPUT) // Pin as output
            DDRB |= _BV(pin);
        else // Pin as input or input pullup
        {
            DDRB &= ~_BV(pin); // Set pin as input
            if(mode == INPUT_PULLUP)
                PORTB |= _BV(pin); // Enable pullup resistors
        }
    }

    void digitalWrite(uint8_t pin, uint8_t val)
    {
      if(val)
        PORTB |= _BV(pin);  // Set pin high
      else
        PORTB &= ~_BV(pin); // Set pin low
    }

    uint8_t digitalRead(uint8_t pin)
    {
      return !!(PINB & _BV(pin));
    }

    // go to sleep
    ISR(PCINT0_vect)
    {
       if(digitalRead(BUTTON0)){
            int i=0;
            while(i<10){
                blink();i=i+1;
            }
            set_sleep_mode(SLEEP_MODE_PWR_DOWN);
            sleep_enable();
            sleep_cpu();
        }
    }

    //wake up
    ISR(PCINT1_vect){
       if(digitalRead(BUTTON1)){
        digitalWrite(LED, HIGH);
       }
    }

    void blink(){
        digitalWrite(LED, LOW);
        _delay_ms(500);
        digitalWrite(LED, HIGH);
        _delay_ms(500);
    }

    int main(void)
    {
        pinMode(BUTTON0, INPUT_PULLUP);
        pinMode(BUTTON1, INPUT_PULLUP);

        pinMode(LED, OUTPUT);
        digitalWrite(LED, LOW);

        // Sets the Pin change interrupt mask PB0, PB1
        PCMSK |= _BV(PCINT0)|_BV(PCINT1);

        //Enables Interrupts globally after setup
        //sei();
        SREG |= _BV(SREG_I);

        while(TRUE){}
    }


texts: Arduino Video Feed (Building Zumo Robot)

texts:
I'm building a Zumo robot with my daughter, but I have very limited experience and knowledge with programming and electronics. Pictures of the equipment I have are in this link and the last picture has all the equipment together: https://imgur.com/a/ehPpFnV. I wanted it to be a fun challenge to build, but I honestly don't know where to start. I'm looking for some advice on how to get started with the Arduino software and hardware. I need to:

Hook up the 2 screens to the power supply (from the Zumo?) or see if I need to buy a separate power supply.
Figure out how to use the SD card with the Arduino so I can pull video from the card and put it on one or the other screen.
How to learn any other programming for the Arduino that may be helpful for this project.

I know this is a lot to ask, but anything helps. Thanks so much!


texts:
I am trying to communicate with a serial port trought matlab. This is my code:

delete (instrfindall)
clear all
close all
clc;

s=serial('COM4');
set(s,'BaudRate',4800);
set(s,'DataBits',8);
set(s, 'Parity','none');
set(s,'StopBits',1);
set(s, 'FlowControl','none');
set(s,'Terminator','CR');
set(s,'TimeOut',5000);

fopen(s)
%Move the probe radial
fprintf(s,'%s','RADIAL=100');

out=fgets(s);

fclose (s)
delete (s)
clear (s)

But i cannot make the serial port to answer me.
Can you help me? Is this code right?

Best regards,


texts: Arduino Saint Smart Chapter 7 Tri Color Module

texts:
I am very new to Arduino, I bought a starter's kit and I am working with the user manual that is available. I am in chapter 6 Tri Color Module

I am using the following code:

// Defining the LED driver pins and some other
// variables.
const int numLEDs = 3;

int blueLEDPin  = 3;
int greenLEDPin = 4;
int redLEDPin   = 5;
int ledPin[3];
int ledPinIndex = 0;

// the setup routine runs once when you press reset:
void setup() {

  Serial.begin(9600);

  // initialize the digital pin as an output.
  ledPin[0] = blueLEDPin;
  ledPin[1] = greenLEDPin;
  ledPin[2] = redLEDPin;

  for (int i=0; i < numLEDs; i++)
     pinMode(i, OUTPUT);

}

// the loop routine runs over and over again forever:
void loop() {

  digitalWrite(ledPin[ledPinIndex%numLEDs], HIGH);
  delay(1000);
  Serial.println(ledPinIndex%numLEDs);
  delay(2000);
  digitalWrite(ledPin[ledPinIndex%numLEDs], LOW);

  ledPinIndex++;
}

My problem is that in the setup() method where the following code is

for (int i=0; i < numLEDs; i++)
         pinMode(i, OUTPUT);

From my understanding pinMode OUTPUT is use to send power out of the specific pin. As the code displays pin 3, 4, and 5 are used but the above code is setting pinMode for 0, 1, 2. Is this write? And even if I comment out the two lines up my project no differently as to the previous code.

Can someone verify if the above code is correct, or should it be setting pinMode for 3, 4, and 5.


texts: comprehensive list of common library methods that do not work in interrupt service routines

texts:
Where is a comprehensive and authoritative list of commonly used library or built-in methods (functions) that do not work properly in Arduino interrupt service routines?

I am aware of the following:

do not use delay()
do not use Serial print methods

which are part of Nick Gammon's advice linked here. His TLDR summary is:

  TL;DR :

  When writing an Interrupt Service Routine (ISR):

Keep it short
Don't use delay ()
Don't do serial prints
Make variables shared with the main code volatile
Variables shared with main code may need to be
            protected by "critical sections" (see below)
Don't try to turn interrupts off or on

however, I am looking for, as I said, a list that is more comprehensive and authoritative.


texts: Anyone know how to wire a lcd with a button to react when the button is pressed and print on the lcd


texts:
I try to use the Timer0 of an Arduino Leonardo (ATmega32u) to trigger an interrupt at regular intervals, using plain avr-gcc (not the arduino library). I try to blink the built-in LED as test, but it does not light up.

If I place a PINC=0x80; in the main function, the LED turns up, but not if I do it from the interrupt.
What am I doing wrong?

EDIT : The LED turns on with TCCR0B = (1 << CS00);, (no prescaler) or TCCR0B = (1 << CS01) (prescaler /8), but it does not with TCCR0B = (1 << CS00) | (1 << CS02); (prescaler /1024, what I want). At 16MHz CPU frequency the resulting frequency should be more than 15kHz, so I should see it instantly.

Here is my code:

#include <avr/io.h>
#include <avr/interrupt.h>
#include <stdbool.h>

ISR(TIMER0_OVF_vect)
{
    PINC = 0x80;
}

int main()
{
    DDRC = 0b10000000;

    //Start Timer 0 @ 15625 Hz
    TCCR0A = 0;
    TCCR0B = (0b101 << CS00);
    TIMSK0 = (1 << TOIE0);
    sei();

    while(true); // Avoid return from main
}


texts: Arduino not running code without connection to PC via USB

texts:
I have an Arduino UNO and esp8266 connected to it. Both devices has separate power lines. Each connected via USB cable, for Arduino USB used as power line and standard firmware uppload line, for esp8266 only as power suppli line. If I connect all to computer's USB ports, everything working fine. But, if I connect Arduino to separate charger that has USB port, then Arduino not running code. I can see it by Serial interface work, because code using it intensively, and when I'm turning Arduino on the RX and TX lines are down all the time, that I think indicates, that code is not running, and Arduino in boot mode, somehow.

I've made a search through same issues and nothing helped from theirs suggestions. I tried to pull RX line to GND through resistor, to make sure that there are no noise on the line, added capacitors for power supply line, to make exclude pulsations on the line. But nothing helped.

Arduino not running code independently from esp8266. I tried to run Arduino separately, without any other connections, but it not helped. Still not running.


texts: Dual Channel Reading with 16 bit AD7705(SPI)

texts:
I want to read 2 separate voltage readings by AD7705 ADC and send the data to Arduino(Master). What is the correct program flow should I implement to get dual-channel operation working. How data will be sent to master when both the channels are converting the voltage.
Thanks in Advance.


texts: sim800l only receiving SMS after serial monitor is started otherwise not receiving

texts:
I am using SIM800L and Arduino Uno.

The programme is working fine when I turn the serial monitor on using Arduino IDE but when I start the Arduino board by using the adapter it is not receiving anything. I have blinked LED on receiving SMS.

#include <SoftwareSerial.h>

SoftwareSerial wire(3, 2);
String  Grsp;

void setup()
{
   wire.begin(9600);
   Serial.begin(9600);
   wire.println("AT+CMGF=1");
    wire.println("AT+CNMI=2,2,0,0,0");
  pinMode(8, OUTPUT);
  digitalWrite(8, HIGH);
  delay(1000);
    digitalWrite(8, LOW);

   delay(100);
}

void loop()
{

  if (wire.available()>0)
  {
        Grsp = wire.readString();
     Serial.println(Grsp.length());
     Serial.println(Grsp);

     if(Grsp.length() > 100)
     {
       Serial.println("if crossed");

      digitalWrite(8, HIGH);
       delay(1000);
        digitalWrite(8, LOW);

      }

}

}


texts: how does c++ understand which function must to use?

texts:
in this code:

    void AdptSendReply(const char* str)
{
    string s(strlen(str) + 2);
    s = str;
    AdptSendReply(s);
}

void AdptSendReply(const string& str)
{
    string s(str.length() + 2);
    AdptSendReply(s); // use the next one
}

void AdptSendReply(string& str)
{
    if (AdapterConfig::instance()->getBoolProperty(PAR_LINEFEED)) {
        str += "\r\n";
        AdptSendString(str);
    }
    else {
        str += "\r";
        AdptSendString(str);
    }
}

i think c++ use of overloading ability.but how it can recognize which of the two functions "void AdptSendReply(string& str)" or "void AdptSendReply(const string& str)" must use?!


texts:
This is the code I am currently using, but I want to add an arithmetic
mean to it. My goal is: when the pin A0 reads 5 values, I get the average
on which the fan and led will depend to be turned on and off, instead of
5 separate measurements.

int tempPin = A0;
int fan = 3;
int led = 8;
int temp;
int tempreal;
int tempMin = 20;
int tempMax = 30;

void setup()
{
  Serial.begin(9600);
  pinMode(fan, OUTPUT);
  pinMode(led, OUTPUT);
  pinMode(tempPin, INPUT);
}

void loop()
{
  temp = analogRead(tempPin);
  tempreal = temp * 0.48828125;
  delay(1);
  if(tempreal > tempMax)
  {
    digitalWrite(fan,HIGH);
    digitalWrite(led,LOW);
    delay(1);
  }
  else if (tempreal < tempMin)
  {
    digitalWrite(fan,LOW);
    digitalWrite(led,HIGH);
    delay(1);
  }
  else if (tempreal >  tempMin && tempreal <  tempMax)
  {
    digitalWrite(fan,LOW);
    digitalWrite(led,LOW);
    delay(1);
  }
}

Edit by Edgar Bonet – The OP added in a comment to my answer:

“I tried [averaging consecutive readings]. It worked as you would expect
but it still does not solves my problem. My sensor is only getting right
values in the beginning of the scanning and then it varies. That is why
I wanted to make average value but it still does not work. Sadly I think
I wont be able to change sensor, but is there any other way to
camouflage this problem?”

Below is a screenshot showing both correct (✓) and incorrect (✗)
readings:


texts: U-blox Neo-6M GPS module and RX LED of Arduino aren't blinking

texts:
I started recently working with a uBlox Neo 6M GPS module.
Connection between Arduino and GPS module....
Vcc pin --> 3.3V ,
Tx pin --> D2,
Rx pin --> D3,
Gnd --> Gnd

I tried with this code:
#include <SoftwareSerial.h>
// Choose two Arduino pins to use for software serial
int RXPin = 2;
int TXPin = 3;
//Default baud of NEO-6M is 9600
int GPSBaud = 9600;
// Create a software serial port called "gpsSerial"
SoftwareSerial gpsSerial(RXPin, TXPin);
void setup()
{
  // Start the Arduino hardware serial port at 9600 baud
  Serial.begin(9600);
  // Start the software serial port at the GPS's default baud
  gpsSerial.begin(GPSBaud);
}
void loop()
{
  // Displays information when new sentence is available.
  while (gpsSerial.available() > 0)
    Serial.write(gpsSerial.read());
}

About 2-3 hours, I was working with it.. But I do not get the GPS LED to blink, as well as my Arduino's RX LED. In serial monitor I didn't get any data. Is my gps module destroyed??


texts:
For one of my hobby projects I would like to use:

Wemos D1 mini pro (schematic)
Wemos D1 Relay Shield (schematic)

to control the 24V (19W) mist maker.

My current wiring is this:

As you can see the both grounds (12V and 5V) are attached to the com connector of the power supply.

I wonder whether grounds should be decoupled (for whatever reason) - i.e. to use separate power supplies? If the above wiring is OK I would really like to know in which circumstances (if any) a separate power supplies would be needed.

Thanks for all your answers in advance.


texts: What are possible issues when moving Arduino to another microcontroller?

texts:
When Arduino was conceived AVR was very much the best 8-bit controller available. But we're 10 years on now, and still using the AVR, despite lots of better microcontrollers available, notably ARMs. In particular M0 and M0+ cores are a lot cheaper, yet are a lot faster and have many more features than AVR.
For instance the NXP LPC824 has more serial buses, more A/D channels and higher A/D resolution, is almost twice as fast as the AVR, yet costs 30% less. (Granted, it doesn't have EEPROM, but you can have that for 20 cents.)

So I was wondering if there are particular issues which prevent the use of more modern microcontrollers on Arduino.
One difference may be Vcc, which is 5V for AVR and 3.3V for ARM. But given that more peripherals work at 3.3V this seems more to be an AVR issue than an ARM issue.

PS: I'm aware of Arduino Due, but that one costs twice as much as a Uno. I'm talking about controllers which price-wise can compete with AVR.


texts: How to filter a blank line received over serial - ESP8266

texts:
How can I filter a garbage completely blank line over my serial data? It comes from the wifi module ESP8266

How I read data:

  while (Serial1.available()){
       String inData = Serial1.readStringUntil('\n');

       Serial.println("Got: " + inData);

  }

Here is my common output:

Got: AT+CIPSEND=6
Got:
Got: OK
Got: >
Got: Recv 6 bytes
Got:
Got: SEND OK
Got:
Got: +IPD,21:Volume From: 99 To 89AT+CIPCLOSE
Got: CLOSED
Got:
Got: OK


texts: Arduino IDE on Linux - directory not found

texts:
I have Ubuntu 14.04 installed on a chromebook through crouton. I'm trying to install the Arduino IDE. I figured out that I needed the 64-bit version of the IDE and downloaded it. Then, I started following the instructions given - I found the downloaded file, which was named arduino-1.8.0-linux64.tar.xz, opened it (this opened a new window in a program called Xarchiver, which listed the subfolders and files), and saw the install.sh file. When I right-clicked, there was no option to run it from the terminal, so I went back to the terminal and did cd Downloads and then tried to cd into the downloaded file. However, it said that there was no such directory. I listed the files in Downloads, and the downloaded file came up, listed in red.

How can I run the install.sh file? What am I doing wrong? Any help would be appreciated.


texts: Code flow execution between loop() and timer interrupts

texts:
My platform is the Arduino DUE.
I know that the timer counts up to a certain value, then generates an interrupt.
In the Arduino DUE, you can specify the timer value. In other words, you can specify the frequency of the intterupts. You can do this via the TC_SetRC(tc, channel, rc) function.

My question is how code flows in general.
Obvisouly the arduino runs the setup function first.
After that it jumps to loop.
But when does tghe timer starts counting down? When you first jump to loop?
Can you figure out how many instructions will be executed in the loop function, before a call to a timer interrupt is performed, for the given frequency you have specified?

After the interrupt is fired, all the code in the interrupt is run.
Then code flow jumps back to loop()?
And when the timer starts counting again? At the same time the code jumps to loop?

If you set up the timer interrupt frequnecy too high, do you run the risk of having code in you loop functin not run at all? (If, for example, you have lots of code inside the loop()).

In that case, would it be wise to put code that you would generally put inside the loop(), inside a timer interrupt?


texts: Capacitive Moisture sensor only shows values 1 and 2

texts:
I'm new to Arduino and electronics in general. I'm trying to connect the Capacitive moisture sensor v1.2 to my arduino and get values in the serial plotter.
I connected the VCC to 5V, GRD to ground and AOUT to A0. However, I keep only getting values of 1, 2 or 3, while they are supposed to be in the hundreds. What could be a cause of such a problem. I'm using the chinese Wavgat board, but I have previously connected the moisture and humidity sensors and they displayed values normally.

Here's the code I used:

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

void loop() {
  val = analogRead(A0);
  Serial.println(val);
  delay(200);
}


texts: I want to control 2 dc motors using the arduino board directly. One motor must rotate clockwise and the other counter clockwise. The directions  doesn't change only the speed of each motors. Can this be done without any shield? Them motors may need a higher voltage than the arduino can provide. If I link the arduino board to a power source of about 15 V (the board is arduino mega limits between 6 and 20 ) and I use "analog.write()" function can I output more than 5 volts(the internal voltage)?


texts:
I am looking for a circuit where I would be able to use a common circuit for 3 phase 3 wire and 3 phase 4 wire. Is there any conversion IC available?
I have attached image for reference used in some model. is it possible to identify based on the label printed on it.


texts: Reproduce simulated temperature data with Arduino


texts: Sending values from Matlab to arduino using serial communication

texts:
I want to send numeric value from matlab to arduino but code is not working.

Matlab code is as:

doi = 3 ;
arduino=serial('COM5','BaudRate',9600); % create serial communication object
fopen(arduino); % initiate arduino communication
fprintf(arduino, '%s', char(doi)); % send answer variable content to arduino
fclose(arduino);

Arduino code is as:

  int solenoidPin = 13; //This is the output pin on the Arduino
int doi;

void setup()
{
  Serial.begin(9600);
  //pinMode(13, OUTPUT);
  pinMode(solenoidPin, OUTPUT); //Sets that pin as an output
}
void loop()
{

  if(Serial.available()>0)
  {

    doi = Serial.read();
    //Serial.println(doi);
    //Serial.println("\n");
    //doi = doi - 48;
   if (doi == 1)
   {
    //Serial.println(1);
    digitalWrite(solenoidPin, HIGH); //Switch Solenoid ON
    delay(1000); //Wait .15 Second
     digitalWrite(solenoidPin, LOW);
    }
  else if (doi == 2)
    {
     //Serial.println(2);
    digitalWrite(solenoidPin, HIGH); //Switch Solenoid OFF
    delay(2000); //Wait .165 Second
    digitalWrite(solenoidPin, LOW);
    }
  else
    {
      //Serial.println(3);
      digitalWrite(solenoidPin, HIGH); //Switch Solenoid OFF
      delay(3000); //Wait .180 Second
      digitalWrite(solenoidPin, LOW);
    }

  }
}

I used str2num(doi) also instead of fprintf(arduino, '%s', char(doi)) but no output.

Please give suggestion to correct this.

Thanks.


texts:
can somebody tell me what`s wrong with my code, i am using it to calculate rpm using incremental encoder

long counter=0;
 long  rpm = 0, z =0;
 long  ini_time = 0;
long  end_time=0;

void setup(){
  attachInterrupt(0, A_RISE, RISING);

  Serial.begin(115200);
}//setup

void loop(){

    Serial.println(rpm);
}

void A_RISE(){
  counter ++;
  if (counter == 1)
    ini_time = micros();
  else if (counter>470){ //470 is ticks per revolution
    z = counter;
    rpm_counter(z);

    counter =0;
  }
}

void rpm_counter(int x){

  end_time=micros()-ini_time;
  rpm=(60*10^6)/end_time;

}


texts: What is the name of this chip on Arduino Mega ? I am not finding its datasheet 56 TI MSP?


texts: Bluetooth module vs wireless module Arduino

texts:
My main question is, what is the main difference between HC-05 Bluetooth module and NRF24L0 wireless module?
Which should I buy?
Which makes these 2 modules different than each other?
Which one should I use in remote control arduino projects?
Which one is made for what purpose?


texts: RFM69HCW 915 MHz radio module: Sending a stream of int values rather than char[ ]

texts:
I'm trying to send a stream of int values (0-4096) from one arduino to another using an RFM69HCW module.

Here's my main code:

#include <RFM69.h>
#include <SPI.h>
#define NETWORKID     0   // Must be the same for all nodes
#define MYNODEID      1   // My node ID
#define TONODEID      2   // Destination node ID
#define FREQUENCY     RF69_915MHZ
#define ENCRYPT       true // Set to "true" to use encryption
#define ENCRYPTKEY    "TOPSECRETPASSWRD" // Use the same 16-byte key on all nodes
#define RFM69_CS      10
#define RFM69_IRQ     2
#define RFM69_IRQN    0  // Pin 2 is IRQ 0!
#define RFM69_RST     9
#define IS_RFM69HCW   true
#define USEACK        true // Request ACKs or not
#define LED           9 // LED positive pin
#define GND           8 // LED ground pin
#define PULSEPIN      0 // Heart Rate Monitor at pin A0

RFM69 radio = RFM69(RFM69_CS, RFM69_IRQ, IS_RFM69HCW, RFM69_IRQN);
String pulsearray;
bool recHR = true;
unsigned long oldtime = 0;
int interval = 5000;
static int readtime = 3000;
static int sampletime = 10; // 1000/this is the thing
static int txinterval = 1000; // delay between transmissions

void setup() {
  initSerial();
  initLed();
  initRadio();
}

void loop() {
  unsigned long newtime = millis();
  if (!recHR && newtime - oldtime >= interval) {
    recHR = true;
    oldtime = newtime;
    Serial.println("recording HR now");
  }

  while (recHR) {
    unsigned long newtime = millis();
    if (newtime - oldtime >= sampletime) {
      readhr();
    }
    if (newtime - oldtime >= readtime) {
      recHR = false;
      oldtime = newtime;
      Serial.println("stopped reading HR");
    }
  }
}

And the function I'm using:

void readhr() {
  for (int i = 0; i < 20; i++) {
    int pulse = analogRead(PULSEPIN);
    pulsearray = pulsearray + pulse;
    pulsearray = pulsearray + '\n';
    Serial.println(pulse);
  }
}

The library function sendWithRetry() requires the following arguments:

bool RFM69::sendWithRetry(uint8_t toAddress, const void* buffer, uint8_t bufferSize, uint8_t retries, uint8_t retryWaitTime)

I would like a way to set up a buffer which can be transmitted in multiple packets during the 5 second analogRead() downtime.
Using a string as my buffer doesn't work when I try to transmit the first n (<60) characters in the String. I've also tried using a char[ ] as my buffer (a lot more troublesome when storing int values) but it still gives the same error:

exit status 1
no matching function for call to 'RFM69::sendWithRetry(int, String&, unsigned int)'


texts: How can I calculate remaining battery life time with arduino

texts: I want to display a 3.7V battery's remaining life time on LCD screen using arduino. Like a laptop does. 1h 23m remaining or others. Do I need any kind of module to measure the thing? Can anyone tell the method please?


texts:
I have the Arduino MEGA and an adafruit touch screen 2.8 inches.

My goal is to draw a pixel given a specific RGB

I am using the ILI9341, GFX, and TFT.h libraries to draw and control the touch screen. I noticed the drawPixel function given, in which it takes in three parameters and draws the pixel:

tft.drawPixel(4,4,ILI9341_BLUE);

But, I am trying to draw a pixel with specific a RGB. So instead, the function would ideally need 5 parameters instead of 3, x, y, and then R, G, and B:

tft.idealDrawPixel(5,6,89,234,76);

I tried putting in a number as the third parameter and not ILI9341_COLOR, and the screen just prints blue:

tft.drawPixel(45,67,255);

Is there a function that allows me to draw RGB pixels specifically? Thanks for any help!


texts:
I am only replacing a portion of my code where I want to use the first method but as you can see it is making my sketch size little bigger

//if(iBPM >= 40 || iBPM <= 170 )
      {
      char iBPMwav[50];
      String thisString = String(iBPM);
      String stringThree =  "n" + thisString;
      stringThree =  stringThree + ".wav";
      stringThree.toCharArray(iBPMwav, 50);
      tmrpcm.play(iBPMwav);
      }

Sketch uses 29678 bytes (100%)

This is simple but at the end, I want to go from the number 40 up to 170, and this is why I want to use the first method.

//if(iBPM >= 40 || iBPM <= 170 )
  {
      if(iBPM == 71)
tmrpcm.play("n71.wav");
  else if(iBPM == 72)
tmrpcm.play("n72.wav");
  else if(iBPM == 73)
tmrpcm.play("n73.wav");
  else if(iBPM == 74)
tmrpcm.play("n74.wav");
  else if(iBPM == 75)
tmrpcm.play("n75.wav");
  else if(iBPM == 76)
tmrpcm.play("n76.wav");
  else if(iBPM == 77)
tmrpcm.play("n77.wav");
  else if(iBPM == 78)
tmrpcm.play("n78.wav");
  else if(iBPM == 79)
tmrpcm.play("n79.wav");
  else if(iBPM == 80)
tmrpcm.play("n80.wav");
  else if(iBPM == 81)
tmrpcm.play("n81.wav");
  else if(iBPM == 82)
tmrpcm.play("n82.wav");
  else if(iBPM == 83)
tmrpcm.play("n83.wav");
  else if(iBPM == 84)
tmrpcm.play("n84.wav");
  else if(iBPM == 85)
tmrpcm.play("n85.wav");
  else if(iBPM == 86)
tmrpcm.play("n86.wav");
  else if(iBPM == 87)
tmrpcm.play("n87.wav");
  else if(iBPM == 89)
tmrpcm.play("n89.wav");
  else if(iBPM == 90)
tmrpcm.play("n90.wav");
  else if(iBPM == 91)
tmrpcm.play("n91.wav");
  else if(iBPM == 92)
tmrpcm.play("n92.wav");
  else if(iBPM == 93)
tmrpcm.play("n93.wav");
  else if(iBPM == 94)
tmrpcm.play("n94.wav");
  else if(iBPM == 95)
tmrpcm.play("n95.wav");
  else if(iBPM == 96)
tmrpcm.play("n96.wav");
  else if(iBPM == 97)
tmrpcm.play("n97.wav");
  else if(iBPM == 98)
tmrpcm.play("n98.wav");
  else if(iBPM == 99)
tmrpcm.play("n99.wav");
  else if(iBPM == 100)
tmrpcm.play("n100.wav");
  else if(iBPM == 101)
tmrpcm.play("n101.wav");
  else if(iBPM == 102)
tmrpcm.play("n102.wav");
else
 tmrpcm.play("n170.wav");
}

Sketch uses 29024 bytes (101%)


texts: ACS712 Not working correctly with Arduino

texts:
So I have the basic setup ready with one relay that is controlling a 200W bulb. The Phase of this bulb is passed through a current sensor acs712. While running a simple analog read example sketch, I get output 511 from ADC, which is as expected. Then I subtracted this 511 from my measurement and observed the results while turning on/off the bulb.

int sensorValue;

void setup()
{
  Serial.begin(9600);  // sets the serial port to 9600
}

void loop()
{
  sensorValue = analogRead(0);       // read analog input pin 0
  Serial.println((511-sensorValue), DEC);  // prints the value read
  delay(100);                        // wait 100ms for next reading
}

Here is the output graph;

While the bulb is off, the current remains 0, but when I turn on the bulb, the voltage fluctuates over positive and negative side. Why is the sensor showing this behavior ?, I am not using any additional capacitor for noise reduction. Do I need to ? but I guess this is not noise. Is it ?


texts:
I'm trying to write web server code. However, I am having trouble with part of it.

Currently, to get it to save a bool variable I have it use a pin, as when I ran the code without it, after the page refreshes it resets the variable to its original value.

How do I get it to save the variable in this code without it using the pin?

digitalWrite (equalPin, server.arg("equal").toInt());
char equalText[80];
if(equalState) {
  strcpy(equalText, "priority is equal. Deactivate");
  equalState = false;
} else {
  strcpy(equalText, "priority is not equal. Activate");
  equalState = true;
}
equalState = digitalRead(equalPin);

I also have several over copies of this for different pages but if I change 1 of them they all change and reset after 10 seconds.

The code follows the example on this site.


texts: SPST switch - powered from pin output, or voltage regulator

texts:
I have a SPST switch and I just want to sense whether it's on or not. I will then turn on/off a relay depending on the state of this switch.

The two options I'm considering are: create a digital out on a pin going to one side of the switch, and read the digital in on another pin off the other side of the switch. Or put 5v from my voltage regulator to the switch, and read a digital in off the other side of the switch.

Would a resistor be necessary for the digital in pin with either of these options?


texts: I have one Arduino and I want to control a Servo motor and other devices. The Servo motor is further away from the Arduino so I want to control it wirelessly. The problem is that I want the Servo to communicate to the Arduino, which in turn communicates to me via wifi, text message, website, etc. I'm guessing I would need two esp8266 chips, one connected to the Servo and one connected to the Arduino. I would also like the other devices to communicate to be via wifi, text message, website as well which are connected to the arduino wired.


texts: expected primary-expression before '.' token

texts:
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); //

#include <SharpIR.h>

#define IR A0 // define Sharp IR signal pin
#define model 1080 // the model of the IR module

/*
 * GP2Y0A02YK0F --> "20150"
 GP2Y0A21YK --> "1080"
 GP2Y0A710K0F --> "100500"
  GP2YA41SK0F --> "430"
 */

void setup()
{
  lcd.begin(16,2);
  lcd.backlight();
}

void loop()
{

  //start of loop Robojax code for LCD with I2C
  lcd.print("Robojax IR Test");
  lcd.setCursor (0,1); // go to start of 2nd line
 int dis=SharpIR.distance();
 String distance = String(dis);
 distance ="Distance: "+distance+"cm";
 lcd.print(distance);
  //lcd.print(millis() / 1000);
  delay(500);
 //end of loopcode Robojax code for LCD with I2C
}