How to use ROHM LB202VL display (on BP-006LH-GC board) with Arduino? I got this 8-unit, 7-segment, 2-digit display board with 24 pins and I am wondering how I can interface with this from my Arduino Uno.

The board is labeled ROHM BP-006LH-GC and it has 8 units of the LB202VL LED display. Please see these photos of the board:

I found the datasheet for the LB202VL unit and I have been trying to make an independent unit on the board to work but I haven't been successful in setting its display.

The datasheet for the LB202VL unit can be found here: http://pdf.datasheetarchive.com/datasheetsmain/Datasheets-27/DSA-525461.pdf

Can anybody help me explain how I can work with this and set the display from my Arduino? After having attempted a few times I feel a little lost with this so any help would be greatly appreciated!

I have a similar display, and I found the wiring by inspection and trial and error:

The display consist of 8 pairs of digits (LB-202VL, common cathode).

If contact points are numbered from 1 to 24 from left to right then
the common cathodes for the digits D1-D16 and the segments D.P. and 'a' - 'g' are noted below.
If you i.e. connect 1 to GND and 7 to + then segment 'c' of the first digit will be on. You have to multiplex the digits in order to use it.

D1
D2
D3
D4
D.P.
D5
c
D6
e
D7
a
D8
g
D9
d
D10
f
D11
b
D12
D13
D14
D15
D16


You are using a char pointer (char*) instead of a char.

When you say;

response[idxUpd]  = assign;

you are assigning not the value but a pointer to that value. That points to assign for every element in response[]. Every response[] get the same pointer value, every response[] get the same value.

Use this:

#define RespLength 10
int response[] = {0,0,0,0,0,0,0,0,0,0};
int idxUpd  = 0;

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

void loop() {
  // put your main code here, to run repeatedly:
    int wkt = random(10, 99);
    response[idxUpd]  = wkt;

    Serial.print("Iteration "); Serial.print(idxUpd); Serial.print(" : ");
    for (int i=0;i<RespLength;i++){
        Serial.print(response[i] );Serial.print(",");
    }
    Serial.println();
    delay(500);

    idxUpd++;
    idxUpd = idxUpd >= 10 ? 0 : idxUpd;
}

I don't understand why you are converting a int to a float. That value doesn't change, so I omitted the dtostr() call.


USB D+ D- to Arduino Mega RX TX Is it possible to directly communicate USB D+ D- to Arduino Mega serial port TX RX?

No, D+/- are high frequency USB signals. TX/RX is 5V UART protocol, i.e. compeletely different. But you can e.g. use AT90USB128x processor to avoid 16u2 bridge. The prosessor is not so mighty as 2560 but it's cheaper and simplifies design.


Why does my stepper motor run when I open the Serial port? For some reason my motor moves a certain amount every time I open the serial port without giving it any other instructions. It will move further by the same amount if I close and reopen the serial port. Please could someone tell me how to avoid this? I haven't had this problem before.
I am using two stepper motors with a A4988 driver each.
Here is my code so far
#include <AccelStepper.h>
#include <MultiStepper.h>

// Define pin connections
const int dirPin1 = 2;
const int stepPin1 = 3;
const int dirPin2 = 4;
const int stepPin2 = 5;

String incomingByte; // for incoming serial data

// Define motor interface type
#define motorInterfaceType 1

// Creates an instance
AccelStepper stepper1(motorInterfaceType, stepPin1, dirPin1);
AccelStepper stepper2(motorInterfaceType, stepPin2, dirPin2);

MultiStepper steppers;

void setup() {
  Serial.begin(9600);
  String excess1 = Serial.readString();
  // Configure each stepper
  stepper1.setCurrentPosition(0);
  stepper2.setCurrentPosition(0);
  stepper1.setMaxSpeed(100);
  stepper2.setMaxSpeed(100);
  stepper1.setAcceleration(10);
  stepper2.setAcceleration(10);
  // Then give them to MultiStepper to manage
  steppers.addStepper(stepper1);
  steppers.addStepper(stepper2);
}

void loop() {
  // send data only when you receive data:
  if (Serial.available() > 0) {
    // read the incoming byte:
    incomingByte = Serial.readString();

    // say what you got:
    Serial.print("I received: ");
    //Serial.println(incomingByte, DEC);
    Serial.println(incomingByte);

    int x = incomingByte.toInt();

    long positions[2];

    positions[0] = x;
    positions[1] = 0;
    steppers.moveTo(positions);
    steppers.runSpeedToPosition();
  }
}

When you open or reopen the Serial port, the Arduino resets (depending on how you open it; some programs don't send the signal on DTR or RTS, which result in the reset).
My guess is, that the stepper driver reacts to the Arduino configuring its pins for the stepper. Difficult to say, what exactly happens there. To mitigate that, you can add an external pulldown resistor (assuming you have an active high stepper driver. For active low use a pullup resistor). That should keep the step line of the driver low even when its not actively driven by the Arduino.


C# and Arduino problem with serial port I would like to establish a communication between my C# program and my Arduino Duemilanove. I tried lot of different tutorials, but none of them were the same, and I'm a little bit confused.

Actually my code is:

C#

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace InterfaceArduinoWindowsFOrm {
  public partial class Form1 : Form {
    public Form1() {
      InitializeComponent();
      serialPort1.PortName = "COM3";
      serialPort1.BaudRate = 9600;
      serialPort1.Open();
    }

    private void pictureBox1_Click(object sender, EventArgs e) {
    }

    private void tabPage2_Click(object sender, EventArgs e) {
    }

    private void listBox1_SelectedIndexChanged(object sender, EventArgs e) {
    }

    private void toolTip1_Popup(object sender, PopupEventArgs e) {
    }

    private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e) {
      Console.WriteLine("test");
    }

    private void button1_Click_1(object sender, EventArgs e) {
      serialPort1.Write("5");
      Console.WriteLine(serialPort1.IsOpen);
    }
  }
}

Arduino:

/* Sweep
  by BARRAGAN <http://barraganstudio.com>
  This example code is in the public domain.
  modified 8 Nov 2013
  by Scott Fitzgerald
  http://arduino.cc/en/Tutorial/Sweep
*/

#include <Servo.h>

Servo myservo;  // Create servo object to control a servo.
// Twelve servo objects can be created on most boards.
int pos = 0;
int message = 0; // This will hold one byte of the serial message
                 // variable to store the servo position.

void setup() {
  Serial.begin(9600);
  myservo.attach(9);  // Attaches the servo on pin 9 to the servo object
}

void loop() {
  if (Serial.available()) {

    // Check to see if there is a new message
    message = Serial.read();

    // Put the serial input into the message
    Serial.print(message);

    if (message == '5') {
      Serial.print("test");
      for(pos = 0; pos <= 180; pos += 1) {
        // Goes from 0 degrees to 180 degrees
        // in steps of 1 degree

        myservo.write(pos);
        // Tell servo to go to position in variable 'pos'

        delay(15);
        // Waits 15 ms for the servo to reach the position
      }

      for(pos = 180; pos>=0; pos-=1) {
        // Goes from 180 degrees to 0 degrees

        myservo.write(pos);
        // Tell servo to go to position in variable 'pos'

        delay(15);
        // Waits 15 ms for the servo to reach the position
      }
    }
  }
}

The problem is, when I click my button, nothing happens, but obviously if I remove the if statement, the servo motor code works.

Since you are sending from the Arduino the received serial data back to the C# application (Serial.print(message);), I would advise to check what you receive on the C# side.
Register to the DataReceived event of the SerialPort as so:

serialPort1.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

And add an event handler:

private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
    SerialPort port = (SerialPort)sender;
    string data= port.ReadExisting();
    // check here what data you received, if any
}

This way you could confirm that the Arduino gets the data properly from the C# side to begin with. Next step would be to understand if this if statement treats the data properly:

if (message == '5')

But starting from examination of what you get from the C# side will help you decide where exactly is the problem.


Software serial conflict with WiFi on ESP8266 I'm trying to use an ESP8266 (Wemos D1 mini) to read from a 19.2K serial port and report the results over WiFi. Programming is via Arduino IDE. The code to read the port works just fine if WiFi is not enabled. Once WiFi is enabled I lose chars from the input stream. I've seen several posts in various places that point to problems with using SoftwareSerial and WiFi at the same time, apparently having to do with timing conflicts. My latest attempt calls

WiFi.disconnect();

before the code that reads the chars from the serial stream, then calls

WiFi.reconnect();

after reading the serial stream but before making the calls to send data over the web. This did not work.

My code is reading from the serial port in a (blocking) loop, which other posts suggest is the problem. This is not a problem when there is no WiFi object connection. I could restructure the code to create a non-blocking read, but that would be a significant effort (and make the code much harder to understand), so before I go that route I'm wondering if there is a different solution.

As noted, there are conflicts between Wifi and SoftwareSerial. The attempt in the question to disconnect WiFi is a step in the right direction, but not enough. You have to actually turn off the WiFi. The challenge is to reliably shut down the WiFi and then start it up again. This has been discussed extensively in the ESP8266/Arduino Git repository here and is referred to by some as "Issue 644".  An sample implementation of the code to reliably is presented here.

Here's what the on/off functions look like. I strongly urge you to go to the code linked above and copy from there rather than here, though.

extern "C" {
#include "user_interface.h"
#define WIFI_RETRIES 25

int conn_tries = 0;
bool WiFiOff() {
    WiFi.disconnect();
    WiFi.mode(WIFI_OFF);
    WiFi.forceSleepBegin();
    yield();

    /*
     * It can take a while for the ESP to disconnect, so we need
     * to give it a couple of seconds before returning a fail.
     */
    while ((WiFi.status() == WL_CONNECTED)
           && (conn_tries++ < WIFI_RETRIES)) {
        delay(100);
#ifdef DEBUG
        Serial.print(".");
#endif
    }
    if (WiFi.status() != WL_CONNECTED)
        return (true);
    else
        return (false);
}

/*
 * Turn the WiFi back on again with forceSleepWake().
 * NOTE:-  =Your= SSID and password must be in the
 *         user_config.h file.
 */
bool WiFiOn() {
    conn_tries = 0;

    WiFi.forceSleepWake();
    WiFi.mode(WIFI_STA);
    wifi_station_connect();
    WiFi.begin("corazon_del_bosque", "");

    /*
     * It may take a while for the ESP to re-connect, depending
     * upon external factors (e:- has the access-point moved out
     * of range since we were last connected?).  This loop will
     * give us a reasonable time to re-connect without blocking
     * permanently.
     */
    while ((WiFi.status() != WL_CONNECTED)
           && (conn_tries++ < WIFI_RETRIES)) {
        delay(100);
#ifdef DEBUG
        Serial.print(".");
#endif
    }
    if (WiFi.status() == WL_CONNECTED)
        return (true);
    else
        return (false);
}

I'm using this code in my program via the Arduino IDE. The author used it in PlatformIO. Other build systems may have other requirements.


How do I write and read internal EEPROM? I am working on an Arduino Mega 2560. I want to read and write the internal EEPROM.

Can I use EEPROM.get()/EEPROM.put()?

I want to store 3 things in EEPROM:

Boolean status.
String password: length 5 digits.
String Mobile number: length 10 digits.

Avoid the 'String' object, use a character array of fixed length. You might want to add one extra byte for the zero-terminator. Put everything in a 'struct' and then you can use the EEPROM.get() and EEPROM.put() to read and write the complete struct. I prefer a struct to keep the data from EEPROM together. That makes it easier to add a checksum and a version number for the data. When something is wrong with the data from EEPROM then default values could be used.

Instead of a struct, you can also read and write the seperate items. The EEPROM.get() and EEPROM.put() should be able to use a character array of fixed length.


How can I made my Arduino follow the time exactly? I am making an Arduino clock. You can set time to it, and then it keeps on going. The problem is that it is always within a minute off. It is not a major issue, but one that I would like to fix. I use the millis function. The program checks if millis is evenly divisible by 60,000(1 minute). After I set the time, millis is NOT at 0, meaning that is ahead of what I set by a number of seconds. How can I fix this? Code:

#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int hours=0;
int minutes=0;
const int modePin=6; //button
int prevModeState=HIGH; //prev state of button
unsigned long timer;
int modeState;//current state
int mode=0;//mode of alarm
int buttonCounter=0;
const int incrementPin=9;
const int switchPin=7;
int incrementState;
int switchState;
int prevIncrementState=HIGH;
int prevSwitchState=HIGH;
int switching=0;

void setup() {
lcd.begin(16, 2);
lcd.setCursor(6, 0);
lcd.print("Time:");
lcd.setCursor(6, 1);
lcd.print("00:00");
pinMode(modePin, INPUT_PULLUP);
pinMode(incrementPin, INPUT_PULLUP);
pinMode(switchPin, INPUT_PULLUP);
}

void loop() {
modeState=digitalRead(modePin);
if(prevModeState!=modeState){
      prevModeState=modeState;
   if(modeState==LOW){
    buttonCounter++;
  if(buttonCounter%2==0){
    mode=0;
    lcd.clear();
    lcd.setCursor(6, 0);
    lcd.print("Time:");
    writeTime();
}
  else{
    mode=1;
    switching=0;
    lcd.clear();
    lcd.setCursor(4, 0);
    lcd.print("Set Time:");
}

   }
  }
if(mode==0){
  timer=millis();
  if(timer%60000==0){
     minutes++;
    writeTime();
    }
}
else if(mode==1){
 incrementState=digitalRead(incrementPin);
  switchState=digitalRead(switchPin);
  if(prevSwitchState!=switchState){
    prevSwitchState=switchState;
    if(switchState==LOW){
    switching++;
    }
    if(switching==4){
      switching=0;
    }

    }

  if(prevIncrementState!=incrementState){
    prevIncrementState=incrementState;
    if(incrementState==LOW){
      if(switching==0){
        if(hours<14){
        hours+=10;
        }
        else if((hours>=14)&&(hours<20)){
        hours-=10;
        }
        else{
          hours-=20;
        }
        }

        else if(switching==1){
          if((hours==9)||(hours==19)){
            hours-=9;
          }
          else if(hours==23){
            hours-=3;
          }
          else{
          hours++;
          }
        }

        else if(switching==2){
          if(minutes<50){
             minutes+=10;
          }
          else{
            minutes-=50;
          }

        }
        else if(switching==3){
          if(minutes%10==9){
            minutes-=9;
          }
          else{
          minutes++;
          }
        }

    }

  }

  writeTime();
}
}

void writeTime(){
  lcd.setCursor(6, 1);
   if(minutes>=60){
        minutes=0;
        hours++;
        }
     if(hours>=24){
        hours=0;
     }
if(minutes<10){

      if(hours<10){
        lcd.print(String("0")+hours+":"+"0"+minutes);
      }
      else{
        lcd.print(hours+String(":")+"0"+minutes);
      }
    }
    else{
      if(hours<10){
         lcd.print(String("0")+hours+":"+minutes);
      }
      else{
         lcd.print(hours+String(":")+minutes);//possibly split if problems arise
      }

    }
}

Three things you can do - any combination of these is good, but the more the better:

Use an RTC module to keep more accurate track of the time.
Connect the Arduino to the internet and use NTP to get the exact time.
Use the time provided by GPS.

The RTC chip can keep track of time when there is no external power, using just a very small button cell.
The GPS and internet time are both very accurate.

Using either or both of those sources to set and maintain the correct time in the RTC chip is the best and most accurate way of keeping the right time on the Arduino.

To increase the accuracy of your existing method you should count seconds, not minutes.

Start by recording the current millis. When 1000 of them have passed you can increase your seconds.  Don't rely on millis() % 1000 since you may miss it whilst doing other things. Also don't rely on your millisecond counter check executing at exactly 1000ms intervals - work on the principle of "at least 1000ms" and move the next check to 1000ms from where it should have happened, not where it did happen.  This can help to combat some clock drift.

static unsigned long mscount = millis();

if (millis() - mscount >= 1000) {
    mscount += 1000;
    seconds ++;
}

Then every 60 seconds you can increase your minutes:

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


Connect to Arduino 2560 using a RS232 Connection Is it possible to connect to an Arduino 2560 using a RS232 (DB9) connection rather than the regular connection using USB cable?

I am thinking of this connection scheme:

PC -> USB cable -> USB to RS232 Multiplexer -> DB9 Cable -> Adapter board -> Arduino 2560

Yes, perfectly possible.  You need an RS-232 interface chip - the most common and well-known of these is the MAX232. You can get them as breakouts on eBay.

That interfaces between the DB9 and pins 0/1 (or other UART comms pins) on the Arduino.

If you are wanting to program the board through it you will also need to connect (after converting the voltage through the MAX232) the DTR line to RESET through a 100nF capacitor.

... Exactly like you would with a breadboard Arduino.


Couldn't connect to local server using Ethernet Shield and Arduino Mega 2560 I'm trying to connect the arduino mega and ethernet shield and try to send some data to a php script. I have connect the ethernet shield to the laptop. Lap is connected to router through wi-fi. Any help in advance please.

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

/******************** ETHERNET SETTINGS ********************/

byte mac[] = { 0x90, 0xA2, 0xDA, 0x0D, 0x85, 0xD9 };   //physical mac address
byte ip[] = { 192, 168, 1, 5 };                   // ip in lan
byte subnet[] = { 255, 255, 255, 0 };              //subnet mask
byte gateway[] = { 192, 168, 0, 1 };              // default gateway

IPAddress server(192,168,1,2);
EthernetClient client;

void setup() {
    Serial.begin(9600);  // Initialize serial communications with the PC
    while (!Serial);     // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4)
    Ethernet.begin(mac,ip,gateway,subnet);     // initialize Ethernet device
    Serial.print("My IP address: ");
    for (byte thisByte = 0; thisByte < 4; thisByte++) {
      Serial.print(Ethernet.localIP()[thisByte], DEC);
      Serial.print(".");
    }
    Serial.println();
    Serial.println("connecting....");
}

void loop()
{
  if (client.connect(server,1234)) { // REPLACE WITH YOUR SERVER ADDRESS
    Serial.println("Server connection OK");
    client.println("GET /add.php?temp1=10&hum1=20 HTTP/1.1");
    client.println("Host:" + server);// SERVER ADDRESS HERE TOO
    client.println("Content-Type: text/plain");
  } else {
    Serial.println("connection failure");
  }

  if (client.connected()) {
    client.stop();// DISCONNECT FROM THE SERVER
    Serial.println("disconnected");
  }

  delay(5000); // WAIT FIVE MINUTES BEFORE SENDING AGAIN
}

Serial Out Put

My IP address: 192.168.1.5.
connecting....
connection failure
connection failure
connection failure
connection failure
connection failure
connection failure
connection failure

I had this problem for quite a long time and then I did a little bit of research!
Here it is in an easy explanation-

When you connect your Ethernet Shield to the Laptop the laptop takes the Ethernet Shield as a source of internet and tries to get an IP Address and other network stuff FROM the shield! BUT what we want is the other way round.

We want the Ethernet shield to take the laptop as a source of internet and get itself an IP assigned by the laptop!

What I do is I make a Laptop-Ethernet Shield network and a Laptop-WiFi network.(Simply means that I connect my laptop to WiFi and Ethernet shield)

Then I JOIN the two networks!

This joining of networks is called network bridging and is done easily, I'll tell you how-

If you're using linux then follow this link here.

else if you're running windows-

1) Connect your Ethernet Shield (With Arduino attached obviously) to the laptop and make sure that your laptop is connected to the WiFi.

2) Go to Network and Sharing Center.

3) Go to Change adapter settings.

4) Select your Wifi adapter and the Ethernet adapter together.

5) Right click on any of the selected adapter and click Bridge connections.

6) Wait till a new network bridge is connected and is done verifying after it's creation.

7) Upload the sketch again on Arduino and you'd be connected.

NOTE

DHCP may not always work as it's a feature of your router/WiFi and not your laptop so try assigning a mannual IP by calling Ethernet.begin(mac,ip) instead of using DHCP by caling Ethernet.begin(mc);

AND do change your ip to 192.168.1.XXX I mean change the last tuple so it does not clash with the ip of any other device.(XXX any number less than 255, generally 100-200)

Do let me know the outcome after trying this out! :D


What will happen if I supply greater than 1.1V to analogue inputs if analogReference set to INTERNAL? I am reading a 50Hz AC voltage using the analogue inputs.

If I set the analogReference() to INTERNAL, meaning 1.1V on the Arduino Uno, what will happen if a voltage greater than 1.1V is supplied to the pin? Will the board be damaged? If not, what value will the ADC give?

You will read 1023.

The limit of the voltage is not the reference voltage but the chip supply voltage - so 5v on a 5v board.


Arduino Uno data logger shield recording nonsense time I'm using an Arduino Uno with the Adafruit Data Logger Shield powered by a Voltaic 5V 2A battery pack. When writing to an SD card, the time stamp never changes (always reports the same now.unixtime). However, when powered from a laptop, the time stamp is correct and everything seems to be working.

The input voltage from the battery is confirmed to be just over 5V and not substantially lower the the laptop usb port.

Has anyone seen this before? Any ideas?

Where are you brining the power onto the Arduino board? If you bring it in through the external power connector you need to account for the voltage needed to run the regulator. You might be running into problems with low voltage and some part of your system that is sensitive to it.

You could try bring the power in on the 5 V pin, but then you are taking responsibility for the quality of the power supply.


Budgeting Power for 5V Arduino Pro Mini In my low power project, I'm using a Arduino Pro Mini (5V, 16 MHz, ATMEGA328) and a low wattage 3W power supply. Everything else on the system other than the Arduino uses a max of 1.98W.

How much power should I budget for the Arduino Pro Mini (without any mods, ie: disconnecting the voltage regulator and LED)?

Arduino mini, and atmega328 in general use less than 10mA with default arduino code. Turning down unused component (ADC and so on), using deep sleep and optimizing pbc would lover this consumption a lot, in the land of uA


My code is not uploading to Arduino Uno, Please help! I am very new to arduino, so new that it is my first board. I keep running into this error
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00

I have searched the internet for hours, tried solutions from almost every StackExchange question related to this topic, and even Reddit posts but none of those have been able to help me. All my settings are as they are supposed to be. Both the correct board and serial port are selected but it still keeps giving me this error:
System wide configuration file is "/home/rahat/Desktop/Arduino/arduino-1.8.13/hardware/tools/avr/etc/avrdude.conf"
User configuration file is "/home/rahat/.avrduderc"
User configuration file does not exist or is not a regular file, skipping
   ` Using Port                    : /dev/ttyS4
     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=0x00
Also my operating system is Ubuntu 20.04 LTS

First of all find out on which port the Arduino is connected by running the command : dmesg | grep tty. You should get [82893.921017] usb 1-1: cp210x converter now attached to ttyXXX with the ttyXXX COM port.
Then check if the port is visible Tools->Port. If the port is not visible then you have a permission issue.


Arduino MKR GSM 1400 SSL client example fails to connect I am using the GsmSSLWebClient example which comes with the MKRGSM library.
The original example works just fine, I get the arduino ascii logo. But when I change the URL the arduino doesn't get any answer:

//char server[] = "arduino.cc";
//char path[] = "/asciilogo.txt";
char server[] = "wepardi.fi";
char path[] = "/robots.txt";

Starting Arduino web client.
connecting...
connected
GET /robots.txt HTTP/1.1
Host: wepardi.fi
Connection: close

disconnecting.

From Firefox https://www.wepardi.fi/robots.txt is displayed correctly.
I tried also some other sites, and from some of them I get the ascii file content correctly, and from some others not.

Something wrong with my settings?

Prints from debug mode:

connecting...

...

AT+USECMNG=0,0,"VeriSign_Class_3_Public_Primary_Certification_Authority_G5",1239
>
+USECMNG: 0,0,"VeriSign_Class_3_Public_Primary_Certification_Authority_G5","cb17e431673ee209fe455793f30afa1c"

OK
AT+USOCR=6

+USOCR: 0

OK
AT+USOSEC=0,1,0

OK
AT+USECPRF=0,0,1,4,"www.wepardi.fi"

OK
AT+USOCO=0,"www.wepardi.fi",443

ERROR

+UUSOCL: 0
AT+USOCL=0

ERROR
connected
GET /robots.txt HTTP/1.1
Host: www.wepardi.fi
Connection: close

disconnecting.

Command
    AT+USOCO=0,"www.wepardi.fi",443
fails

GsmWebClient (no SSL) example works fine with any hosts I have tried.

I finally found a solution to this problem. Disabling certificate validation in MKRGSM library makes the SSL connection succeed also to this site. In MKRGSM/src/GSMClient.cpp I changed

//     MODEM.sendf("AT+USECPRF=0,0,1,4,\"%s\"", _host);
       MODEM.sendf("AT+USECPRF=0");

to use modem factory settings. I still don't know what was the problem with the certificates.
Thanks to everyone who tried to help with this.


ESP32 start BLE after deep sleep I'm new to using the esp32 as a microcontroller. I'm currently working on a so-to-say remote control. Since I want to use the esp32 with an external battery I need to put it in deep-sleep after I pressed some buttons to preserve battery.
All that works fine I've connected a small touchpad to put the esp32 into deep sleep mode using the esp_deep_sleep_start() function . The controller itself goes to sleep and can be woken up using the following 2 lines:
  touchAttachInterrupt(T0, wakeCallback, TOUCH_THRESHOLD);
  esp_sleep_enable_touchpad_wakeup();

In order to communicate with my Raspberry Pi 'Base Station' I decided to use BLE.
My server is configured the following way (where bleServer, bleCharacteristic and bleService are global variables):
  BLEDevice::init("esp-32-remote");
  bleServer = BLEDevice::createServer();
  bleServer->setCallbacks(new ServerCallbacks());

  bleService = bleServer->createService(SERVICE_UUID);
  bleCharacteristic = bleService->createCharacteristic(
                        CHARACTERISTIC_UUID,
                        BLECharacteristic::PROPERTY_READ |
                        BLECharacteristic::PROPERTY_WRITE
                      );

  bleCharacteristic->addDescriptor(new BLE2902());
  bleService->start();

  BLEAdvertising *pAdvertising = BLEDevice::getAdvertising();
  pAdvertising->addServiceUUID(SERVICE_UUID);
  pAdvertising->setScanResponse(true);
  pAdvertising->setMinPreferred(0x06);
  pAdvertising->setMinPreferred(0x12);
  BLEDevice::startAdvertising();

Upon regular restart using the buttons everything works fine. I can connect to the device using python and the bluepy library.
If I now wake the controller I can't do anything anymore. The setup() function gets called and there are no errors, nor does the controller crash due to any code errors (seemingly).
Then the loop function gets called once, and thats it. I can't connect to the device anymore until I press the hardware reset button.
The questions that arise are:

might there be some error in the way I shutdown the bluetooth module?
Does the loop function work after being woken up from deep sleep?

Maybe one of you has an idea regarding my issue. If there are more information that I need to provide, don't hesitate to tell me, I'm new to the whole mcu topic and I don't know whats best to provide here.

Does the loop function work after being woken up from deep sleep? YES
loop function isn't magical.  its just a function that gets called over and over.  In other words, if it gets called once, it can be called again except if

it did something to deactivate itself
never reached the end

during that first call.  Check that you are not activating some sort of state inside the loop or going into a blocking call awaiting a signal that is never sent.
For good measure, make sure to reset all your variables to their expected states - expecting something to be 0 or set via the original definition may be insufficient.  This is something that occurs on a power reset so if reset is making it work again, thats a likely culprit.  Use a bare minimum of code in the loop for debug so you can figure it out.


Arduino Uno with SD, Cardinfo sketch how to list only visible files There are two files (that can be seen on my computer) on my sd card, 6.bmp and example.txt (the latter written from my arduino). I have them connected to my arduino via LCSTUDIO breakout board (which surprisingly caused me no trouble at all).

When I run the example "cardinfo" sketch, the files it lists includes those two files along with tons of others, which I assume are just invisible from a personal computer.

How would I list only the files that can be seen from my computer (i.e. aren't inside any directory, but are just plain in the SD card)?

Using arduino UNO

Simple Answer: Don't think you can

Long Answer: Dont think you can, because, unlike an OS like windows, mac, linux, etc. The arduino just tales all the files. You could save those two files and format it as FAT16 though, then add the 2 files back on the sd and there you go.


Mini ethernet shield pins don't have SI Please somebody who had the same issue help me.
The question is how to connect this Mini Ethernet shield to an Arduino.
The main problem is the pins that my shield have or haven't; my current connections to the Arduino Mega 2560 are:

5v to 5v
GND to GND
LNT to NULL
CLK to NULL
SO  to pin50
WOL to NULL
SLK to PIN52
ST  to ????
RST to RST
CS to PIN53
Q3 to NULL
GND to NULL

But in all cases when I search the connection diagram every picture has SI, but I don't have it (I tried to connect ST to PIN51 without luck).

What kind of Ethernet shield is that? Or how to connect those pins?

I hope someone can help me; thank you in advance.

/*
  DHCP-based IP printer

  This sketch uses the DHCP extensions to the Ethernet library
  to get an IP address via DHCP and print the address obtained.
  using an Arduino Wiznet Ethernet shield.

  Circuit:
   Ethernet shield attached to pins 10, 11, 12, 13

  created 12 April 2011
  modified 9 Apr 2012
  by Tom Igoe
  modified 02 Sept 2015
  by Arturo Guadalupi

 */

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

// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = {
  0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02
};

void setup() {
  // You can use Ethernet.init(pin) to configure the CS pin
   // Ethernet.init(53);  // Most Arduino shields
  //Ethernet.init(5);   // MKR ETH shield
  //Ethernet.init(0);   // Teensy 2.0
  //Ethernet.init(20);  // Teensy++ 2.0
  //Ethernet.init(15);  // ESP8266 with Adafruit Featherwing Ethernet
  //Ethernet.init(33);  // ESP32 with Adafruit Featherwing Ethernet

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

  // start the Ethernet connection:
  Serial.println("Initialize Ethernet with DHCP:");
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    if (Ethernet.hardwareStatus() == EthernetNoHardware) {
      Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
    } else if (Ethernet.linkStatus() == LinkOFF) {
      Serial.println("Ethernet cable is not connected.");
    }
    // no point in carrying on, so do nothing forevermore:
    while (true) {
      delay(1);
    }
  }
  // print your local IP address:
  Serial.print("My IP address: ");
  Serial.println(Ethernet.localIP());
}

void loop() {
  switch (Ethernet.maintain()) {
    case 1:
      //renewed fail
      Serial.println("Error: renewed fail");
      break;

    case 2:
      //renewed success
      Serial.println("Renewed success");
      //print your local IP address:
      Serial.print("My IP address: ");
      Serial.println(Ethernet.localIP());
      break;

    case 3:
      //rebind fail
      Serial.println("Error: rebind fail");
      break;

    case 4:
      //rebind success
      Serial.println("Rebind success");
      //print your local IP address:
      Serial.print("My IP address: ");
      Serial.println(Ethernet.localIP());
      break;

    default:
      //nothing happened
      break;
  }
}

And result is :

16:41:14.242 -> Initialize Ethernet with DHCP:
16:41:14.804 ->    Failed to configure Ethernet using DHCP
16:41:14.848 -> Ethernet    shield was not found.  Sorry, can't run
without hardware. :(

The "Mini Ethernet Shield" uses ENC26j60 chip. The Arduino Ethernet library is for Wiznet W5100/W5200/W5500 chips. You can't use it with ENC26j80.

With Arduino Mega I would recommend to use the UIPthernet library for ENC26j80. Other option is the EtherCard library.

The UIPEthernet library has the same API as the the Arduino Ethernet library.


CH340G and CP2102 devices not recognized with Thinkpad L380 I have three different devices, none of them gets recognized on my new Thinkpad L380 running Windows 10:

Arduino Nano Clone with CH340G chip (USB2Serial)
NodeMCU (Lolin V3) with CH 340G chip (USB2Serial)
NodeMCU (ESP-WROOM-32) with CP2102 chip (USB2UART)

All three of them are recognized properly both on my desktop computer running Windows 10 (on USB 2.0 ports) as well as on my other laptop (Acer Switch Alpha 12, Win10, USB 3.0 port).

But even after hours of trying I was not able to connect those devices to my Thinkpad.
Things I've tried so far:

Of course, simply installing the Arduino IDE and try plug'n'play
Downloading and installing the CH340G driver from the official website
Disabling Secure Boot, enabling testsigning mode and reinstalling the CH340G driver
For the CP2102 device I only tried installing the driver under "normal" Windows (e.g. no testsigning enabled) since it also worked that way on my desktop computer

I have to admit that it's been a while since I set up the drivers on my other laptop and desktop computer, but I cannot remember that there was anything unusual I had to do back then.

Does anybody else know about problems regarding Thinkpad laptops? At first I thought USB 3.0 might be the problem, but the Acer laptop works just fine with the USB 3.0 port.

Update

Somehow the laptop now at least recognizes the Arduino Nano clone in the device manager and I can choose the COM port in the Arduino IDE. I can't tell what made the difference. All I did was to plug in a dongle for a wireless mouse in the USB ports to verify that they are working with "normal" devices and afterwards the Nano was recognized at least with a yellow "!" in the device manager. I then was able to uninstall the CH340 drivers and reinstall them. The device manager now displays the Nano as correctly installed.

But uploading a sketch fails. It outputs the errors:

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x0a
avrdude: ser_send(): write error: sorry no info avail
avrdude: ser_recv(): read error: Access denied

The RX LED is faintly blinking in red at the beginning of the process, then the upload seems to get stuck until the error messages are displayed.

The NodeMCU Lolin V3 with the same CH340 chip is still not recognized, though.

Serial communication (with the Serial monitor of the Arduino IDE) is now possible. I uploaded the "ASCIITable" example using my Desktop PC, connected the Arduino to the ThinkPad and could successfully read the output over the serial interface.

I recently bought a cheap USB 2.o hub.
Turns out that the CH340G devices are recognised if I plug them in the hub rather than in the laptop directly. Maybe this helps somebody else who is searching for a solution, even though I can't explain why the hub is making a difference.


Counting to 1000 In Both cores execution time problem in esp32? I am trying to count to 1000 with single core and dual core with esp32 but the output(run time) dose not make sense, the time which takes a single core should be doubled compared to dual core in theory right?
Here is the code
TaskHandle_t Task1;
TaskHandle_t Task2;
SemaphoreHandle_t baton;

int i = 0;
long l;

void setup() {

  Serial.begin(115200);
  pinMode(2, OUTPUT);
  pinMode(4, OUTPUT);

  baton = xSemaphoreCreateMutex();
  l = millis();
  xTaskCreatePinnedToCore(
    Task1code, /* Function to implement the task */
    "Task1", /* Name of the task */
    10000,  /* Stack size in words */
    NULL,  /* Task input parameter */
    1,  /* Priority of the task */
    &Task1,  /* Task handle. */
    0); /* Core where the task should run */

//single core or dual core execution

//  xTaskCreatePinnedToCore(
//    Task2code, /* Function to implement the task */
//    "Task2", /* Name of the task */
//    10000,  /* Stack size in words */
//    NULL,  /* Task input parameter */
//    1,  /* Priority of the task */
//    &Task2,  /* Task handle. */
//    1); /* Core where the task should run */

}
void Task1code( void * parameter) {
  while (true) {
    xSemaphoreTake(baton, portMAX_DELAY);
    xSemaphoreGive(baton);
    delay(1);// I don't understand in here without this command output result is worse
    i++;
    if (i == 1000) {
      l = millis()-1;
      Serial.print("Done ");
      Serial.print(xPortGetCoreID());
      Serial.print(" ");
      Serial.println(l);

    }if(i>1000){
      vTaskDelete(Task1);
    }
  }
}
void Task2code( void * parameter) {
  while (true) {
    xSemaphoreTake(baton, portMAX_DELAY);
    xSemaphoreGive(baton);
    delay(1);// I don't understand in here without this command output result is worse
    i++;
    if (i == 1000) {
      l = millis()-1;
      Serial.print("Done ");
      Serial.print(xPortGetCoreID());
      Serial.print(" ");
      Serial.println(l);
    }if(i>1000){
      vTaskDelete(Task2);
    }
  }
}
void loop() {

}

The output I get for runtime
Single core :- 1033 ms
Dual core :- 701 ms

Without delay(1); command the result is even more obvious
Single core :- 39 ms
Dual core :- 40 ms

How can I make my algorithm show that single core takes twice time as dual core execution time I wan't both cores to work parallel not one after the other.

Your must use the semaphore to protect the read/write access to i
(Only one task is allowed to modify the variable at a time)
xSemaphoreTake(baton, portMAX_DELAY);
i = i + 1;
xSemaphoreGive(baton);

Additionally you should combine your if clauses. If both tasks increment iit could happen, that it will never has the value 1000for the second task.


Communicating Via Serial1 on Arduino Mega Apologies if this a relatively simple question, but I am rather new to Arduino's and cannot seem to find any concise information on the topic.
This is my XBee, mounted on a shield and placed onto a MEGA 2560. I want to leave Serial for USB debugging and use the Serial1 for XBee communication.

Just to confirm, the two XBee's do communicate if I use SoftwareSerial.   This is the code that works using SoftwareSerial:
#include <SoftwareSerial.h>

// XBee's DOUT (TX) is connected to pin 10 (Arduino's Software RX)
// XBee's DIN (RX) is connected to pin 11 (Arduino's Software TX)
SoftwareSerial serial1(10, 11); // RX, TX
boolean nextLine = false;
void setup()
{
  Serial.begin(9600);
  serial1.begin(9600);
}

void loop()
{
   while(serial1.available()){ // there is data being sent from the xBee
    char read = char(serial1.read());
    if(read == 'A'){
      //Where ~ is the EOT character
      serial1.write("55.134~");
    }
  }
}

How do I communicate using Serial1?

If you take a look at the headers on the Mega, you'll notice that one of them has labels of "RX1" and "TX1" through "RX3" and "TX3". You'll also notice that the XBee shield does not connect to that header, therefore you cannot use Serial1 through Serial3 with the shield. Either switch to a breakout board that you can connect manually or stick to software serial.


Regulator magic smoke I have accidentally released the magic smoke from the regulator on a digispark board. I did this when I accidentally plugged a circuit into the 5V and the VIn instead of the 5V and Gnd, and then plugged the board into the USB port.

The attiny chip still works - I know because I plugged it in to the USB ,with no circuitry attached, and the uploaded program still runs happily.

My question is, is there any possibility that when the magic smoke was released from the regulator, the attiny was also damaged?

Secondly, is there any harm in leaving the dead regulator on the board? Or am I better off cutting it off?

Linear voltage regulators have an internal parasitic diode that shorts the output to the input. You have burned out this diode which has destroyed the regulator, but it is highly unlikely that any other components have been damaged. You can get away with cutting away the legs of the regulator, but complete removal will be difficult due to the large size of the tab connection and will likely result in damage to the other components.


Runtime Error when using array of structs of unknown size as variable within class - some kind of overflow issue? I have a class defined as below, it's basically a simple ring buffer, with some methods for getting useful statistics from the data held in the buffer.

enum BalanceMsgType{
  BAL_MSG_NOT = 0,
  BAL_MSG_READING = 1,
  BAL_MSG_SPECIAL = 2,
  BAL_MSG_ERROR = 3
};

typedef struct MeasuredMass{
  float mg;
  unsigned long time;
  bool steady;
  BalanceMsgType type;
};

class RingBuffer{
  private:
  unsigned int _size = 0;
  unsigned int _pos = 0;
  MeasuredMass *_array;
  void LinearRegression(){
    //... left out for simplicity
  }
  public:
  float lin_reg_m = 0;
  float lin_reg_c = 0;
  float lin_reg_r = 0;
  float est_current_mg = 0;
  //methods
  RingBuffer(unsigned int size){
    _size = size; //forgetting to put this line ->div0-> >1hr debugging :(
    _array = new MeasuredMass[_size];
    for (int i = 0; i < _size; i++){
      _array[i].mg = 0.0;
    }
  }
  void Add(MeasuredMass in_element){
    _array[_pos] = in_element;
    _pos = (_pos + 1)%_size;
    LinearRegression();
    est_current_mg = lin_reg_m*(in_element.time+BALANCE_DELAY) + lin_reg_c;
  }
  void ReadInOrder(MeasuredMass *pdata){  //Call with
                                          //my_buffer.ReadInOrder(data)
    for(int i = 0; i < _size; i++){
      pdata[i]=_array[(_pos+i+1)%_size];
    }
  }
  float Sum(){
    //...
  }
  float Mean(){
    //...
  }
  float StdDev(){
    //...
  }
  bool SteadyEnough(float max_sd){
    //...
  }
};

It compiles fine, and runs nicely in test programs. However, if I include it in larger programs (something like progmem 117404 of 122880 bytes, global vars 13604 of 32768) I get a "Board at COM8 not available" warning when using the Arduino Serial Monitor after uploading to my Fubarino Mini. (Even without actually interacting with those programs beyond creating an instance of the class.) Recent experience tells me this is some kind of crash due to a runtime error.

Fiddling around with the code, I've found that the issue doesn't occur in a version of the library which holds an array of floats instead of my MeasuredMass. That my MeasuredMass struct is obviously much larger than a float suggests to me that this is due to some pointer/array overflowy behaviour.

I've also managed to show that if I alter the class such that it uses a fixed length array rather than a pointer to one, the issue disappears.

i.e. RingBuffer's private member MeasuredMass *_array; becomes MeasuredMass _array[25];
and

RingBuffer(unsigned int size){
  _size = size; //forgetting to put this line -> div0 -> >1hr bugtracking
  _array = new MeasuredMass[_size];
  for (int i = 0; i < _size; i++){
    _array[i].mg = 0.0;
  }
}

becomes

RingBuffer(){
  for (int i = 0; i < _size; i++){
    _array[i].mg = 0.0;
  }
}

I'd rather maintain the ability to set the size of the ring buffer at runtime (in my case it's set based upon the number of seconds' worth of data requested), so can anyone help me in figuring out how I can achieve this without running into the overflow / memory problems I seem to be having?

Thanks

The problem is most likely here:

_array = new MeasuredMass[_size];

You're allocating _size * sizeof(MeasuredMass) bytes in the heap. If _size is too big the amount of memory allocated becomes too great and it fails to allocate. You should check if _array is NULL or not after the new.  If it's NULL then it failed to allocate.

The problem is that heap allocation is limited to 2kB. This is regardless of the amount of memory you actually have in the chip. This is a limit imposed by the compiler (actually the libraries bundled with the compiler) and is set by a value in the linker script.  It's something I've been campaigning to have removed from the libraries for many years, but it's always fallen on deaf ears. So much so that I provide a "fixed" version of the compiler in UECIDE that removes this hard limit.

The best thing you can do is to not use dynamic allocation. Instead have a statically created array which you then pass to the constructor.

MeasuredMass massBuffer[25];
RingBuffer massRing(massBuffer, 25);

and:

RingBuffer(MeasuredMass *buf, unsigned int size){
  _size = size; //forgetting to put this line ->div0-> >1hr debugging :(
  _array = buf;
  for (int i = 0; i < _size; i++){
    _array[i].mg = 0.0;
  }
}


HC-05 bridge using Arduino Nano and GNU Screen I connect an HC-05 module to an Arduino nano with CH341 serial chip (voltage divider on RX pin). I am trying to make a bridge for a test, i.e. serial in, echo local and echo to Bluetooth and vice versa. I modified the echo code from here.

int incomingByte = 0;    // for incoming serial data

#include <SoftwareSerial.h>

SoftwareSerial BTSerial(10, 11); // RX | TX

void setup() {
    BTSerial.begin(38400);    // opens serial port, sets data rate to 9600 bps
    Serial.begin(9600);    // opens serial port, sets data rate to 9600 bps
}

void loop() {
  // send data only when you receive data:
  if (Serial.available() > 0) {

    // read the incoming byte:
    incomingByte = Serial.read();

    // say what you got:
    Serial.print((char)incomingByte);
    BTSerial.print((char)incomingByte);
  }

  if (BTSerial.available() > 0) {

    // read the incoming byte:
    incomingByte = Serial.read();

    // say what you got:
    Serial.print((char)incomingByte);
    BTSerial.print((char)incomingByte);
  }

under OSX I open two terminals. In the first terminal using screen /dev/cu.wchusbserial1410 9600 I see local echo as desired. But on the second terminal using screen /dev/cu.HC-05-SPPDev 38400 I see nothing after pairing. The only effect is that by typing the latter command, the module stops blinking rapidly and blinks only two times with long pause in between. Exiting the screen environment, then again blinks rapidly.

Appreciate any hints what I am doing wrong...

=====

intermediate success but not quite there yet:

I simplified the code and corrected the wrong connection. Local echo on serial works as usual, even between the two, characters are being transferred, but they are black question marks instead of why I typed.

/*
 * echo script
 */

byte incomingByte;

#include <SoftwareSerial.h>

SoftwareSerial BTSerial(3, 2); // RX | TX

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

void loop() {
  if (Serial.available()) {
    incomingByte = Serial.read();
    Serial.print((char)incomingByte);
    BTSerial.print((char)incomingByte);
  }

  if (BTSerial.available()) {
    incomingByte = BTSerial.read();
    Serial.print((char)incomingByte);
    BTSerial.print((char)incomingByte);
  }
}

Any ideas?

========

Edited the Buadrate to 9600. Now everything works.

Based on the above comments I provide here the full answer in the hope it will be useful in the future.

HC-05 has two modes. The Communication Mode and AT Command Mode. In the latter mode, HC-05 responds in kind of "config" way and many default settings of the communication mode can be change here. While the baud rate of the communication mode, and many other settings can be changed, the baud rate of the AT command mode is always fixed 38400 to avoid any confusions and mistakes. On the other hand, the default factory baud rate of the communication mode, i.e. before any change, is set to 9600. So the solution to my problem was to set the baud-rate to 9600 on my newly purchased HC-05 and I was able to make an echo bridge between HC-05 Bluetooth and serial. Here is the code:

/*
 * echo script
 */

byte incomingByte;

#include <SoftwareSerial.h>

SoftwareSerial BTSerial(3, 2); // RX | TX

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

void loop() {
  if (Serial.available()) {
    incomingByte = Serial.read();
    BTSerial.print((char)incomingByte);
  }

  if (BTSerial.available()) {
    incomingByte = BTSerial.read();
    Serial.print((char)incomingByte);
  }
}

After pairing HC-05 with OSX, I was able to open two OSX Terminals with one of these commands in the first terminal:

screen /dev/cu.wchusbserial1410 9600

and in the other:

screen /dev/cu.HC-05-SPPDev 9600

Everything worked properly, i.e. typing in one terminal produced characters in the other and vice versa. For changing the default baud-rate in the communication mode, I found a very good tutorial which can be found here.


Problem in receieving message I'm working on a project in which when I press reset button the arduino should send longitudes and latitudes to my phone. I'm a beginner and tried to join two codes, first code can send the message and the second code can get the lon and lat printed on the serial monitor.

First code--

int timesTosend=1;
int count=0;
char phone_no[]="+917771914436";
void setup()
{
  Serial.begin(9600);
  delay(2000);
  Serial.println("AT+CMGF=1");
  delay(200);
}
void loop()
{
  while (count<timesTosend)
  {
    delay(1500);
    Serial.print("AT+CMGS=\"");
    Serial.print(phone_no);
    Serial.println("\"");
    while(Serial.read()!='>');
    {
      Serial.print("Hii If this message is sent then its a huge sucess for me");
      delay(500);
      Serial.write(0x1A);
      Serial.write(0x0D);
      Serial.write(0x0A);
      delay(5000);
    }
    count++;
  }
}

Second code--

#include <SoftwareSerial.h>
#include <TinyGPS.h>

long lat,lon; // create variable for latitude and longitude object

SoftwareSerial gpsSerial(4, 3); // create gps sensor connection
TinyGPS gps; // create gps object

void setup(){
  Serial.begin(9600); // connect serial
  gpsSerial.begin(9600); // connect gps sensor
}

void loop(){
  while(gpsSerial.available()){ // check for gps data
   if(gps.encode(gpsSerial.read())){ // encode gps data
    gps.get_position(&lat,&lon); // get latitude and longitude
    // display position
    Serial.print("Position: ");
    Serial.print("lat: ");Serial.print(lat);Serial.print(" ");// print latitude
    Serial.print("lon: ");Serial.println(lon); // print longitude
   }
  }
}

My code which is not working--

#include <SoftwareSerial.h>
#include <TinyGPS.h>
long lat,lon; // create variable for latitude and longitude object

SoftwareSerial gpsSerial(4, 3); // create gps sensor connection
TinyGPS gps; // create gps object

void setup()
{
  Serial.begin(9600); // connect serial
  gpsSerial.begin(9600); // connect gps sensor
    Serial.begin(9600);
  delay(2000);
  Serial.println("AT+CMGF=1");
  delay(200);
}

int timesTosend=1;
int count=0;
char phone_no[]="+917771914436";
void loop()
{
  while (count<timesTosend)
  {
    delay(1500);
    Serial.print("AT+CMGS=\"");
    Serial.print(phone_no);
    Serial.println("\"");
     while(Serial.read()!='>');
    {
      while(gpsSerial.available())
      {
        if(gps.encode(gpsSerial.read()))
        { // encode gps data
    gps.get_position(&lat,&lon); // get latitude and longitude
    Serial.print(lat,lon);
      delay(500);
      Serial.write(0x1A);
      Serial.write(0x0D);
      Serial.write(0x0A);
      delay(5000);
        }
      }
    }
    count++;
  }
}

Please help me out by correcting my mistake in the code.

Serial.print(lat,lon);

That doesn't do what you think it does.  That is trying to print the latitude encoded in base "lon", which just isn't going to work.

Instead you need to send it as separate operations:

Serial.print(lat);
Serial.print(",");
Serial.print(lon);

Also you should separate out the GPS and GSM routines.  Create a function that gets the latitude and longitude, and another function that sends the two values as a text message.  Then you can keep things as discrete obvious steps and not get confused with what is happening when.


how to block Arduino code until a certain event? i am tring to enter a series of numbers using "keypad" to different variables..when simulate the code on proteus it only took the first "getkey()" function and ignored the rest ..
SO,
How can i block an arduino code until a key is pressed by keypad, in other words prevent the rest of code from being executed before a key is pressed

It depends on how the "keypad" is implemented. If you've got it hooked up to a hardware interrupt, then you only need to add an interrupt handler for that event.

On the other hand, the more "straight-forward" implementation is that you have to poll the pins to see if a key was pressed.  Simply do that in a loop until you see a key press, call your event-handler method, and then continue to loop.


Timeout error uploading code to Arduino Mega 2560 I am new to Arduino programming, and my first sketch (from a tutorial) failed to upload. I am having trouble trying to figure out what is causing it (have tried to upload the sketch using different COM ports on my Mac).

Here's my setup:

  USB COM Port -> Arduino Mega 2560 -> Grove Mega Shield -> Grove Temperature Sensor
  v1.2 connected to Mega Shield UART0.

Here's the code from the tutorial:

// Demo code for Grove - Temperature Sensor V1.1/1.2
// Loovee @ 2015-8-26

#include <math.h>

//R0 = 100000 results in 'overflow in implicit constant conversion'

const int B=4275;                 // B value of the thermistor
const int R0 = 100000;            // R0 = 100k
const int pinTempSensor = A5;     // Grove - Temperature Sensor connect to A5

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

void loop()
{
    int a = analogRead(pinTempSensor );

    float R = 1023.0/((float)a)-1.0;
    R = 100000.0*R;

    float temperature=1.0/(log(R/100000.0)/B+1/298.15)-273.15;//convert to temperature via datasheet ;

    Serial.print("temperature = ");
    Serial.println(temperature);

    delay(100);
}

And here's the error output:

avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_cmd(): short reply, len = 0
avr_read(): error reading address 0x0000
    read operation not supported for memory "signature"
avrdude: error reading signature data for part "ATmega2560", rc=-2
avrdude: error reading signature data, rc=-1
avrdude: stk500v2_ReceiveMessage(): timeout

What I have done so far:

1) Disconnect and reconnect USB Cable
2) Restart Arduino IDE (1.6.9)
3) Changed COM Ports
4) Press the reset button

Could someone please explain to me what the error output means?

Have you tried to upload your sketch without the shields? I had a similar problem once where I couldn't upload while a connection was plugged into UART0. Unplugging the sensor worked for me.


Does the square-wave nature of PWM dictate how much resistance you need? I think the answer is yes, but I wanted to ask the question anyway for future common reference. And to check my understanding.

Say I want to power 10 LEDs with PWM with my Mega 2560. I have a bunch of 200 ohm resistors.

I know the Mega and most other Arduinos can safely provide a maximum of 200mA total current. 200mA / 10 is 20mA per LED maximum.

Using my 200 ohm resistors I can calculate how much voltage will supply 20 mA of current:

V = 200 ohms * 20mA
V = 4V

So I just need to make sure to analogWrite less than or equal to 4V to each of the ten LEDs and I won't cross the 200mA threshold. That's if PWM was true analog.

However, PWM is not true analog, and if I analogWrite 4V to each pin, they're going to spend most of the time at 5V and some of the time at 0V.

When every pin is at 5V the board has to supply

(5V / 200 ohms) * 10 = 250mA

Which is over the spec, so I am in danger of damaging my board. Right?

So if I want to calculate the maximum current draw of the 10 LEDS being powered simultaneously with PWM, I have to assume that they are all getting 5V regardless of what I analogWrite to them. I do not actually have control over the voltage, I only have control over the resistance.

Thus in order to be safe I need to get some new resistors with resistance:

5V / 20mA = 250 ohms

Is this all correct?

It's... mostly wrong. For three independent reasons.

The LEDs themselves, like all diodes, absorb some of the electrovoltaic potential of the electricity passing through them, resulting in a voltage decrease in their circuit. This means that although 5V is being used to power the resistor and LED in a circuit, only some of that voltage is passing through the resistor. If we use a typical (for blue, white, and other exotic colors) forward voltage (Vf) of 2.8V, this means that the resistor only has 2.2V across it. For a 200ohm resistor, this means that only 11mA is passing through the circuit. If you want 20mA to pass through the LED you need to use a resistance of 110ohm instead.

Second, the voltage from the MCU pins themselves depend on the current passing through them. Section 32.7 of the ATmega2560 datasheet, "Typical Characteristics - Pin Driver Strength" has charts for voltage versus current for both sourcing and sinking current; at 20mA the voltage drops to about 4.5V, which means that the resistance required for a 2.8V LED drops from 110ohm down to 85ohm.

Third, although semiconductors (i.e. the MCU and LED) can be damaged when too much current passes through them, it is not the current itself that causes the damage. The current passing through the voltage drop results in a consumption of power, and this power subsequently turns into heat. This heat then causes the breakdown of the semiconductor material. Even a junky, third-hand LED can take bursts of current up to 35mA or so without being damaged, provided the duration is limited. With a PWM signal this duration is directly linked to both the frequency and the duty cycle of the signal. You will need to see the datasheet for the LED in question to figure out what the maximum safe current and duration are, but the implication is that if you keep the frequency high enough and the duty cycle low enough, you can get away without any resistor at all and both the MCU and LED will survive.


Getting more current through an LED array I have an Arduino Uno controlling an array of 24 LEDs (datasheet).  I understand these LEDs are ultraviolet and have a forward current of 0.5A.  My power source (12V 2A) is wired to a switch which is then wired to the LED array and Arduino.  I should probably use a 12V 4A power source but was worried if too much current would go to the Arduino.  As per my attached diagram, the Arduino and LED array are in parallel.  I would like to get more current through my LEDs to increase their brightness.  What would be the best way to do this?

Updated: I tried adding a 100 Ohm resistor (where R11 is located) but the Arduino wasn't drawing enough power to turn on my LCD.  And then I tried a 1 Ohm resistor instead but the resistor burned out.  Unfortunately, I threw out the resistor and don't have a picture of it.  I believe the correct value should be ~47 Ohm so I have added that resistance as R11.  However, I haven't tested it yet as I want to make sure it's correct.  (12V - 6V) = 130mA * R >>> R = 46.15 Ohm.  I used a voltage drop of 6V so that at least 5V is still going into the Arduino (12V - 6V = 6V which is greater than 5V).  I measured the current through a multimeter to be 130mA.

The current a bipolar transistor configured as a common emitter amplifier will allow from its collector to its emitter is equal to its beta time the base to emitter current.

A beta of 100 is common for many transistors. Assuming this information is close enough to your transistor, we can choose a base series resistance suitable for the collector to emitter current desired.

For example if you were using a 5 volt microprocessor and the voltage drop across the base to emitter was the usual 0.7 volts for silicon semiconductors and you had a base series resistor of 10Kohms:

V = I * R
V = 5 - 0.7 = 4.3 volts
R = 10000 ohms
I = 4.3/10000 = 0.43mA
I(ce) = Beta * 0.43mA
I(ce) = 100 * 0.43mA = 43mA

You could pass up to 43mA from the collector to the emitter.  If that is not enough,you can lowered the base resistor to 1Kohms:

R = 1000 ohms
I = 4.3/1000 = 4.3mA
I(ce) = Beta * 4.3mA
I(ce) = 100 * 4.3mA = 430mA

And increase the current to 430mA.  You still need to verify that the processor can supply the current to control the transistor (4.3mA as calculated above) as well as pick a transistor of sufficient capacity to handle the load.

If a beta of about 100 is not enough, consider using a Darlington transistor arrangement. This type of "2 transistor" device has a gain of the product of each individual transistor's beta.  So, it is common for such a device to have a beta of 10000!  Using this device, you can use a much larger base resistor and still be able to switch more current.


Non-blocking incrementation with single button pressure I am looking for a way to increment a variable by one each time a button is pressed. Current approach is the following :

    if (redButton.isPressed())
    {
        a++;
        delay(100);
    }

isPressed() just return true if the pin state is HIGH.

delay(100) is used to compensate the small amount of time the button is being pressed. Otherwise a would be incremented multiple times in a single press. But it's blocking behavior, my program can't do anything else during that delay.

In short I'm looking to add a method in my Button class to detect if the button "has just been released".

In your approach a button press will be detected every 100ms when you just keep the button pressed. So you have to set a flag when the button is pressed. When the button is not pressed while your flag is set, that's the event you're looking for. In this way you can detect both a button press and a release respectively.
As @JRobert mentioned, there still has to be an amount of time between two calls to such a routine to provide some button debouncing.

bool pressed_flag=false;
bool button_timestamp=millis();
uint16_t button_period=100;

if(millis()-button_timestamp>button_period){
  button_timestamp=millis();
  if(redButton.isPressed() && !pressed_flag){
    // button has just been pressed
    // you can do sth. here
    pressed_flag=true;
  }
  else if(!redButton.isPressed() && pressed_flag){
    // button has just been released
    // you can do sth. here
    pressed_flag=false;
  }
}


How to break out the due power supply and USB connectors? I am planning a build with my own enclosure for the arduino due. As an alternative i would like to bypass the power jack and usb port that are factory soldered onto the board, in order to use jacks mounted on the enclosure, along with a power switch.
I've looked at the info regarding the boards pin configuration at https://www.arduino.cc/en/pmwiki.php?n=Main/arduinoBoardDue, and would appreciate if someone could confirm or correct this:

Can i use an external 9V adapter through a jack connected to the Vin and GND pins, respectively?

According to This question, you can't connect an alternative programming USB port to Serial 0 TX/RX pins (Mega board). If this applies to the due as well, what do i need to break out the programming USB port?

Edit: Perhaps one of these puppies is the least complicated solution?

so 1 - yes. the VIN pin has a common trace with the barrel jack, you can verify with a multimeter in continuity/beep mode. ive actually put power out through the barrel jack on a mega.
2- i cant find a clear schematic for the due at the moment, but on the mega the rx/tx pins are also common with the usb pins, thus they are not usable while plugged into usb


What type of connector does the GROVE system use? What type of connector does GROVE use?

I'm interested in wiring some old sensors so they're compatible with GROVE, so I first need to identify the connector so I can buy the housing and pins to crimp. It looks to be some type of JST connector, but there are many different sizes, each with incompatible pitches and a lot of retailers often advertise them incorrectly. Unfortunately, I can't find any documentation of the connector on Seeedstudio's site.

It looks like the Grove connector is proprietary. I emailed Seeedstudio, and they directed me to this datasheet. Unless I'm reading it incorrectly, it doesn't appear to correspond to any type of JST connector, although it's similar. It has 2mm pin spacing, which would make it closest to the JST-PH type, but all the other dimensions are slightly different.


Send analog value over IR? for my rc robot I want to use ir to send/receive the value from a jostick.

Is it possible ? I can't use any other radio chip like nrf24l01.

Yes, it is possible. That is already supported by the IR library. Please see this tutorial for further details. The outline of the sender is:

 uint16_t sample = analogRead(A0);
 irsend.sendSony(sample, 16);

And the receiver:

 if (irrecv.decode(&decodedSignal)) {
    uint16_t sample = decodedSignal.value;
    ...
 }

Cheers!


Increment in switch statement not working No matter how I rearrange this, the increment compare always returns false....

I have even taken it out of the if, and put it in its own if:

int buttonFSM(button *ptrButton)
{
    int i;
    i = digitalRead(ptrButton->pin);
    switch(ptrButton->buttonState)
    {
    case SW_UP:
        if(i==0 && ++ptrButton->debounceTics == DBNC_TICS) //swtich went down
        {
            ptrButton->buttonState = SW_DOWN;
            ptrButton->debounceTics = 0;
            return SW_TRANS_UD;
        }
        ptrButton->debounceTics = 0;
        return SW_UP;
    case SW_DOWN:
        if(i==1 && ++ptrButton->debounceTics == DBNC_TICS) //switch is back up
        {
            ptrButton->buttonState = SW_UP;
            ptrButton->debounceTics = 0;
            return SW_TRANS_DU;
        }
        ptrButton->debounceTics = 0;
        return SW_DOWN;
    }
}

Looks to me like the path where the if doesn't happen are getting you. You don't show what DBNC_TICS is set to, but I'm assuming it's > 1.

ptrButton->debounceTics will never be greater than 1 because you always:

    ptrButton->debounceTics = 0;


Servo motors won't work with motor controller I have a motor controller controlling two motors, which works perfectly fine when I comment out the two servos in the below code. These two servos are not connected to the motor controller but simply being operated using other Arduino Uno pins, as seen in the code.

When the servo attach() functions are included in the code the motor controller only works with one of the motors and the other completely stops working.

I don't understand why the servos are interfering with the motor controller. What's going on here?

#include <Servo.h>
Servo myServo1;
Servo myServo2;

int m1_ALI = 10;
int m1_BLI = 9;
int m2_ALI = 3;
int m2_BLI = 11;

int m1_AHI = 12;
int m1_BHI = 4;
int m2_AHI = 6;
int m2_BHI = 5;

void setup() {

  //myServo1.attach(7);
  //myServo2.attach(8);

  pinMode(m1_AHI, OUTPUT);
  pinMode(m1_ALI, OUTPUT);
  pinMode(m1_BLI, OUTPUT);
  pinMode(m1_BHI, OUTPUT);
  pinMode(m2_AHI, OUTPUT);
  pinMode(m2_ALI, OUTPUT);
  pinMode(m2_BLI, OUTPUT);
  pinMode(m2_BHI, OUTPUT);
}

void loop() {

moveForward(30);

}//end loop

void moveForward(int x){

    digitalWrite(m1_AHI, LOW);
    digitalWrite(m1_BLI, LOW);
    digitalWrite(m1_BHI, HIGH);

    digitalWrite(m2_AHI, LOW);
    digitalWrite(m2_BLI, LOW);
    digitalWrite(m2_BHI, HIGH);

    analogWrite(m2_ALI, x);
    analogWrite(m1_ALI, x);
}//end moveForward

See Servo.cpp:

  Note that analogWrite of PWM on pins associated with the timer are disabled when the first servo is attached.
   Timers are seized as needed in groups of 12 servos - 24 servos use two timers, 48 servos will use four.

Also Servo Library reference

  On boards other than the Mega, use of the library disables analogWrite() (PWM) functionality on pins 9 and 10, whether or not there is a Servo on those pins.

You are using pins 9 and 10 for your motors.

analogWrite uses PWM, the servo library uses PWM, you have a conflict of resources here.


How to read an analog value on ESP32-CAM with the SD card reader enabled? I use an ESP32-Cam module for a project for which I need both the SD card and the cam. According to this page, the only pins that are not in use by either the camera or the SD card reader are GPIO0, GPIO2 and GPIO16. However, I need to read an analog value, which is only possible with the pins 12-15, 2 and 4, as the Arduino forums state, which are all in use by the SD card reader.
However, I came across a way to make the SD reader leave the GPIO4 pin out, namely by initializing it with
SD_MMC.begin("/sdcard", true);

Now the flashlight does not light up anymore when accessing the SD card, which means that there is no output anymore to GPIO4. However, it still does not allow me to read the pin after the SD card has been initialized. I also tried "converting" the pin to a GPIO through
pinMode(4, FUNCTION_3);

but it did not make a difference.
So my question is: How can pin 4 be used to read analog values while still keeping the SD card reader functional? And if this is not possible, is there any other way to read an analog value into the ESP32-CAM?

According to the schematic and pin notes, I don't think you can use GPIO4 as an ADC input (it can be used as a GPIO pin and technically it can be configured as an ADC pin), but it has a 47k pull-up resistor on it, making it not possible to be used as an ADC input.
Depend on your hardware wiring skill, one alternative is to use an external ADC chip with i2c interface (such as an MCP3221) and connect it to TWI_SCL and TWI_SDA, but those pins are only available on cam-connector, not on the header pins.


I need some help getting data from a rangefinder I have wired up my range finder (CJVL53L0XV2) to a breadboard for testing and have run the arduino example code for the rangefinder. The rangefinder works, but I do not know how to take the distance that the range finder shows on the serial monitor, example: distance measured 44mm, and turn that information into a variable that the rest of my program could use.

I am not sure how to "grab" data from the sensor and turn that data into a variable that I can then manipulate. I have tried to dissect the example code, but it seems to be taking data and using functions that do not exist anywhere but in some files in the arduino library that I can't identify or access.

Below is the code that I have been trying to reverse engineer.

[code]
Adafruit_VL53L0X lox = Adafruit_VL53L0X();
int pbl = 9;
void setup() {
  pinMode(pbl, OUTPUT);
  digitalWrite(pbl, HIGH);
  delay(1);
  Serial.begin(115200);

  // wait until serial port opens for native USB devices
  while (! Serial) {
    delay(1);
  }

  Serial.println("Adafruit VL53L0X test");
  if (!lox.begin()) {
    Serial.println(F("Failed to boot VL53L0X"));
    while(1);
  }
  // power
  Serial.println(F("VL53L0X API Simple Ranging example\n\n"));
}

void loop() {
  VL53L0X_RangingMeasurementData_t measure;

  Serial.print("Reading a measurement... ");
  lox.rangingTest(&measure, false); // pass in 'true' to get debug data printout!

  if (measure.RangeStatus != 4) {  // phase failures have incorrect data
    Serial.print("Distance (mm): "); Serial.println(measure.RangeMilliMeter);
  } else {
    Serial.println(" out of range ");
  }

  delay(100);
}
[/code]

measure.RangeMilliMeter was the key to it all. After experimenting for several hours, I finally got it.


How to connect relay How to I connect the pins of one channel relay to control and led which is connected to pin 13 of an arduino uno.can you tell me the steps which pin will go to which pin

Wiring Diagram to Pin 13 for a single relay? This might help.


Basic WiFly server returning unexpected output within web client Currently trying to implement a lightweight webserver using the WiFly shield and an Arduino UNO, this is the code I have so far:

#include <SPI.h>
#include <WiFly.h>
WiFlyServer server(80);

/* Function defs */
void cmd(void)  { SpiSerial.print("$$$"); }
void dhcp(void) { SpiSerial.println("SET IP DHCP 0"); }
void pass(void) { SpiSerial.println("SET WLAN PHRASE 22222222"); }
void ssid(void) { SpiSerial.println("JOIN BTHOMEHUB"); }
void port(void) { SpiSerial.println("SET IP LOCAL 80"); }
void ip(void)   { SpiSerial.println("SET IP ADDRESS 192.168.1.123"); }
void tcp(void)  { SpiSerial.println("SET IP PROTOCOL 2"); }
void boot(void) { SpiSerial.println("REBOOT"); }

/* Pointer to a handler function */
typedef void (*Handler)(void);
Handler table[8] = { cmd, dhcp, pass, ssid, port, ip, tcp, boot };

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

  for(short x = 0; x < 7; x++) {
    table[x]();
    delay(100);
  }
}

void loop() {
  WiFlyClient client = server.available();

  if(client){
    while(client.connected()) {
      if(client.available()) {
        client.println("
Hi

This is text.
");
      }
    }
    delay(100);
    client.flush();
    client.stop();
  }
}

This compiles well, but when hitting 192.168.1.123 in my web browser I get an ever-increasing output like:

*HELLO*<
<
<
<
<
<
<
<
<
<
<
< (cont.)

Definitely not the expected html. I have been playing with this code for hours now and this is the most positive output I can get. If I do a Serial.write(client.read()) within if(client.available()) { I am able to print all the request information to the serial monitor, it just seems I am perhaps sending the data in an incorrect format? Any suggestions? Cheers

Edit

I have updated the codebase to include the http headers,

client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Connnection: close");
client.println("");
client.println("<!DOCTYPE html>");
client.println("
Hi.....

now I get I different (similar) output, seems like it is printing the first character of each new line

*HELLO*H
C
C

<
<
H
C
C

Your browser sent a HTTP GET request. You need to send a HTTP response in kind, in accordance with the protocol, for your browser to correctly interpret the data. Something like this should do:

  #define TIMEOUT 100
  char response[] = "
Hi

This is text.
";
  unsigned long lastRead;
  ...

  while (client.connected()){
    if (client.available()){
      lastRead = millis();
      while (millis() - lastRead < TIMEOUT){
        while (client.available()){
          Serial.write(client.read());
          lastRead = millis();
        }
      }
      client.println("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nConnection: closed\r\n\r\n");
      client.print(response);
      break;
    }
  }
  delay(1000);
  client.stop();

EDIT:

It turns out that the Wifly shield sends a response status as well as "HELLO" by default. You have to disable that with a few commands:

set comm remote 0
set comm open 0
set comm close 0

This will ensure that "HELLO" isnt sent each time a client connection is made, though I'm not sure if this affects the default HTTP/0.9 200 OK response status that is always sent. You can try the sketch above with and without the response header to see what you get.


Arduino UNO R3 + SIM800L / NodeMCU via Hadware Serial. Possible? I'm using Arduino UNO R3 with NodeMCU and SIM800L module. I have to connect these two devices to UNO and make a serial communication between them: UNO<>SIM800L and UNO<>NodeMCU.

Can I use GPIO0 and GPIO1 of UNO (RX, TX) to communicate with one of above devices?

Thanks in advance.

If all you need to do is communicate between the NodeMCU and the SIM800L, what do you need the Arduino for?

Connect the SIM800L directly to the NodeMCU and program the NodeMCU to do whatever communication is needed for the SIM800L.


ESP8266, prints ready at start but no response to AT command I have been using ESP8266 wifi module with Arduino as FTDI. The power for ESP8266 comes from LM317 5V - 3.3v regulated supply(I am sure 5V is powerful enough to give upto 1A of current).

The RX of ESP8266 is connected to RX of Arduino via a voltage divider to ensure 3.3V logic level. But still, I am not getting any response to AT command, though my laptop and phone wifi have successfully connected to AI-Thinker... SSID(which is an open hotspot from ESP8266).

I am also having some garbage values on the serial port immediately after I turn on the power supply to ESP8266. I have tested all baud rates available in Arduino IDE v1.0.5 with no results.

The resistor values for lm317 are R1 = 125 Ohm, R2 = 225 Ohm with which I am getting around 3.2 Volts.

The connections are as follows:-

-----Arduino UNO-----

RESET ------------ GND

Arduino UNO ----- ESP8266

TX ------------------- TX

RX ---5V to 3.3v--- RX

GND ----------------- GND

ESP8266 --------- LM317(5V to 3.3V)

VCC --------------- 3.3V

GND --------------- GND

CH_PD ------------ 3.3V

EDIT - 1: I have bought a new ESP8266, and even it doesn't responds to any AT commands, thought there is some difference in the previous ESP8266 output and this new ESP8266 output.

The difference is a sort of good news to me, it sends ready after sending some garbage at 115200 baud on boot which never happened with previous one(ESP8266).

Is anyone having some clue why there is no response to AT commands?
May it be a issue with TX line?

EDIT - 2: I have also used another Arduino with same connections doubting the TX pin on Arduino, but with same luck, bad luck. Still, nothing got changed.

EDIT - 3: I am shifting 5v to 3.3v by using three 100 ohm resistors.

Connect TX of arduino to esp8266 RX, and arduino RX to esp8266 TX.

See this link for more info.


I have to reload Sketch every time I start my Yun I am new to Arduino and IoT. I got my hands on a Yun and loaded a simple sketch to subscribe to a topic. I am receiving messages (I have set up a PHP script and broker on a server, which takes care of the messages) and can turn ON and OFF LED, L13. But when I disconnect the Yun from my PC and connect it again (to power it up), it stops receiving messages. I have to load the sketch again to make it work. Here is my code:

#include <spi.h>
#include <pubsubclient.h>
#include <yunclient.h>

byte server[] = { 192, 168, 1, 196 };
int port = 1883;
char* pubTopic = "fromYun";
char* subTopic = "sensor/light";

void callback(char* topic, byte* payload, unsigned int length) {
  //convert byte to char
  payload[length] = '\0';
  String strPayload = String((char*)payload);
  // handle message arrived
  if(strPayload == "ON") {
    digitalWrite(13, HIGH);
  } else if(strPayload == "OFF") {
    digitalWrite(13, LOW);
  }
}

YunClient yun;
PubSubClient mqtt(server, port, callback, yun);

void setup() {
  Serial.begin(9600);
  pinMode(13, OUTPUT);
  digitalWrite(13, LOW);
  Bridge.begin();
  if (mqtt.connect("arduinoClient")) {
    mqtt.publish(pubTopic,"hello world!");
    mqtt.subscribe(subTopic);
  }
}

void loop() {
  mqtt.loop();
}

Am I missing something?

I referred to this post and PubSubClient -> mqtt_basic.ino for making this ketch.

I don't understand what mqtt.connect("arduinoClient") is. I mean, what is this string "arduinoClient"? In one sketch on GitHub I saw it as "yun"...

Any help will be appreciated. Thanks in advance!

EDIT: I am using Mosquitto MQTT.

Please explain which messages? Serial port messages or MQTT messages?

The mqtt.connect name "arduinoClient" is the ID name. It depends on the server what the parameters should be. For some servers it can be an empty string and the second parameter should be the account name, and a third parameter for the password/key.

When you upload a sketch, the OpenWrt part is already running. Perhaps there is a problem with Bridge.begin. Try to wait 90 seconds before calling Bridge.begin. If a 90-second delay makes it work, lower it to 5 seconds, and keep it at 5 seconds.

Perhaps you can use (blinking) LEDs to indicate that the code has finished the Bridge.begin or to indicate an error.

When you solve this problem, there will be other problems. Have you updated to the newest firmware for the OpenWrt part? The Arduino Yún might only work with a very simple and small sketch. Don't try to add too many things that use the Bridge. The OpenWrt/linux part is reliable, you can run linux scripts there. The ATmega32U4 part is just like an Arduino Leonardo and is also reliable. It is the combination and the Bridge that causes a never ending chain of problems.

What about the Raspberry Pi? That is reliable. Have you thought about the ESP8266 or ESP32 in Arduino compatible mode? Adafruit has an MQTT server for users, and the Adafruit Feather M0 WiFi seems a very nice board. Anything but the Yún.

My best advice for you is to grab a hammer and destroy the Yún and forget about it. It will make your life so much easier.

(I just noticed that this is a very old question, sorry, but my answer is still valid).


Arduino connection with the server failed I am trying to connect arduino uno and ethernet shield and try to send some data to an asp.net web api application. When i upload the sketch, i get in the serial monitor connection failed.
I don't understand what's going wrong ?
Below is the code i am using

#include "cactus_io_DHT22.h"
#include <SPI.h>
#include <Ethernet.h>
#include <Client.h>

#define DHT22_PIN 2

byte mac[] = {
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xDD };

IPAddress ip(192,168,0,177);
IPAddress server(192,168,0,11);
EthernetClient client;

DHT22 dht(DHT22_PIN);
float heatindex1 =0.00;
float heatindex2 = 0.00;

void setup() {
  Ethernet.begin(mac,ip);
    delay(1000);  Serial.begin(9600);

    Serial.println("connecting...");
    if (client.connect(server, 80)) {
      Serial.println("connected :D ");
    }
  Serial.print("Arduino server IP address: ");
  Serial.println(Ethernet.localIP());
  Serial.println("DHT22 Humidity - Temperature Sensor");
  Serial.println("RH\t\tTemp (C)\tTemp (F)\tHeat Index (C)\t Heat Index
 (F)\t Max(C)\t\t Min(C)");

  dht.begin();
  dht.readHumidity();
  dht.readTemperature();

}

float max1=dht.temperature_C;
 float min1=100;

void loop() {
  dht.readHumidity();
  dht.readTemperature();
  heatindex1=dht.computeHeatIndex_C();
  heatindex2=dht.computeHeatIndex_F();

  if(dht.temperature_C>max1)
  {max1=dht.temperature_C;}
  if(dht.temperature_C<min1)
  {min1=dht.temperature_C;}

  // Check if any reads failed and exit early (to try again).
  if (isnan(dht.humidity) || isnan(dht.temperature_C)) {
    Serial.println("DHT sensor read failure!");
    return;
  }
  if (client) {

   // When a client sends a request to a webserver, that request ends with a blank line
    boolean currentLineIsBlank = true;

    Serial.println("OK"); }

  if (client.connect(server, 80)) {
    client.print("GET /api/todo?humidity=");
    client.print(dht.humidity);
    client.print("&temperature1=");
    client.print(dht.temperature_C);
    client.print("&temperature2=");
    client.print(dht.temperature_F);
    client.print("&heatindex1=");
    client.print(heatindex1);
    client.print("&heatindex2=");
    client.print(heatindex2);
    client.print("&max1=");
    client.print(max1);
    client.print("&min1=");
    client.print(min1);// And this is what we did in the testing section above. We are making a GET request just like we would from our browser but now with live data from the sensor
    client.println(" HTTP/1.1"); // Part of the GET request
    client.println("Host: 192.168.0.11"); // IMPORTANT: If you are using XAMPP you will have to find out the IP address of your computer and put it here (it is explained in previous article). If you have a web page, enter its address (ie.Host: "www.yourwebpage.com")
    client.println("Connection: close"); // Part of the GET request telling the server that we are over transmitting the message
    client.println(); // Empty line
    client.println(); // Empty line
    client.stop();    // Closing connection to server

  }

  else {
    //If Arduino can't connect to the server (your computer or web page)
    Serial.println("--> connection failed\n");
  }

   Serial.print(dht.humidity); Serial.print(" %\t\t");
  Serial.print(dht.temperature_C); Serial.print(" *C\t");
  Serial.print(dht.temperature_F); Serial.print(" *F\t");
  Serial.print(dht.computeHeatIndex_C()); Serial.print(" *C\t ");
  Serial.print(dht.computeHeatIndex_F()); Serial.print(" *F\t ");
  Serial.print(max1); Serial.print(" *C\t ");
  Serial.print(min1); Serial.println(" *C\t");

  delay(5000);
}

I don't know of this library, but you're using the connection code twice, once in the setup() and later again in the loop().

You're already checking whether the client exists:

if (client) {

Why are you asking a few lines down again to connect?

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

My guess is, that this if()-Clause is not necessary. Or the connection in the setup() should be removed.

If this isn't the source of the error, first test whether the server on 192.168.0.11 is running and that you can connect (from a different device) to the port 80.


Not sure if logic analyzer shows an error or perhaps just a 'relay bounce' I have an Arduino controlling a relay. I was taking a look at the timings using a logic analyzer and at the onset of the relay switching, it quickly switches again.

This seems to be occurring randomly and I thought it could be highlighting a problem with my code but I wondered if it might just be a 'relay bounce' due to the speed of the switch. I've attached an image below. Any feedback is greatly appreciated. Thanks.

According to your plot, the pulse length is 50 microseconds. Typical mechanical relay switching time is 10 milliseconds, which is 200 times longer. It's next to impossible that the pulse is due to your software powering the relay back on for a moment, since the relay simply could not react to such a short input pulse.

So yeah, it's just a bounce. You can safely ignore it in most cases, unless you're counting events or doing something similar. In the latter case, there are both hardware and software debouncing techniques, which share the basic idea of a low-pass filter.


Arduino-based mains frequency monitor I'm looking to put together a simple mains frequency monitor based on the Arduino platform. The mains here are 250 V @ 50 Hz, but obviously these fluctuate slightly, which is the whole point of the exercise. (I am not interested in capturing voltage fluctuations, only frequency fluctuations).

I have never used any Arduino products before, but I am familiar with PIC-based MCUs. I understand Arduino should be somewhat simpler. Also, I am not an electronics engineer.

Presumably, the Arduino will sample the mains frequency for a second or two, and then report the result somehow. I guess the easiest way is for a computer connected to the Arduino by USB to receive the result and act accordingly. Otherwise, other options include adding an Ethernet module to the Arduino and having it HTTP POST the result to a web server.

(I assume doing this naive method is preferable to recording a time series and then performing a Fourier transform?)

Size isn't a huge concern, but a compact device is preferable over a larger one as I'll be 3D-printing a custom enclosure for it. Therefore I would like to use the Arduino Nano if it's suitable.

Here is what I have so far:

The 250V mains will be half-rectified with an IN4004 (?) transistor (together with a 1K resistor and 0.22 uF cap), and that will go into a 4N35 optocoupler.
A digital (?) GPIO pin from the Arduino goes into the base of the 4N35 and emitter goes to GND.
The Arduino samples for a short time the number of pulses on that pin, does a simple calculation, and reports the result.

Here are my uncertainties so far:

Based on my research, I believe the Arduino can reliably be powered by USB. If this is correct, this would be ideal as it would avoid me having to build a low voltage DC power supply for it.
How stable is the clock on the Arduino? How many decimal places on the frequency can I realistically achieve?
I presume I'll need to debounce the result from the optocoupler? Will there be some noise as the transistor transitions between states? Are there built-in debouncing functions or will I need to write my own? How is this likely to affect available clock cycles and therefore the accuracy of the measurement?
I've seen PIC projects where it interacts with the computer by emulating a keyboard. While simple, this wouldn't be ideal as the computer it's connected to must also remain usable. The software processing the result should run in the background while a user can continue using the computer. How simple is it to write some software (in C#) that will recognise the Arduino connected via USB, and communicate with that device in particular?

I also welcome any other comments and suggestions. Thank you.

Edit: Following these helpful comments and suggestions, I've made some revisions and asked a follow-up question.

I understand Arduino should be somewhat simpler [than PIC].

The whole Arduino platform (boards, core library and IDE) makes it super
easy to get started and do simple things. However, if you want to
“push the limits” and use the full potential of the MCU, you may have to
dig into low-level programming, and this has a steep learning curve.

The 250V mains will be half-rectified with an IN4004 (?) transistor
(together with a 1K resistor and 0.22uF cap), and that will go into a
4N35 optocoupler.

1 kΩ seems way too low to me: your resistor will dissipate on
average 31 W, and it will burn unless it is a heavy-duty power
resistor. You should choose a resistor that limits the current to a
value low enough to avoid overheating, but still high enough to reliably
turn on the optocoupler. If these two constraints end up being
incompatible, you will need a step-down transformer in addition to (not
instead of) the optocoupler.

A digital (?) GPIO pin from the Arudino goes into the base of the 4N35
and emitter goes to GND.

The base of the optocoupler is typically left floating. You connect the
Arduino input to the collector, using either the internal or an external
pullup resistor, and you ground the emitter.

I believe the Arduino can reliably be powered by USB.

Yes, powering through USB is fine. The Arduino itself draws very little
power. Only when it is powering something else you may worry about
power limits. Here it would seem your Arduino will only be sourcing a
very small amount of current into the output transistor of your
optocoupler, so you will be fine.

How stable is the clock on the Arduino?

Terrible. Most Arduinos are clocked off a ceramic resonator. These
are typically specified with 0.5% frequency tolerance, but their
frequency is constantly fluctuating, and is also strongly dependent on
ambient temperature. This makes those Arduinos grossly unsuited for any
job requiring precise timings. I would recommend you get an Arduino
sporting a real quartz crystal, like the Leonardo or the Micro. A quartz
crystal can be quite inaccurate, but at least its frequency is stable.
It's orders of magnitude more stable than a ceramic resonator. C.f.
for example this article about the Arduino clock frequency
accuracy.

I presume I'll need to debounce the result from the optocoupler?

If the capacitor after your half-wave rectifier is well dimensioned,
your signal should be clean and not need debouncing. The Arduino digital
inputs all have Schmitt triggers which clean up the input noise as
long as it is not excessive. If you really need debouncing (check with a
scope if you can), well... there are no provisions for doing so in the
Arduino core library, but there is a Debounce tutorial among the
examples shipped with the Arduino IDE, and there are a few third party
debounce libraries floating around the Web.

How simple is it to write some software (in C#) that will recognise
the Arduino connected via USB, and communicate with that device in
particular?

As stated in other answers, your Arduino will be seen by your computer
as a virtual serial port. I don't know C#, but any decent programming
language should allow you to easily read data from a serial port.
Measuring method:
You will time one or several periods of the input signal. There are
several ways of doing so. In roughly increasing order of complexity and
accuracy:

You continuously monitor the digital input, in a loop, and whenever
you see a transition from LOW to HIGH you record the current time
using micros().

You use an interrupt pin as the input and you have the interrupt
handler record the time with micros().

You use the input capture facility of your 16-bit timer running at
the full CPU speed.

The methods using micros() have a resolution of 4 µs. Both will
give you some software-induced jitter because they depend on the timing
of your program execution. The advice given by GuitarPicker: “Keep your
code predictable, using as few conditional branches as possible that
might alter how long your code takes to run each cycle” is relevant only
to the first method. The interrupt method is immune to your main loop
timing, but it is still affected by the CPU processing other interrupts.
The input capture method will give you single-cycle resolution and
accuracy, with zero software-induced jitter. That would be my first
choice, but it requires digging into the MCU datasheet and doing some
low-level programming.

Addendum: Here are some tentative answers to a comment posted by
Ozzah to his own question:

I probably want 4 decimal places if possible.

If you want 10−4 absolute accuracy, you may need to
calibrate your clock, even if it is a crystal. If you only require
10−4 stability (variations of the frequency), then even a
ceramic resonator may be (barely) up to the task, if you don't mind
recalibrating it every few weeks, and assuming your indoor temperature
doesn't vary by more than ≈ 10°C.

I want the highest resolution and best tolerance possible.

Then a quartz crystal is definitely a plus. It's roughly 100 times
more stable than the ceramic resonator.
But if you really want the “best”, you may as well follow Milliways'
advice and get a GPS reference. Some options, in increasing order of
price and accuracy:

A simple GPS module for the Arduino. Make sure you get one with a
1PPS output (a “one pulse per second” reference signal). You may want
an external antenna for better reception.
A GPSDO (GPS disciplined oscillator). This is typically a lab-grade
frequency standard consisting of an OCXO (oven-controlled crystal
oscillator) disciplined by a feedback loop into tracking GPS time. It
gives the same long-term stability as the simple GPS module but has
far better short-term stability.
A rubidium-based GPSDO. This is similar to the above but has also a
rubidium atomic frequency reference. Still better short-term
stability. Now we are talking about stabilities in the
10−11 to 10−12 range. Provably overkill for
your use case.

From the software point of view, I would recommend you start with the
interrupt method, just to get a prototype working easily, and then go to
the input capture method, as it will give you the best accuracy. It
should be possible to be cycle-accurate with the interrupt method, but
that would require some non-trivial tweaks.
Note also that the Arduinos based on the ATmega32U4 (Leonardo and Micro
at least) have two 16-bit timers with input capture capability. You
can then time both the mains signal and a 1PPS reference in parallel. If
your Arduino has only one 16-bit timer (like the Nano), you would have
to time one of the signals with the interrupt method.

I'm trying to find a way to determine which Arduino boards use
crystals for the MCU clock and which use ceramic resonators. From what
I can see, they all have a crystal, but presumably that's for the USB
interface?

Yes, the USB/serial interface is clocked off a crystal more often than
the main MCU. The Arduinos that do not have a separate USB/serial
bridge (like those based on the ATmega32U4) seem to have the main MCU
clocked off a crystal.

How can I get a list of Arduinos that use crystals?

It's often stated in the product page. E.g., the page of the Arduino
Micro states
(emphasis mine): “It has 20 digital input/output pins (of which 7 can be
used as PWM outputs and 12 as analog inputs), a 16 MHz crystal
oscillator, a micro USB connection, an ICSP header, and a reset
button.”
Arguably, the info is not very prominent, and a compiled list would be
useful. I think this could be a very good question to ask in this site.