Running a robot with 2 front-facing sensors, but it's stuttering Here's the run down: I have a small robot with four continuous servo motors and two ultrasonic sensors. It's run by and UNO board with a Sensor Shield V5 on top.
My goal is to program the front right and front left sensors to both be returning distances in inches, and have the robot turn in the direction with the most room when one of the sensors returns a distance less than some minimum.
I am very confident that the motors and sensors aren't the issue, as testing them by themselves shows no issues. However, when I run the below code the robot stutters, mainly just going backwards but stuttering forwards and occasionally turning for a second or two. Any ideas what's going on?

#include <Servo.h>

Servo FL;
Servo FR;
Servo BL;
Servo BR;

const int FRecho = 11;
const int FRtrig = 10;
const int FLecho = 9;
const int FLtrig = 8;

long durationFL;
long durationFR;
int distanceInchR = 24;
int distanceCmR;
int distanceInchL = 24;
int distanceCmL;

const int minDistanceInch = 18;
const int minDistanceCm;

enum movementStates {
 STILL,
 FORWARD,
 BACK,
 TURNFR,
 TURNFL,
 NOTHING
};

enum movementStates movement;

void setup() {

  FL.attach(4);
  FR.attach(5);
  BL.attach(6);
  BR.attach(7);

  pinMode(FRtrig, OUTPUT);
  pinMode(FRecho, INPUT);
 pinMode(FLtrig, OUTPUT);
  pinMode(FLecho, INPUT);

  movement = NOTHING;

  forward();

}

void loop() {

updateDistanceFL();
updateDistanceFR();

updateDirection();

}

void forward () {
  FL.write(180);
  FR.write(0);
  BL.write(180);
  BR.write(0);
  movement = FORWARD;
}

void turnFR () {
  FL.write(180);
  FR.write(180);
  BL.write(180);
  BR.write(180);
  movement = TURNFR;
}

void turnFL () {
  FL.write(0);
  FR.write(0);
  BL.write(0);
  BR.write(0);
  movement = TURNFL;
}

void backUp () {
  FL.write(0);
  FR.write(180);
  BL.write(0);
  BR.write(180);
  movement = BACK;
}

void still () {
  FL.write(90);
  FR.write(90);
  BL.write(90);
  BR.write(90);
  movement = STILL;
}

void updateDirection() {

  if (distanceInchR < minDistanceInch && distanceInchL < minDistanceInch) {
    if (movement != BACK) {
      backUp();
    }
    else if (distanceInchR < minDistanceInch) {
     if (movement != TURNFL) {
      turnFL();
     }
    }
    else if (distanceInchL < minDistanceInch) {
     if (movement != TURNFR) {
      turnFR();
     }
    }
    else if (distanceInchR > minDistanceInch && distanceInchL > minDistanceInch)
    if (movement != FORWARD) {
      forward();
    }
  }
    else {
      if (movement != STILL) {
        still();
      }
    }
}

void updateDistanceFR(){
digitalWrite(FRtrig, LOW);
delayMicroseconds(2);
digitalWrite(FRtrig, HIGH);
delayMicroseconds(10);
digitalWrite(FRtrig, LOW);
durationFR = pulseIn(FRecho, HIGH);
distanceCmR= durationFR*0.034/2;
distanceInchR = durationFR*0.0133/2;
  }

void updateDistanceFL(){
digitalWrite(FLtrig, LOW);
delayMicroseconds(2);
digitalWrite(FLtrig, HIGH);
delayMicroseconds(10);
digitalWrite(FLtrig, LOW);
durationFL = pulseIn(FLecho, HIGH);
distanceCmL= durationFL*0.034/2;
distanceInchL = durationFL*0.0133/2;
  }

your updateDirection logic doesn't quite work the way you think it does.

after a bit of code formatting and comments it looks like this:

void updateDirection() {

    if (distanceInchR < minDistanceInch && distanceInchL < minDistanceInch) {
        if (movement != BACK) {
            backUp();
        } else if (distanceInchR < minDistanceInch) {
            //always entered if movement == BACK
            if (movement != TURNFL) {
                turnFL();
            }
        } else if (distanceInchL < minDistanceInch) {
            //never entered
            if (movement != TURNFR) {
                turnFR();
            }
        } else if (distanceInchR > minDistanceInch && distanceInchL > minDistanceInch)
            //never entered
            if (movement != FORWARD) {
                forward();
            }
        //endif distanceInchR < minDistanceInch && distanceInchL < minDistanceInch
    } else {
        // entered when distanceInchR > minDistanceInch || distanceInchL > minDistanceInch
        if (movement != STILL) {
            still();
        }
    }
}

it looks like you had a missing closing brace around the first condition. Causing the only movement functions that get called to be backUp, turnFL and still.

If we add the missing braces then it looks much better:

void updateDirection() {

    if (distanceInchR < minDistanceInch && distanceInchL < minDistanceInch) {
        if (movement != BACK) {
            backUp();
        }
    } else if (distanceInchR < minDistanceInch) {
        if (movement != TURNFL) {
            turnFL();
        }
    } else if (distanceInchL < minDistanceInch) {
        if (movement != TURNFR) {
            turnFR();
        }
    } else if (distanceInchR > minDistanceInch && distanceInchL > minDistanceInch) {
        if (movement != FORWARD) {
            forward();
        }
    } else {
        if (movement != STILL) {
            still();
        }
    }
}


Getting an error while uploading code to Arduino when ESP8266 is attached I am trying to use an ESP8266 and an Arduino to access the Arduino from the network. I tried to do something but I'm facing some challenges. I hope I am using the correct board "Generic ESP8266 Module".

#include <SoftwareSerial.h>

const byte rxPin = 2; // Wire this to Tx Pin of ESP8266
const byte txPin = 3; // Wire this to Rx Pin of ESP8266

// We'll use a software serial interface to connect to ESP8266
SoftwareSerial esp8266(rxPin,txPin);

void setup() {
  Serial.begin(9600);
  esp8266.begin(9600);
  delay(1000);
}

void loop() {
  Serial.println("Sending an AT commands");
  esp8266.println("AT");
  delay(30);
  while(esp8266.available()) {
    String data = esp8266.readStringUntil('\n');
    Serial.println("Got response from esp8266: " + data);
  }
}

Error

Archiving built core (caching) in: C:\Users\XYZ~1\AppData\Local\Temp\arduino_cache_322251\core\core_esp8266_esp8266_generic_CpuFrequency_80,FlashFreq_40,FlashMode_dio,UploadSpeed_115200,FlashSize_512K64,ResetMethod_ck,Debug_Disabled,DebugLevel_None_____feb0d75f3cf4e05271af4f91549cd009.a
Sketch uses 226657 bytes (52%) of program storage space. Maximum is 434160 bytes.
Global variables use 32464 bytes (39%) of dynamic memory, leaving 49456 bytes for local variables. Maximum is 81920 bytes.
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed
error: espcomm_upload_mem failed

First off you have the wrong board selected. It's the Arduino Uno that you are programming, not the ESP8266. Just because you have connected an ESP8266 to the Arduino doesnt't magically change what the Uno is.

Secondly you cannot have anything connected to pins 0 and 1 of the Arduino while programming. Those pins are used for communication with the PC. As a general rule it is best to never use ghem for anything.

To communicate between the Arduino and the ESP8266 you should either pick two other pins and use SoftwareSerial or invest in a board that has at least one independent UART (such as the Mega2560 or the Leonardo).


Delay() function and I2C interrupt In my design, one arduino pulls a line high on other arduino, the other arduino polls this pin and if that is high sends the data on I2C bus.

The first arduino holds the line high for 100ms using the delay() method, the other arduino is sending the data during this time, but the I2C receive interrupt is not being triggered.

I have attached a sequence diagram for a better explanation for what is happening.

I suspect that the delay() method somehow is disabling the I2C ISR from triggering.

Sorry guys, I made a very silly mistake here, i was using Serial.print here in ISR, following the Slave_Receiver example in the Arduino examples. I got a bit carried away with the use of those Serial debug messages and added lots of them,

I got this info from
https://stackoverflow.com/questions/17985830/arduino-using-interrupts-freezes-processing-and-serial-output

checkout answer by elias

The code does not freeze now. Sorry for the troubles, i hope this helps someone else in return.


WebSocketsServer.h: No such file or directory I'm trying use the NodeMCU WebSocket.

I downloaded the required libraries from:
https://github.com/Links2004/arduinoWebSockets
and pasted them in my Arduino libraries folder. I uploaded my code but got this error:

WebSocketsServer.h: No such file or directory.

Can you please tell me why my Arduino IDE won't find the WebSocketsServer.h header file when it is physically present in my Arduino libraries folder?   Or if there's an alternative way to use the NodeMCU WebSocket?

Here's the code:

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

// Replace with your network credentials
const char* ssid = "<WiFi-SSID>";
const char* password = "WiFi-PASSWORD";

WebSocketsServer webSocket = WebSocketsServer(81);
ESP8266WebServer server(80);   //instantiate server at port 80 (http port)

String page = "";
int LEDPin = D5;

void setup(void){
 //the HTML of the web page
 page = "
Simple NodeMCU Web Server

<button>ON</button>&nbsp;<button>OFF</button>
";
 //make the LED pin output and initially turned off
 pinMode(LEDPin, OUTPUT);
 digitalWrite(LEDPin, LOW);

 delay(1000);

 Serial.begin(115200);
 WiFi.begin(ssid, password); //begin WiFi connection
 Serial.println("");

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

 Serial.println("");
 Serial.print("Connected to ");
 Serial.println(ssid);
 Serial.print("IP address: ");
 Serial.println(WiFi.localIP());

 server.on("/", [](){
    server.send(200, "text/html", page);
 });

 server.on("/LEDOn", [](){
    server.send(200, "text/html", page);
    digitalWrite(LEDPin, HIGH);
    delay(1000);
 });

 server.on("/LEDOff", [](){
    server.send(200, "text/html", page);
    digitalWrite(LEDPin, LOW);
    delay(1000);
 });

 server.begin();
 webSocket.begin();
 webSocket.onEvent(webSocketEvent);

 Serial.println("Web server started!");
}

void loop(void){
  webSocket.loop();
  server.handleClient();
  if (Serial.available() > 0){
    char c[] = {(char)Serial.read()};
    webSocket.broadcastTXT(c, sizeof(c));
  }
}

void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length){
  if (type == WStype_TEXT){
   for(int i = 0; i < length; i++) Serial.print((char) payload[i]);
   Serial.println();
  }
}
~~~

after you included the zip file to library you must rename directory like this 'WebSocketsServer'. And then you copy all file in 'src' directory and then paste them to its parent directory (WebSocketsServer)


Dynamic SSID + Password from ESP8266WiFi I'm using the ESP8266WiFi library on a NodeMCU, running the arduino bootloader in the arduino software (Windows 10 app version).

I'm trying to load the SSID and password from SD-card (this part is successfull).

My problem this far is when i use the Wifi library it looks like this:

 Wifi.begin(const char*, const char*);

Since it takes 2 const parameters i cannot change it later. Is there anyway i can add SSID and PASSWORD to my sketch without having to recompile it. (I have to send it to people who does not know how to compile and flash an arduino)

I'm not attached to the ESP8266WiFi library, i'm not attached to SD-card, other solutions are welcome.

SD-reader works as planned, WiFi works as planned with a static password and SSID.

The const keyword there does not force the data you call it to be constant, it only forbids certain assignments with the parameters inside that function but it's just superfluous in most cases. Meaning you can call it with input you got from serial or some other source (for ex. setup page accessible from hotspot->Store in EEPROM->Next boot connect to set WiFi AP). There's also a nice StackOverflow thread about this here and why it's not actually a good idea in many cases.


Arduino Convert std:string to String I'm working on BLE project with espressif library. And It returns me founded BLE device.

std::string getManufacturerData();
std::string getName();
int         getRSSI();
BLEScan*    getScan();

When I want to print device name to serial port

BLEAdvertisedDevice founded_dev;
founded_dev=foundDevices.getDevice(0);
Serial.println("Name -> " + founded_dev.getName());

It gives me error like this

no matching function for call to 'HardwareSerial::println(std::__cxx11::basic_string<char>)'

So how can i convert to std:string to String in Arduino?

Don't. Instead just access the underlying C string:

Serial.print(F("Name -> "));
Serial.println(founded_dev.getName().c_str());


Digital Pins reads 1 when configured with internal_pullup I work with Arduino DUE. I would like to configure few of my digital pins as INPUT pins. When the µc sets these particular 4 pins , the DUE must be activated. Something like a DATAREADY pin in the SPI,where the data will be sent to the slave only,when it sets the pin to 1.

According to the datasheet , the external µC would set the pin state from 0 to 1. I tried this program for experimenting the effect of digital pins,

int RDY = 52;
void setup() {

 Serial.begin(9600);
pinMode(RDY,INPUT_PULLUP);
pinMode(50,INPUT);
digitalWrite(RDY,HIGH);

}

void loop() {

digitalRead(RDY);
digitalRead(50);
digitalRead(11);
digitalRead(12);

Serial.println(digitalRead(RDY));
Serial.println(digitalRead(50));
Serial.println(digitalRead(11));
Serial.println(digitalRead(12));

delay(100);
}

Results obtained are; 1,1,0,0 as expected. I cannot find a proper way to detect the change of state of the pin (from 0 to 1). To make detect changes, I connected/disconnected the 5V output pin of DUE to the particular digital pins. The results never changed with connection and disconnection of the 5V wire for any pin.

Is there any possible way to detect the change of the pin state as in INPUT mode in Arduino DUE?
Most examples are dealing with switches,but in my case I need a pin as a input.

Thanks

There is no difference between a switch and a "pin" for input. All are either HIGH or LOW. You tie it HIGH with the pullup, and then try giving it a HIGH with +5V (Caution: The Due is a 3.3V device, not 5V!).

At no point do you ever give it a LOW signal (connect the input to GND), so how can it ever read LOW?


Get strings from Serial.read() I want to read strings from Serial.read() to send them later.

To get the data from the Serial monitor I'm doing this:

String stringOne  = "";
int  incomingByte;

if (Serial.available() > 0) {

  while(Serial.available() > 0)
  {
     incomingByte= Serial.read();
     stringOne = String(stringOne + String(incomingByte));
  }

  Serial.println(stringOne);
  stringOne = "";

The issue is that when I type:

'a'

I got:

'97'

for
    'abc'

I got

'979899'

so on and so forth.

What should I do in order to get the same string I type?

You're adding the ASCII value of each char to your string, hence you get numbers. See the various String constructors at:
https://www.arduino.cc/en/Tutorial/StringConstructors

Either cast the read byte to a char:

stringOne = String(stringOne + String((char)incomingByte));

or consider receiving characters as chars, instead of ints:

char incomingByte;

There is a perfectly valid one-method call which does all of this hassle easier and more efficiently: https://www.arduino.cc/en/Serial/ReadStringUntil

Note that you'll sooner or later anyhow have to add a framing prototcol. For example, you're sending down text commands to Arduino, and each command is separated by a new line character. ReadStringUntil will handle that very nicely.


Accelerometer Z Value off a significant amount, all other values reasonable I'm using the MPU9255 Accelerometer to measure acceleration in the X,Y, and Z directions.  As per the datasheet, I've applied a scaling to the raw digital values based off of whether I specified +- 2G, +- 4G, +- 8G etc.  This scaling works fantastically, but there is consistent noise on the Z axis, far greater than that of gravity's 1G of force.  Here is a sample output

ACCELEROMETER-X
0.7226562500
ACCELEROMETER-Y
0.1523437500
ACCELEROMETER-Z
7.9707031250

ACCELEROMETER-X
0.7460937500
ACCELEROMETER-Y
0.1875000000
ACCELEROMETER-Z
8.0468750000

As you can see, there is about 7G of noise on the Z axis. I calculated the scaling with this code:

//Get accelerometer scaling based off of how many G's per of variation the system was tuned to handle
int16_t getAccScalar(int16_t system_scale){
  int16_t acc_scalar = 16384;
  short scalar = 1;
  if(system_scale == ACC_FULL_SCALE_4_G){
    scalar = 2;
  }
  else if(system_scale == ACC_FULL_SCALE_8_G){
    scalar = 4;
  }
  else{
    scalar = 8;
  }
  acc_scalar /= scalar;
  return acc_scalar;
}

And then in configuration I use a register writing function with this header:

void I2CwriteByte(uint8_t Address, uint8_t Register, uint8_t Data)

and call it with these values

I2CwriteByte(MPU9250_ADDRESS,28,ACC_FULL_SCALE_2_G);

Anyone know why this is happening? Thanks and have a squanchy day.

Accelerometer static errors are usually not anywhere near that large, so I suspect your scaling code is not behaving correctly. You could verify this by turning the accelerometer on its side and see if the Z axis retains a +7G value, or if the X/Y axis instead becomes too large.


Can't burn bootloader through Arduino Nano clone ISP to atmega328p I'm trying to use a Nano v3 as ISP to program an atmega328p on a board with ISP headers:

I followed the instructions under
https://www.arduino.cc/en/Tutorial/ArduinoISP which I think have been recently updated. I'm simply connecting ISP headers together except for D10 from programmer to reset on the target AVR.

The ISP sketch seems to be working fine as far as I can see the heartbeat pulsing a led. But when trying to burn bootloader with settings:

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

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x14

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x01
avrdude: stk500_initialize(): (a) protocol error, expect=0x14, resp=0x10
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

avrdude: stk500_disable(): unknown response=0x12
Error while burning bootloader.

I noticed something weird though, the 5V and GND on the ISP header on the programmer nano only has around 0.4V. This even without anything external but the usb connected. Is my nano broken or is the usb connection not able to deliver enough power?

Your slave micro isnt resetting when your master wants it to reset.

Ie: master sends a reset signal before initiating further communication, and it seems that your slave not being reset.

So its not responding.

Once cross check your isp signal lines.


OLED on Hardware SPI, on DUE I want to use an OLED with DUE.
I plan to connect it via hardware SPI.
The Due has a 3X2 pin connector labeled SPI. Is it here where i connect the SCK and MOSI?

If indeed, i connect it here, then which one is SCK and which one is MOSI?

Most importantly, i saw somewhere that in the DUE, hardware digital pin 13 is SCK and pin 11 is MOSI?
Is this true? Because if it is, i can simply hook it up to these pins and get rid of the confusing 3X2 pin connector.

It doesn't look like it's true. There is only one SPI module and it has fixed pins which are not duplicated anywhere.

However there are three instances of USART which can be used in synchronous mode as SPI:

USART0: RXD0(PA10) / TXD0(PA11) / SCK0(PA17)
USART1: RXD1(PA12) / TXD1(PA13) / SCK1(PA16)
USART2: RXD2(PB21) / TXD2(PB20) / SCK2(PB24)

Whole table from SAM3X datasheet:

But I'm not sure if the Arduino IDE supports this mode, or you'll have to do it from scratch by yourself.

You can even use RTS as select slave signal:


Is my Arduino Ethernet Shield broken? I have an Arduino setup from which I can control my RGB LED strip from my computer using LAN.
It worked like a charm in the start, but after two days, my Ethernet Shield W5100 for Arduino Uno stopped working, and I can't figure out why.
When I connect the Ethernet Shield, the red LED "pwr" is solid red and the "FULLD" flashes orange every second.
The setup:
I have followed an Adafruit guide, connecting the Arduino as such:
On top of the Arduino, I have the Ethernet Shield. All this is powered by an 12V/4A power supply connected to the Arduinos 2.1mm jack.
As I said, this setup worked fine for a few days. While it was on, I noticed the Arduino getting somewhat hot, but some google searches assured me that Arduino Uno can handle high temperatures, so I did not pay any attention to it.
The LED strip is not too long - about 2 meters with about 150 LEDs.
What I have tried:

When I detach the Arduino from my breadboard, the Ethernet Shield
will still not connect
I have tried connecting the Shield to another Power Supply (Computer USB) using another Arduino, but the Shield would still not connect.
I have added a debugging Serial.print message in the Arduino loop function. When using serial monitor, this message is printed over and over again (as if it is stuck in a reset loop)
I have verified for MAC address collisions, even changed the MAC address of the Shield multiple times.

Have I somehow burned the Ethernet Shield? Why won't it work anymore?

I'm sorry to tell you but i think you damaged your board severely that's because you took more energy from the pins than an arduino can handle.

150 LEDs takes way too much power for the arduino to handle as you can see here.

So you likely burnt something on your board and might have to replace it :/
make sure which board is damaged(the arduino itself or the shield) before replacing it.

If the ATmega328P(The chip on the arduino) is damaged then this should be an easy fix.

Instead of what you did, you shoud have powered the LED strip from another power supply(not from the arduino pins) and used the arduino to turn "this power supply" on and off(probably using transistors).


Using ESP8266-01 with Arduino uno R3 I am trying to learn how to use ESP-01(AI-Cloud, Black Version) with arduino

Initially, I created an adapter for it that has 4 inputs: RX, TX, Vcc(3.3v), GND I checked it and the wiring seems fine then I attached TX of arduino to TX of ESP and same with RX but with a voltage divider (1k ohm,2kohm),I uploaded arduino with a blank sketch and tried to run commands like AT and AT+CWMODE? but I got no response on the serial monitor.I tried to look for a proper tutorial to do this but, all tutorials show how to upload a sketch to ESP rather than arduino. Then I searched and found this piece of code:

#include <SoftwareSerial.h>

#define DEBUG true

SoftwareSerial esp8266(2,3); // make RX Arduino line is pin 2, make TX Arduino line is pin 3.
                            // This means that you need to connect the TX line from the esp to the Arduino's pin 2
                            // and the RX line from the esp to the Arduino's pin 3
void setup()
{
 Serial.begin(9600);
 esp8266.begin(115200); // your esp's baud rate might be different

 sendData("AT+RST\r\n",2000,DEBUG); // reset module
 sendData("AT+CWMODE=2\r\n",1000,DEBUG); // configure as access point
 sendData("AT+CIFSR\r\n",1000,DEBUG); // get ip address
 sendData("AT+CIPMUX=1\r\n",1000,DEBUG); // configure for multiple connections
 sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // turn on server on port 80
}

void loop()
{
 if(esp8266.available()) // check if the esp is sending a message
 {
   /*
   while(esp8266.available())
   {
     // The esp has data so display its output to the serial window
     char c = esp8266.read(); // read the next character.
     Serial.write(c);
   } */

   if(esp8266.find("+IPD,"))
   {
    delay(1000);

    int connectionId = esp8266.read()-48; // subtract 48 because the read() function returns
                                          // the ASCII decimal value and 0 (the first decimal number) starts at 48

    String webpage = "
Hello
&lth2>World!
<button>LED1</button>";

    String cipSend = "AT+CIPSEND=";
    cipSend += connectionId;
    cipSend += ",";
    cipSend +=webpage.length();
    cipSend +="\r\n";

    sendData(cipSend,1000,DEBUG);
    sendData(webpage,1000,DEBUG);

    webpage="<button>LED2</button>";

    cipSend = "AT+CIPSEND=";
    cipSend += connectionId;
    cipSend += ",";
    cipSend +=webpage.length();
    cipSend +="\r\n";

    sendData(cipSend,1000,DEBUG);
    sendData(webpage,1000,DEBUG);

    String closeCommand = "AT+CIPCLOSE=";
    closeCommand+=connectionId; // append connection id
    closeCommand+="\r\n";

    sendData(closeCommand,3000,DEBUG);
   }
 }
}

String sendData(String command, const int timeout, boolean debug)
{
   String response = "";

   esp8266.print(command); // send the read character to the esp8266

   long int time = millis();

   while( (time+timeout) > millis())
   {
     while(esp8266.available())
     {

       // The esp has data so display its output to the serial window
       char c = esp8266.read(); // read the next character.
       response+=c;
     }
   }

   if(debug)
   {
     Serial.print(response);
   }

   return response;
}

I hooked pins according to the code and it worked serial monitor output some lines but with allot of garbage values, This also created a wifi hotspot 'AI-Thinker' which I connected to and opened Ip as shown on debugging. This made ESP try to send string 'webpage' but mostly was garbage.

so my question is, how to properly use esp with arduino to maybe just switch an led on or send data from sensors, super basics?

Is it better to use esp Library and upload sketches to esp and control arduino with it?

Can some one suggest the proper tutorial for this? because even after all this I am still confused that is RX of arduino connected to RX(which makes no sense but given in many of google images) or TX of ESP-01?

To confirm that the serial communication is working, connect the ESP to the Arduino D10 and D11 that is used as SoftSerial pins.

+----+
| PC |
+--/-+
   |       +---------+
   \-------| Arduino |
     USB   +--.------+
              | SoftSerial
              |
           +--\----+
           | ESP01 |
           +-------+

And then upload this code to the Arduino. The code is from https://www.arduino.cc/en/Tutorial/SoftwareSerialExample

/*
 Receives from the hardware serial, sends to software serial.
 Receives from software serial, sends to hardware serial.

 The circuit:
 * RX is digital pin 10 (connect to TX of ESP01)
 * TX is digital pin 11 (connect to RX of ESP01)

 Created back in the mists of time
 modified 25 May 2012
 by Tom Igoe
 based on Mikal Hart's example

 This example code is in the public domain.
 */

#include <SoftwareSerial.h>

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

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

  Serial.println("Goodnight moon!");

  // Set the data rate for the SoftwareSerial port
  mySerial.begin(115200);
  mySerial.println("Hello, world?");
}

void loop() {

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


Arduino RF24 library Delay after write function causes no byte availability It's about the RF24 library you can find here. http://maniacbug.github.io/RF24/index.html

I transmit data from one Arduino to another using NRF24L01 radios.
When I use the write-function on the transmitter arduino (joystick is an array) and after that I put in a delay higher then 10, the available function returns false.

Transmitter

radio.write( joystick, sizeof(joystick) );
delay(20);

Receiver

if(!available())
  print('No data'); // delay > 10 --> No data will be printed

Why is it working with a delay of 10 but not above? Has it something to do with timeouts which is mentioned in the docs of the library?: http://maniacbug.github.io/RF24/classRF24.html#a4cd4c198a47704db20b6b5cf0731cd58

Thank you for your answers.

In my situation the issue was with the Transmitter not continuing to transmit after a delay. I was able to resolve the issue using the powerDown (http://maniacbug.github.io/RF24/classRF24.html#aa0a51923a09ba4f3478aba9be0f8a6a1) and powerUp (http://maniacbug.github.io/RF24/classRF24.html#a5cdaf47aa0edd6dca1b9a8bb7972a1a3) functions. Here is a snipet of my code. "radioTx" is the name assigned to my transmitter.

//standard code setup for arduino uno board examples
radioTx.begin();
radioTx.setChannel(108);
radioTx.openWritingPipe(pipe);

}

void loop() {

  int dist_cm = sonar.ping_cm();

  Serial.println(dist_cm);
  radioTx.write(&dist_cm,sizeof(dist_cm));
  radioTx.powerDown();
  delay(5000);
  radioTx.powerUp();

  }


Can I leave AVcc disconnected? I am using ATmega8A standalone but analog pins (Port C) have not been use.

Due to ATmega8A does not have a PRR (Power Reduction Register) to disable ADC and TWI.

I would like to know, is it a work around solution to reduce the power consumption if AVcc is not connected?

No. You must connect AVcc even if you're not using the ADC.  According to the datasheet:

  AVCC is the supply voltage pin for the A/D Converter, Port C (3:0), and ADC (7:6). It should be externally connected to VCC, even if the ADC is not used. If the ADC is used, it should be connected to VCC through a low-pass filter. Note that Port C (5:4) use digital supply voltage, VCC.


Connecting arduino to an existing circuit I have a little clock with a button on it that i need to push four times every second hour. I am trying to get the arduino micro to do it for me.

I am trying to figure out how to connect the arduino to trigger it. The clock is operated by a CR2 (3.0V) cell battery. Is there a way to do this without a transistor? If not what do i need? How can i find out how much amp my circuit requires?

The red arrow is pointing on the cable i think triggers the clock, and i think the black arrow is pointing on the cable that is the clock gnd.

(edit: I have found similar questions explaining the process with transistor, but not without..)

Yes, This can be achieved without a transistor.

As the circuits would be on isolated power supplies: Arduino circuit on one and the clock on another, you can use a Solid State Relay.

Use the relay with your Arduino (5v or 3.3v) and wire the relay contacts parallel to the clock switch. This will isolate any power issues as clock will be powered with its own power and Arduino will be powered with its own.

You can program Arduino with proper delays to actuate the relay accordingly.

Hope this helps.


How to detect the direction of rotation with a sensor encoder timing disk (photoelectric speed sensor)? I am making a DIY gaming steering wheel and am stuck.
For measuring the rotation of the wheel, I'm using a sensor encoder timing disk, which is usually found in printers. - https://robu.in/product/photoelectric-speed-sensor-encoder-coded-disc-code-wheel.

A lot of tutorials on youtube use this.
But I just cannot seem to understand how to use this sensor.

Please help me in figuring this out: using this sensor, how to -

Measure how much the wheel rotated?
Know which direction did the wheel rotates in (clockwise, anti-clockwise).

PS: I tried using a rotatory encoder, but it is unable to sense rotation when rotated by a 1000 RPM motor. Would love to understand why.

Thanks!

It seems to be a A/B coding : if A gets high before B, it's one way (count for exemple), and if B gets high before A, it's other way (decount).
So, connect power and ground. Then connect the two wires to input pins :

    int P_A=2; int P_B=3; //Inputs
    long int position = 0; //Position of wheel
    long int lastPosition = 0; //last position of wheel : for speed computing

Notice that one pin must be an hardware interrupt pin (Uno 2 an 3 are interrupt pins. Then attach interrupt in the stup :

    attachInterrupt(2, wheel, RISING);  //wheel is arbitray

Then create the interruption code :

    void wheel(){
        int sB = digitalRead(P_B);
        if (sA == sB)   { //Clockwise
        position++;
        }
        else   { //Counterclockwise
        position--;
        }

Then, in your loop, you can print position when it changes to read current position :

    if(lastPosition != position){
        Serial.println(position);
    }

i hope it will help...
Notice that if you use both interruptions, you get a better resolution, but speed limit is lower.


Mega 2560 powered with 7V don't work correctly I have an Arduino Mega 2560  with a GPRS seeedstudio shield and an USB Host CircuitsAtHome shield which work fine when powered with USB or with an adjustable voltage regulator set at 8V.

When I set this voltage regulator at 7V (minimum voltage from the spec to get the better efficiency) I am still reading 5V and 3.3V on the pins of the Arduino and all the leds of the Arduino and the GPRS shield seems fine but the USB Host CircuitsAtHome shield seems to not work properly.
I cannot debug it using the console because if I plug the USB cable, everything works fine...

Why 7V fail while 8V is ok?

The adjustable voltage regulator can provide up to 5A which is plenty.

The Voltage-Regulator has a dropout-voltage of 1,2V, but in line to the regulator is a diode, which adds another minimum 0,7V (dont know the exact part number, so i guessed the voltage of a Si-diode at ~1A). So you have to supply at least 5 + 1,2 + 0,7 = 6,9V. I presume the circuit doesnt draw a constant current all the time, so from time to time the regulator cant supply the 5V because you sink under the necessary dropout-voltage of the rehulator/diode-combination.

-> Use 8V  or bypass the Diode D1 (with a solder-bridge) and use 7V if its a must and you are sure the input-polarity is always correct.

Arduino-Mega-2560-schematic: http://arduino.cc/en/uploads/Main/arduino-mega2560_R3-sch.pdf


Can you use Serial Port as a variable? I am doing a project where, for troubleshooting reasons, I find myself often swapping components to different serial ports. Maybe one time it's in Serial, then in Serial1, maybe I need to try if software serial works.
But changing every line where Serial.print or Serial.write is written for the new port is a hassle and easy to screw up.
Would it be possible to either create a definition at the beginning of the code that lets me rename Serial to SensorSerial so just by changing that definition I am sure it will use the correct port?

Majenko's answer is the right answer for your question. But to answer the title of the question, if you ever need to use different Arduino outputs and inputs as variable, most of them have common type Stream or Print. So it would be:
Stream& SensorSerial = Serial;

or
Stream* SensorSerial;
SensorSerial = &Serial;

The Arduino Stream classes hierachy:


Custom ATMega 2560 board won't execute Arduino code I have a custom PCB with an ATMega 2560 microcontroller on it. To test if the ATMega was working properly, I uploaded the following code:

void setup() {
  Serial.begin(9600);
  Serial.println("Test setup");
  pinMode(6, OUTPUT);
  pinMode(30, OUTPUT);
  pinMode(31, OUTPUT);
  pinMode(32, OUTPUT);
}

void loop() {
  digitalWrite(6, HIGH);
  digitalWrite(30, HIGH);
  digitalWrite(31, LOW);
  digitalWrite(32, HIGH);
}

The mentioned ports are connected to LEDs, 6 to an external LED and 30, 31 and 32 to LEDs on the PCB. Each connected in series with a 220 Ohm resistor.

The board is setup like this:

When uploading I am using a Arduino UNO as ISP and after uploading the Arduino IDE says 'Done uploading' without any errors, but the board is not showing any sign of executing the code. I have checked that VCC is 5V and RESET is HIGH after uploading. The text "Test setup" is also not shown on the serial monitor.

Does anybody have a clue why the board is not working?

Thanks on forehand.

When using an empty ATMega2560 you need to change the fuse settings, otherwise it will just upload your code but it won't execute.
This tutorial explains it very clearly:
Programming ATMega 2560 with Arduino UNO


nodeMCU - 2 loops at a time - one continuously and second every 10 seconds i have nodeMCU v3(esp8266) so i need to make 2 checks
1 check is the pin D1 which needs to be done continuously  and another check is web link check every 10 seconds,
problem is coz when i put delay then it stops the first check

void loop() {

 if (digitalRead(pinD1)==1){
       digitalWrite(pinD0, HIGH);
       delay(20000);
 }else{
       digitalWrite(pinD0, LOW);
 }

      loop2();

}

void loop2(){
   if (json1=="ON"){
    digitalWrite(pinD0, HIGH);
      delay(20000);
}else{
     digitalWrite(pinD0, LOW);
               delay(10000);

  }
}

Rather than using delay, use millis() and a variable to check if the some time has expired

void loop()
{
    static int check = 0;
    int now = millis();
    if (now >= check) {
        if (digitalRead(pinD1)==1){
            digitalWrite(pinD0, HIGH);
            check = now + 20000;
        } else {
            digitalWrite(pinD0, LOW);
            check = now;
        }
    }
    loop2();
}

void loop2()
{
    static int check = 0;
    int now = millis();
    if (now >= check) {
        if (json1=="ON"){
            digitalWrite(pinD0, HIGH);
        } else {
            digitalWrite(pinD0, LOW);
        }
        check = now + 20000;
    }
}


Reading updated serial data from ESP8266 I have connected my ESP8266 to my Arduino Uno on pin 2 & pin 3 as RX & TX. I adjusted the baud rates and I have no issue receiving the data from the ESP8266.

The ESP8266 gets connected as a client to a server and grabs the likes count of a Facebook page. The data on the ESP8266 serial port is updated correctly every time the ESP sends a get request to the server to get the updated likes count of a particular Facebook page.

Unfortunately I'm not receiving this updated likes count on my Arduino serial port. I'm always receiving the same likes count. I have to close the serial window and open it again to receive the new count. Or reset the Arduino itself to receive the new likes count.

So why isn't it posting the latest likes count sent from the ESP to the Arduino instantly without having to reset the Arduino? Maybe I have an issue in the void loop().

Because I display this data on an external display and I need it to be updated without me needing to reset the Arduino every time to receive the latest count.

void loop() {
  char c;
  while (esp8266.available() && c != '\n') {
    c = esp8266.read();
    response += c;
  }
  //If end of line
  if (c == '\n') {
    //Getting the likes string only
    if(likes = response.substring(response.indexOf("Likes:")+6, response.indexOf("::"))) {
      //Filtering some unneeded strings
      if((strstr(likes.c_str(), "URL")) == NULL) {
        currentLikes = atol(likes.c_str());
        Serial.print(currentLikes);
        //Printing likes count on serial port
      }
      Serial.println();
    }
  }
}

Thank you everyone I had to just clear the response string every time.

I have just added response = ""; after the Serial.print(currentLikes);


PC8563 Arduino interface i am trying to interface pc8563 with arduino uno . I have small doubt related to RTC slave address reading

RTC datasheet says page no 14
where device slave address is A2 for write and Read A3
i would like to know how A2 /A3

Example code from website device id mentioned as 0X51

My question how to config exact slave address ??

#include "Wire.h"
#define PCF8563address 0x51

byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;
String days[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };

byte bcdToDec(byte value)
{
  return ((value / 16) * 10 + value % 16);
}

byte decToBcd(byte value){
  return (value / 10 * 16 + value % 10);
}

void setPCF8563()
// this sets the time and date to the PCF8563
{
  Wire.beginTransmission(PCF8563address);
  Wire.write(0x02);
  Wire.write(decToBcd(second));
  Wire.write(decToBcd(minute));
  Wire.write(decToBcd(hour));
  Wire.write(decToBcd(dayOfMonth));
  Wire.write(decToBcd(dayOfWeek));
  Wire.write(decToBcd(month));
  Wire.write(decToBcd(year));
  Wire.endTransmission();
}

void readPCF8563()
// this gets the time and date from the PCF8563
{
  Wire.beginTransmission(PCF8563address);
  Wire.write(0x02);
  Wire.endTransmission();
  Wire.requestFrom(PCF8563address, 7);
  second     = bcdToDec(Wire.read() & B01111111); // remove VL error bit
  minute     = bcdToDec(Wire.read() & B01111111); // remove unwanted bits from MSB
  hour       = bcdToDec(Wire.read() & B00111111);
  dayOfMonth = bcdToDec(Wire.read() & B00111111);
  dayOfWeek  = bcdToDec(Wire.read() & B00000111);
  month      = bcdToDec(Wire.read() & B00011111);  // remove century bit, 1999 is over
  year       = bcdToDec(Wire.read());
}

void setup()
{
  Wire.begin();
  Serial.begin(9600);
  // change the following to set your initial time
  second = 0;
  minute = 28;
  hour = 9;
  dayOfWeek = 2;
  dayOfMonth = 13;
  month = 8;
  year = 13;
  // comment out the next line and upload again to set and keep the time from resetting every reset
  setPCF8563();
}

void loop()
{
  readPCF8563();
  Serial.print(days[dayOfWeek]);
  Serial.print(" ");
  Serial.print(dayOfMonth, DEC);
  Serial.print("/");
  Serial.print(month, DEC);
  Serial.print("/20");
  Serial.print(year, DEC);
  Serial.print(" - ");
  Serial.print(hour, DEC);
  Serial.print(":");
  if (minute < 10)
  {
    Serial.print("0");
  }
  Serial.print(minute, DEC);
  Serial.print(":");
  if (second < 10)
  {
    Serial.print("0");
  }
  Serial.println(second, DEC);
  delay(1000);
}

RTC datasheet

Normal I2C addresses are 7-bit long. On the first frame of an I2C
transaction, the master sends an 8-bit byte containing the address of
the slave followed by a bit specifying whether this is a read or a write
operation. Some people tend to call “address” the whole 8-bit frame,
which causes confusion. Because of this, we end up having three flavors
of I2C addresses:

the 7-bit address, which is the real device address
the 8-bit “write address”, which is the address followed by a 0
meaning “write operation”
the 8-bit “read address”, which is the address followed by a 1
meaning “read operation”

For your RTC, the 3 addresses are the following, in hex and binary:

7-bit = 0x51 = 0b1010001
write = 0xA2 = 0b10100010
read  = 0xA3 = 0b10100011

The Arduino Wire library expects the 7-bit address.


How to display tilt sensor data on an LCD? I'd like for a 16x2 LCD monitor from Sparkfun to display sensor data from a 4-directional tilt sensor from Parallax. The Arduino board is a Duemillanove. The board will run and power both programs and modules, but the serial monitor displaying the tilt sensor data will not relay the info to the LCD display. Any suggestions?

Here are the two pieces of code I am trying to get to work together—they are both from Arduino:

For the tilt:

void setup() {
   Serial.begin(9600);
}
void loop() {
   Serial.print("Photo 1: ");
   Serial.print(digitalRead(6), DEC); // Display Out 1 value
   Serial.print("; ");
   Serial.print("Photo 2: ");
   Serial.println(digitalRead(7), DEC); // Display Out 2 value
   delay(250); // Wiat 1/4 second
}

For the LCD:

#include <SoftwareSerial.h> // Attach the serial display's RX line to digital pin 2
SoftwareSerial mySerial(3,2); // pin 2 = TX, pin 3 = RX (unused)
void setup() {
  mySerial.begin(9600); // set up serial port for 9600 baud
  delay(500); // wait for display to boot up
}
void loop() {
  mySerial.write(254); // move cursor to beginning of first line
  mySerial.write(128);
  mySerial.write(" "); // clear display
  mySerial.write(" ");
  mySerial.write(254); // move cursor to beginning of first line
  mySerial.write(128);
  mySerial.write("movement recorded");
  while(1); //
  wait forever
}

Update:

I'm still tinkering with the suggested program from @Ariser shown below, but keep getting a compile error:

tilt_lcd_ase.cpp: In function ‘void loop()’:
tilt_lcd_ase.cpp:24:43: error: expected ‘)’ before ‘;’ token
tilt_lcd_ase.cpp:25:43: error: expected ‘)’ before ‘;’ token

I've done some research and one person had a similar problem, but it was within #include not void loop. The search continues, but if anyone has a suggestion please chime in. The liquid crystal library is also turning up similar errors but it needs a closer look.

The serial monitor cannot relay data from different peripheral unit in an arduino system.

I think you have certain misconception of the hard and software. Your USB connection to the microcontroller on the arduino is just a trunk for a asynchronous serial transmission. In the past this was done via a RS-232 interface.

So, what is it, that you see in your serial monitor? That's just a bunch of characters sent by the microcontroller on your arduino. This data is sent from the microcontroller, because some piece of software fills the fifo of its serial interface. In fact, such commands are executed, when you call the method "Serial.print()". Data gets then sent to your PC, Mac or whatever you are running your IDE on.

Now on the very same microcontroller the software for your tilt sensor is being executed. How could the serial monitor (which resides on your PC) route data from your tilt sensor to your LCD display? I'll tell you: It can't.

(In fact you could write a terminal script on your PC which reads data from serial and writes it back to the same interface, but it may cross your mind, that this might be a very big indirection)

So what do you wanna accomplish? You want to put data read from a device connected to your Arduino to another device connected to your Arduino. So you better tell it the Arduino. The serial monitor will not be involved, hence you won't need any calls of Serial.print() to accomplish that.

To help you with that task, we need to see the code you have written so far.

Ok. first thing you need to know: You can't have two arduino sketches running simultaneously on your arduino. This is, because there is nothing like an operating system on your arduino which might provide a scheduler to run both programs. (If you want, look up scheduler on wiki, as it is very useful to know what you can't have)

So you need two pieces of code to run on the same microcontroller (the big black thing on your arduino) one doing the tilt sensor readings and the other printing data on your display. Hence you have to make one program out of two. To accomplish this, you have two problems to solve.

you have to execute both code fragments alterantely, which, because the controller is fast enough, boils down to do both task nearly simultaneously
you have to bring the data which is acquired by code part 1 from the tilt sensor to code part 2 writing to the display. This is (for people into programming) rather simple as it simply has to be stored in a variable.

I recommend you to look up some programming basics at the arduino home page concerning the "setup" function and the "loop" function. But for now: You can have only one of each running on your arduino. Everything which is inside "setup" is executed only once after powerup. Everything which is inside "loop" is going to be executed over and over again consecutively (if nothing breaks).

Your program might look like this:

#include <SoftwareSerial.h> // Attach the serial display's RX line to digital pin 2
SoftwareSerial mySerial(3,2); // pin 2 = TX, pin 3 = RX (unused)

char gl_senstr1[15];
char gl_senstr2[15];

void setup() {
  mySerial.begin(9600); // set up serial port for 9600 baud
  delay(500); // wait for display to boot up
}

void loop() {
  mySerial.write(254); // move cursor to beginning of first line
  mySerial.write(128);
  mySerial.write(" "); // clear display
  mySerial.write(" ");
  mySerial.write(254); // move cursor to beginning of first line
  mySerial.write(128);
  mySerial.write("movement recorded");

      sprintf(gl_senstr1, "%d", digitalRead(6);
      sprintf(gl_senstr2, "%d", digitalRead(7);

  sprintf(gl_senstr1, "%d", digitalRead(6));
  sprintf(gl_senstr2, "%d", digitalRead(7));

  mySerial.write("sensor1: ");
  mySerial.write(gl_senstr1);
  mySerial.write(" sensor2: ");
  mySerial.write(gl_senstr2);

   delay(250); // Wiat 1/4 second

}

I did not test it, because I neither own your display nor that sensor. But you can give it a try. You eventually have to dive into the art of programming if you want to accomlish little more than this. This is where the rubber meets the road.


Arduino can't see any library I have installed for nrf905? nrf905\
nRF905-All-In-One-Shield\
RadioHead-master\
RadioHead\

None any of them are compiled with their examples without getting errors.

Error message:

nRF905_RX.ino:4:20: fatal error: NRF905.h: No such file or directory
compilation terminated.
Error compiling.

Libraries used:

Elechouse
RadioHead Github
RadioHead Doxygen
zkemble/nRF905

The errors you were getting when you compiled was because if the libraries were extracted straight to the Arduino library folder from the .zip, the file path becomes too long for the compiler to find it.

So what you need to do is to create a new folder in the libraries folder for each library.

Note: you cannot do the standard libraryName\src\foo.cpp as this seems to give errors for these libraries (in that it does not find them).

What you need to do is to make a file in the libraries directory; for the zkemble one you can create a main folder called nRF905, then take the files under nRF905/arduino/nRF905 from github and place them in the folder created earlier. It should look like this:

You should repeat this for the Elechouse one as well as it solved the problem too. i.e.

C:\\...\libraries\NRF\examples\
C:\\...\libraries\NRF\NRF905.cpp
C:\\...\libraries\NRF\NRF905.h
C:\\...\libraries\NRF\keywords.txt

Also of importance is that once you have the library from Elechouse compiling you need to open up the .cpp file and go to line 16, where there is

PROGMEM unsigned int freq_tab[10] = {

and to this add const, like so:

PROGMEM const unsigned int freq_tab[10] = {


Two power source for Arduino and a relay In my work, I have an ESP-8266, Arduino-Uno and a Relay. ESP 8266 and Uno is connected. Relay's data signal is take from arduino's 12th pin. ESP is powered from Uno.

If I use two different power sources for Uno and Relay, Relay does not response for the signal from Uno. (Both have a same common ground)

If relay is powered from Uno, then after load control (power on and off) ESP-8266 goes down.

The uno can't provide enough power to power an ESP8266 reliably.  I suggest you power it from a separate source.

When ever you use separate power supplies for a circuit you need to "tie the grounds together", connect them.  Otherwise the circuits don't use the same definition of zero.


Can Bluetooth HC-05 Module detect other modules and relay data back to phone? I want the following to happen:

The HC-05 is paired to a phone. The module is called "Amy". The module is worn, say, as a wristband by a person.
Amy passes another wristband-with-HC-05-module called "Bob".
Amy inquires about Bob, and if the RSSI signal received is strong, it relays the name "Bob" to the phone which will somehow store the information in an app.
The HC-05 will pass many other modules, each with different usernames. A list of names will be stored by the phone app.
All other HC-05 modules, i.e. Bob and co. , would be doing the same thing with their own phones.

How feasible is this?

Correction - BLE devices give off RSSI, but not Bluetooth. BLE devices can be used as iBeacons. I have settled on the HM-19 Bluetooth 5.0 module. A phone acts as an iBeacon scanner.


Doubt in choosing the right DC motor? Take this motor as an example - https://www.robotshop.com/en/12v-100rpm-583-oz-in-brushed-dc-motor.html

it has torque of 42kg.cm

I know all the calculation to find the payload of dc motor from here - https://www.quora.com/How-do-I-calculate-how-much-weight-can-DC-motor-carry

My main concern is the output power. Power formula is:-

power = voltage x Stall Current
      = 12 x 2A = 24W

But the specification says that the power is 5W. Which value should I use in my calculation?

With a current rating of 0.68 A at 12 V you get the normal power requirement of 8.6 W for a 7Kg.cm torque.

If, for any reason, you stall the motor, your driver must be capable to output 2.2 A or 26.5 W to avoid a permanent damage.


Stop multiple presses in vex bumper (Unexpected bumper output) According to Official documentation of the Vex Bumper, it states that the bumpers will cause:

  the robot sometimes [counts] a press twice. This issue is also caused by the robot counting too fast and as the limit switch is released, a second press is registered by the robot.

The documentation suggests this code:

task main() {
    while(true) {
         string presses = buttonPresses;
         if(presses != last) {
             writeDebugStreamLine(presses);
         }
         last = presses;

         if(SensorValue(bump) == 1) {
             wait1Msec(5);
             while(SensorValue(bump) == 1){}
             buttonPresses++;
         }
    }
}

However, if you are like me, this didn't work at all, multiple button presses were registered from holding down the button for a moment and releasing it.

Because this problem was so infuriating and strange, I managed to do a workaround which the program refused to take a sudden addition to button counts after taking a first one. This enabled me to use the button without multiple extra counts.

string last;
float buttonPresses = 0;
float time = time1[T1];
bool isFirstTime = true;

task main()
{
    ClearTimer(T1);
    clearDebugStream();
    while(SensorValue(go) != 1) {

        string presses = buttonPresses;
        if(presses != last) {
            writeDebugStreamLine(presses);
        }
        last = presses;

        if(SensorValue(bump) == 1 && buttonPresses < 6) {
            if(isFirstTime || time1[T1] - time > 50) {
                isFirstTime = false;
                wait1Msec(15);
                while(SensorValue(bump) == 1){time = time1[T1];}
                buttonPresses++;
            }
        }

    }
}

If you want extra probability against multiple extra "presses" you can widen the interval of tolerance (in this case the 50 value) to something larger, but it makes it less accurate at registering quick taps.


What's the most efficient implementation of map(x,0,1023,50,250)? I recently noticed how the map() function in Arduino was bulky in both terms of flash space used and time taken to execute, largely because it deals with long and involves a division and multiplication.

Many times you can replace maps with more basic functions i.e.

output = map(input,0,1023,0,255);

can become

output = input >> 2;

or

output = map(input,0,1023,1023,0);

can become

output = 1023 - input;

I have one line in some code that says:

backlight = map(LDRreading,0,1023,50,250);

How could this be simplified so that it is both space and time efficient?

I'll allow slight differences in output values if it results in a much better solution.

The screenshot shows a base-2 (i.e. binary) result of calculating the constant part of a mapping. You can approximate this multiplication by a constant by a number of shifts added together. You need to break down each multiplication in the result first:

x * 0.0012 = x >> 3

x * 0.00012 = x >> 4

x * 0.00000012 = x >> 7

Then add these together. You are essentially breaking it down into convenient base-2 multiplies (which can always be represented by shifts) and adds - nearly always more efficient.

This doesn't get you right to 250, but pretty close:

>>> for i in range(0, 1024, 34):
...   print (i >> 3) + (i >> 4) + (i >> 7) + 50
...
50
56
62
   [snip]
235
241
247
>>> print (1023 >> 3) + (1023 >> 4) + (1023 >> 7) + 50
247

Do all your processing with a left-justified int (ADLAR=1) though, to minimize errors. The ADC returns a 10bit result, and ADLAR choses if this is aligned to the left or right of the two result registers.


DS18B20 Temperature Sensor return as float function returning null 50% of the time I just got an DS18B20 Temperature sensor and am trying to modify the example code to use a function instead. Below is my getTemp function. It's working but returning results with a 0 value part of the time for example:

  Temperature = 72.39
  Temperature = 0.00

If I add Serial.print(fahrenheit); within the function I am always provided with the correct temperature. I though this may have to do with needing a delay but adding delay(5000); in my loop didn't help.

I'm assuming it's something simple I'm not understanding about how floats return.

#include <OneWire.h>

// OneWire DS18S20, DS18B20, DS1822 Temperature Example
//
// http://www.pjrc.com/teensy/td_libs_OneWire.html
//
// The DallasTemperature library can do all this work for you!
// http://milesburton.com/Dallas_Temperature_Control_Library

OneWire  ds(2);  // on pin 10 (a 4.7K resistor is necessary)

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

float getTemp(char tScale) {
  byte i;
  byte present = 0;
  byte type_s = 0;
  byte data[12];
  byte addr[8];
  float celsius, fahrenheit;

  if ( !ds.search(addr)) {
    ds.reset_search();
    delay(250);
    return false;
  }

  ds.reset();
  ds.select(addr);
  ds.write(0x44, 1);        // start conversion, with parasite power on at the end

  delay(1000);     // maybe 750ms is enough, maybe not
  // we might do a ds.depower() here, but the reset will take care of it.

  present = ds.reset();
  ds.select(addr);
  ds.write(0xBE);         // Read Scratchpad

  for ( i = 0; i < 9; i++) {           // we need 9 bytes
    data[i] = ds.read();

  }

  // Convert the data to actual temperature
  // because the result is a 16 bit signed integer, it should
  // be stored to an "int16_t" type, which is always 16 bits
  // even when compiled on a 32 bit processor.
  int16_t raw = (data[1] << 8) | data[0];
  if (type_s) {
    raw = raw << 3; // 9 bit resolution default
    if (data[7] == 0x10) {
      // "count remain" gives full 12 bit resolution
      raw = (raw & 0xFFF0) + 12 - data[6];
    }
  } else {
    byte cfg = (data[4] & 0x60);
    // at lower res, the low bits are undefined, so let's zero them
    if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
    else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
    else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
    //// default is 12 bit resolution, 750 ms conversion time
  }
  celsius = (float)raw / 16.0;
  fahrenheit = celsius * 1.8 + 32.0;
  if (tScale == 'C') {
    return celsius;
  }
  else if (tScale == 'F') {
    return fahrenheit;
  }

}
void loop(void) {
    Serial.print("Temperature = ");
    Serial.println( getTemp( 'F' ) );

}

Edit:
Interesting enough, adding an if statement to the loop fixes this, however. I'd still like to understand what is going on:

void loop(void) {
  if ( getTemp( 'F' ) == 0 ){
    Serial.print( "Temperature = " );
    Serial.println( getTemp( 'F' ) );
  }
}

You have intermittent communication problems.

Your address search occasionally fails and getTemp() returns false. In C++ (and many other languages) false will be implicitly cast to (int) 0, (float) 0.0f, and so on.

Your getTemp() function  also is difficult to debug because the multiple return statements have different meaning.

After the delay(250); you do a return false; in order to skip the rest.

In the example at https://www.pjrc.com/teensy/td_libs_OneWire.html the meaning of the return statement(s) is different. There the return happens within the void loop() function, where it simply means to interrupt the current execution (without returning a value) and continue with the next loop.

While it is generally okay to have multiple return, it can sometimes be problematic and I recommend to avoid it.

If you want to clean this up while still preserving the ability to detect a fault, you have a couple of options (order from most to least recommended):

do the setup/checking in a different function (and only call the second one if the first one succeeded), i.e. if (isReady()) { Serial.println(getTemp()); }
set a separate error variable, i.e. error = true; return 0; (and then check error later)
define a 'default' value that you interpret as an error (and never expect to be a temperature), i.e. return NAN; // not a number


How do I redefine the overlfow of compare interrupts in Arduino programming? If I'm programming a pin change interrupt I can call attachInterrupt at various points in my code and change what function is called when the interrupt occurs.

The overflow and compareA/B interrupt calls are defined by the ISR macro which is evaluated at compile time, which therefore can't be changed at run time. One solution would be to make that function consist of a single line, which invokes a function pointer. If I'm reading the code correctly, this is how attachInterrupt is implemented. Short of mucking with the interrupt vector table (which seems like a bad idea, or at least very hard to debug if you screw it up), is there another way to redefine the overflow or compare interrupt functions?

What about using a switch statement inside the ISR function and reroute the flow depending on the value of the global variable used in the switch?

uint8_t status = 0;

void myInterruptFn() {
  switch(status) {
    case 0:
      // do something
      status = 1;
      break;
    case 1:
       // do something else
       status = 0;
       break;
   }
}


MAX31855 giving NaN after some readings In my current project I am measuring temperature using K-type thermocouple and MAX31855 breakout board and Arduino uno.

I have used Adafruit-max31855 library and example code from that library. But monitoring on serial monitor after some reading it is giving NaN.

Here is the code I have used:

#include "Adafruit_MAX31855.h"

int thermoDO = 5;
int thermoCS = 6;
int thermoCLK = 7;

Adafruit_MAX31855 thermocouple(thermoCLK, thermoCS, thermoDO);

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

  Serial.println("MAX31855 test");
  // wait for MAX chip to stabilize
  delay(500);
}

void loop() {
  // basic readout test, just print the current temp
   Serial.print("Internal Temp = ");
   Serial.println(thermocouple.readInternal());

   double c = thermocouple.readCelsius();
   if (isnan(c)) {
     Serial.println("Something wrong with thermocouple!");
   } else {
     Serial.print("C = ");
     Serial.println(c);
   }
   //Serial.print("F = ");
   //Serial.println(thermocouple.readFarenheit());

   delay(1000);
}

Circuit Diagram:

Output:

What could be the possible error for this and how can I solve this?

Try to Serial.println(thermocouple.readError()). It will give you an
error code, which is a bit field:

1 = open circuit
2 = short to ground
4 = short to Vcc

C.f. the
datasheet.


What's Leonardo 5V pin current limit? I'd like to know how much current can supply the 5V pin and the 3.3V pin on an Arduino Leonardo board. I've been lead not to trust the specs on Arduino's website. And, as an added question, can the 5V pin supply enough power for an LM741 opamp?

Thanks!

The 5V pin is either supplied by the USB port, which has a limit of 500mA (imposed by a resettable fuse) if directly connected to the computer or a powered hub (or 100mA in an unpowered hub), or the on-board regulator (NCP1117ST50T3G), which is 1A, when powered externally.

The 3.3V pin is regulated using an LP2985-33DBVR which has a current limit of 150mA (the specifications on the website say 50mA. This is wrong. I think it is a left-over from the old Uno boards with FTDI chips where the 3.3V was fed directly by the internal 3.3V regulator of the FTDI chip and thus limited to 50mA).

Yes, the 5V pin has more than enough current to run an LM741 op-amp.


Communication with sensor KMX63 in I2C I trying to use a new sensor the KMX63 with a Arduino Uno board, my sensor is on a evaluation board made by kionix.
For the connexion il linked as follows:
| Pin Uno | Pin evaluation board |
| A5 | 5 |
| A4 | 7 |
| 3.3 | 1 |
| GND | 8 |
Here the schematic of the evaluation board:

I found a technical note from the constructor that advice to do some steps after the power up of the sensor to insure it's well functioning I wrote a code following it:

#include <Wire.h>
#include "KMX62.h"

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

  Serial.println(F("Starting"));

  byte error=7;
  byte id=0;
  byte command=0;
  delay(60);
  Wire.beginTransmission(KMX62_I2C_ADD_2);
  Wire.write(0x7F);
  Serial.println(F("Write 0x7F"));
  Wire.write(0x00);
  Serial.println(F("Write 0x00"));
  delay(100);
  error=Wire.endTransmission();
  Serial.print(F("retour 1 : "));
  Serial.println(error);
  if( error==0 ){
    Wire.beginTransmission(KMX62_I2C_ADD_2);
    Wire.write(CNTL2);
    Wire.write(0x00);
    error=Wire.endTransmission();
    if( error==0 ){
      Wire.beginTransmission(KMX62_I2C_ADD_2);
      Wire.write(CNTL1);
      Wire.write(0x80);
      error=Wire.endTransmission();
      if(error==0){
        delay(5);
        Wire.beginTransmission(KMX62_I2C_ADD_2);
        Wire.write(WHO_AM_I);
        Wire.endTransmission(false);
        Wire.requestFrom(KMX62_I2C_ADD_2,1);
        id=Wire.read();
        error=Wire.endTransmission();
        if(id==0x18||id==0x2D){
          Wire.beginTransmission(KMX62_I2C_ADD_2);
          Wire.write(COTR);
          Wire.endTransmission(false);
          Wire.requestFrom(KMX62_I2C_ADD_2,1);
          command=Wire.read();
          error=Wire.endTransmission();
          if(command==0x55){
            Serial.println(F("device ok"));
          }else{
            Serial.println(F("Issue with the sensor step e : need to be rebooted"));
          }
        }else{
          Serial.println(F("Issue with the sensor step d id=wrong : need to be rebooted"));
        }
      }else{
        if(error==2||error==3){
        Serial.println(F("Issue with the sensor step c : need to be rebooted"));
        }
      }
    }else{
      if(error==2||error==3){
        Serial.println(F("Issue with the sensor step b : need to be rebooted"));
      }
    }
  }
}

void loop(){

}

but i have an issue the steps , the program seem to freeze when i try to write into the register 0x7F.
I don't get any trace that i should have after the wire.endtransmission().
Here the trace i obtain :
09:56:35.477 -> Starting
09:56:35.511 -> Write 0x7F
09:56:35.511 -> Write 0x00

i have use the I2C scanner to check if the sensor appear, i had to modify the scanner to add a delay before Wire.beginTransmission and the Wire.endTransmission to avoid the scanner to be freeze too at the first address tried. After the modification i did saw the sensor at the address it was mean to be.
here the trace for the I2C scanner :
Scanning...
I2C device found at address 0x0F  !
done

Anyone have an idea of why i can't write anything to my sensor without making my program freeze indefinitely each time ?
PS : After the advice of chrisl i rerunned all my programs on a arduino mini pro on 3.3V / 8Mhz and got the same result.

I finally found where the problem was, i had made a error on the reading of the schematic of the evaluation board. I thought that the pin J1-9 was already wired in intern but it was wrong. I wired it to the VCC output of my board and it work perfectly now.


Need to buy a new breadboard? I'm new to Arduino and haven't done any education in electrical engineering before, so this might be a very dumb question.

I'm busy with a project to control two servo motors with Arduino. Now yesterday I connected the wires incorrectly to the breadboard, so the wires started smoldering. I didn't connect the resistor correctly, so I guess that might have been the problem.

Now I replaced the wiring, but it's not working and I don't know if the software might be the problem or the breadboard need to be replaced as well. I cannot see anything wrong with the breadboard, but it was warm so I don't know if it might be burned from the inside? The wiring of the servomotors seems to be okay, so I guess that I don't need to replace those I hope.

Any tips about how to check everything is still working?

Or might it be a good idea to buy an LED and add it to the breadboard to ensure it's okay?

EDIT:
I guess I found some code to check that the servomotors are still okay. Just add them directly to the Arduino and run some code: Sweep

One other question: one of the servomotors doesn't have a black, red and yellow cable but a red, brown and orange. How can I know which ones the same as yellow, red and black?

You could check the connections of the breadboard, using a multimeter (set to continuity check) and wires in the breadboard holes, with the + and - leads, from the meter, at either end of each row/column of connections, following the diagram below:

It might be a bit tedious, but it should only take thirty minutes maximum, and would give you peace of mind as well as saving you four Euros...

If you say that it was working before and now is not, then maybe the breadboard is damaged. However, it is unlikely that the whole breadboard is... try moving your components to a different part of the breadboard.

The breadboard could possibly get warm, as servos can use a fair bit of current, and breadboards aren't really designed for power circuitry. You may be better off using an Arduino Servo shield and connecting the servos directly to that, rather than using the breadboard. Why are you using a breadboard - can you, as Majenko states, provide a schematic diagram?

Answering the last part of your question - Taking the graphics from my answer to Code to control servo with shield, to show the different colours for the four different connector types:

Futaba and Airtronics connectors

Hitec and JR Radio connectors have the same pin out:

.

This means that the red, brown and orange leads go to a JR Radios connector.


Arduino Uno pin dead for no reason. Why? After struggling with an LCD showing rubbish characters on my previous post, I found that my pin 5 was dead, for no reason. I never connected it to anything except the LCD - I bought it two days ago.

I'm glad that I bought two extra ATmega328P-PU along with it, burned bootloader into it, and it worked, but what causes my pin 5 to be dead?

I did use A5 as an input before, but I don't get how it affected PWM pin 5.

FYI, this is my first time playing with Arduino.

I have quite a few Arduinos lying around and only one has failed completely, which I think is because I "zapped" it with static electricity, which is a problem, as Chris Stratton suggested.

Make a habit of grounding yourself before handling electronics, for example by touching some metal (earthed) part before reaching for your Arduino. Don't work while standing on a synthetic carpet, for example.

  but what causes my pin 5 to be dead?

Possible reasons:

static electricity
accidentally shorted an output pin to ground, which could damage the output driver if you are outputting HIGH
accidentally connected an output pin to +5V, which could damage the output driver if you are outputting LOW
connected the pin to a negative voltage
connected the pin to more than +5V
powering the board "parasitically" which means connecting power to the data pins before connecting power to the main power input
tried to "sink or source" more than 40 mA which is the absolute maximum rating. For example, connecting an LED directly to the pin without a current-limiting resistor

The other link he refers to: Bad LCD? Bad microcontroller? Or what?


help adapting a sketch to use a 16x2 lcd I have found a great instructable that shares a sketch.  I'm a noob, but i think i do understand it and how to adapt it for my use, but he has used a different display than i have.... and I just don't know how to get the output to display on it.
In the sketch he uses a Oled Display, all i have on hand is a 16x2 I2c LCD.  I have tried to use libraries and other code from other sketches that work on this display, but I just do have the knowledge to make it work.
Can someone help me please?
This is the page:
https://www.instructables.com/Measure-Fuel-Level-With-Arduino/
This is the code:
#include "SSD1306Ascii.h"
#include "SSD1306AsciiAvrI2c.h"
SSD1306AsciiAvrI2c oled;
#define I2C_ADDRESS 0x3C

int TankValue0;
int TankValue1;

void setup() {
  Serial.begin(9600);
  oled.begin(&Adafruit128x64, I2C_ADDRESS);
  oled.setFont(System5x7);
  oled.clear();
}

void loop() {
  int sensorTankValue0 = analogRead(A1);
  int sensorTankValue1 = analogRead(A2);
  TankValue0 = map(sensorTankValue0, 295, 785, 0, 100);
  TankValue1 = map(sensorTankValue1, 295, 785, 0, 100);
  if (TankValue0 < 0) {
    TankValue0 = 0;
  }
  if (TankValue1 < 0) {
    TankValue1 = 0;
  }
  if (TankValue0 > 100) {
    TankValue0 = 100;
  }
  if (TankValue1 > 100) {
    TankValue1 = 100;
  }
  oled.print("T0=");
  oled.print(TankValue0);
  oled.println(" ");
  oled.print("T1=");
  oled.print(TankValue1);
  oled.println(" ");
  oled.setCursor(0, 0);
}

OK, I have it working OK, by adding code from a battery monitor. I kinda just stabbed at it till it stuck, changing "oled" to "LCD" and a few other things.  Sorry i can't be more descriptive..... I'm not sure why it worked but eventually it stopped chucking errors at me .
This is the working code:
#include <LiquidCrystal_I2C.h>

int TankValue0;
int TankValue1;

LiquidCrystal_I2C lcd(0x27, 16, 2);   // set the LCD address to 0x27 for a 16 chars and 2 line display

void setup() {
  lcd.init();                          // initialize the lcd
  lcd.init();
  lcd.backlight();
  lcd.setCursor(1, 0);
  lcd.clear();
  lcd.print("WORD");
  lcd.setCursor(0, 1);
  lcd.print("TO");
  delay(1500);
  lcd.clear();
  lcd.print("YO ");
  lcd.setCursor(0, 1);
  lcd.print("MOMMA");
  delay(2000);
  lcd.clear();
  pinMode(A0, INPUT);
  Serial.begin(9600);               // starting the Serial Monitor
}

void loop() {
  int sensorTankValue0 = analogRead(A0);
  int sensorTankValue1 = analogRead(A1);
  TankValue0 = map(sensorTankValue0, 210, 695, 0, 100);// i just changed the first 2 set of values till it was right for full and empty
  TankValue1 = map(sensorTankValue1, 210, 695, 0, 100);
  if (TankValue0 < 0) {
    TankValue0 = 0;
  }
  if (TankValue1 < 0) {
    TankValue1 = 0;
  }
  if (TankValue0 > 100) {
    TankValue0 = 100;
  }
  if (TankValue1 > 100) {
    TankValue1 = 100;
  }
  lcd.print("Water Level is :");
  lcd.setCursor(0, 1);
  delay(100);
  lcd.print("WATER TANK = ");
  lcd.print(TankValue0);
  lcd.print("%");
  lcd.setCursor(0, 0);

  delay(10000);
  lcd.clear();
}


Why do you need to shift bits when reading from an analog sensor? I was playing around with some analog grove sensors and looking at examples (https://github.com/DexterInd/GrovePi/blob/master/Software/Go/grovepi/grovepi.go - this specific example is in go and for raspberry pi, but it's the same on arduino) I realised that you need to "(int(val[1]) << 8) | int(val[2])" before getting the result.

Why is that so? Why do the second 8 bits need to be left shifted by 8 and why is there then an OR with the third group of bits?

You read bytes in the order:

Most significant byte   (let's call this msb)
Least significant byte  (let's call this lsb)

The formula to get to real value is msb * 256 + lsb
256 because this is the value of the maximum value of one byte, + 1. which is bits (2 ^ 8 = 256).

However, a CPU is normally faster in bit operations than in arithmetic operations.

Assume msb is 10101010
and lsb is    11001100

Now below is the table with the calculation order

sensor value             msb         lsb
00000000 00000000        10101010    11001100
00000000 10101010                                sensor value = msb
10101010 00000000                                msb << 8, or msb * 256
10101010 11001100                                (msb << 8) + lsb, or (msb * 256) + lsb

Actually I would expect a cast to an unsigned byte type (8 bits). However, if the values msb or lsb would be floating points/doubles, than the remainder will be removed, leaving an integer (whole) number.


Arduino MQTT Bluetooth Is there a library to use MQTT with a bluetooth module (HC-06) instead of WiFi? If not is there a similar ready for use implementation of a publisher subscriber pattern available?

MQTT is TCP/IP native. If you want to access it via Bluetooth, you need a gateway; a device that translate protocols. You need one for the specific protocols involved: MQTT, TCP/IP and Bluetooth.

Google "MQTT Bluetooth gateway" to find alternatives like this one:

  The iGS01 gateway listens for beacons, gets their advertising data and
  forwards it on to your server or an IoT server via TCP, HTTP(S) or
  MQTT. It can be used to feed back-end systems that report on the
  presence or absence of iBeacon or Eddystone beacons or act on beacon
  sensor (e.g. accelerometer, temperature, light, humidity) data.

  The gateway connects to your local 2.4GHz frequency band WiFi access
  point and is managed via a web browser interface. It can  be connected
  via WPS (press button on both the gateway and the WiFi access point).
  It can also be managed via Telnet commands from other hardware (or a
  human).

  For MQTT/MQTTS, the host, port, username, password and a root CA cert
  can be provided.

There are also software only solutions available, but I didn't found a generic one, only specific for certain vendors.


Interfacing with desktop computer console software Recently I bought the following USB to Serial cable: https://www.adafruit.com/products/954

This cable has grd, vcc, rx and tx lines.

I am looking to use this cable to interface with my desktop computer with a program like Tera Term or Hyperterminal so i can output messages for debugging purposes.

Also, I am trying to stay from using the Arduino IDE. I would prefer using C and flashing in the hex manually.

So, can anyone point me to a tutorial or explain how to make this happen?

thanks people.

For debugging:

Configure the UART on the ATmega to output TTL serial. If you are using the Arduino libraries, then Serial is what you want. Connect the TX pin of the ATmega to the RX of the USB/Serial cable, and vice versa.

Open the serial device on your computer in the program of your choice. When you write to the UART on the ATmega, you should see the messages in your terminal.

Pretty straightforward.

For programming:

If you're going to be using C and flashing things manually, you'd best go and buy an AVR programmer so you can program the ATmega directly without messing about with a bootloader. A programmer is ~15USD, so you might as well buy one. Then you can use the GNU AVR toolchain, which is very easy to use. Compile code with avr-gcc, and program the device with avrdude.

If you really want to use programming over serial, you'll have to manually hit the reset button each time you program the chip, because (as Mikael pointed out), that serial cable lacks the lines necessary to automatically reset the chip (and drop to the bootloader).


Simultaneous output from sonar array I am working on a project that records the elevation changes of a 1 foot wide section using sonar distance measurement. I have 10 HC-SR04 sensors arranged in a straight line over this 1 foot section.

The issue I am having is that when I send an output from my sonar sensor, I must wait until the return signal is recorded before I can trigger the next sonar sensor to take a measurement. This is rather slow and decreases the sampling frequency significantly. I need each sonar sensor to take 1000 measurements per second for my project.

Is there a way to have the HC-SR04 sensors simultaneously output and listen for the return signal? I would want all 10 sensors to send a 40 kHz pulse at the same time, and then when a return signal is recorded, another 40 kHz pulse is sent out.

The average distance to the 1 foot wide section is about 11 inch. If the Arduino is limited and there are other control boards that can accomplish this, it would help a lot if you can point me in the right direction.

1000 measurement for 10 sensors per seconds, it means there are 10000 measurement per sec with 0.1 mS time slot for each measurement.
According to SRF-04 Documentation,
(1)

If nothing is detected then the SRF04 will lower its echo line anyway after about 36mS.

So, time slot for each reading is 36 mS ("if" nothing is detected), which means for 10 SRF04 x 1000 reading, it will take 360000 mS = 360 Sec.
(2)

I would want all 10 sensors to send a 40kHz pulse at the same time, and then when a return signal is recorded, another 40kHz pulse is sent out.

Its seems reasonable. But,

According to the timing diagram, 1 cycle minimum period consist of :

100 us Trigger pulse ==> 0.0001 s
8 Cycle burst at 40 kHz = (1/40000)*8 s ==>  0.0002 s
100 us Echo pulse ==> 0.0001 s
10 ms delay time ==> 0.01 s

Total for 1 cycle is 0.0104 s, so for 1000 readings x 10 sensors (object to detect is present) will be 104 s.
All sensor burst at the same frequency, great idea. However it's not advised (or rather not possible) because that will disturb each sensor reading unless you successfully change each sensors frequency or doing sound modulation. Even if you success in modulating 10 sensors frequency, the needed time is still not met 1 s interval

100uS for 10 sensors trigger pulse at once ==> 0.0001 s
8 Cycle burst at 40 kHz = (1/40000)*8 s ==>  0.0002 s
100 us (minimum) Echo pulse --> 0.0001 s x 10 sensors ==> 0.001 s, because Arduino does not support threading, which mean there is no way you can read all at same time
10 ms delay time ==> 0.01 s

Time for 1 cycle (10 sensors reading): 0.0113, 1000 readings : 11.3 s
(3)
"How about changing the beam pattern?"

Changing beam pattern and beam width
You can't! This is a question which crops up regularly, however there is no easy way to reduce or change the beam width that I'm aware of. The beam pattern of the SRF04 is conical with the width of the beam being a function of the surface area of the transducers and is fixed.

So, rather than trying to modify the ultrasonic, more reasonable solution is changing the way you do elevation measurement.


Serial.write and Serial.println return different values? Cannot use correct ones I have a text file on an SD card, and I am trying to print the lines to the serial monitor.

This Code Works:

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

File myFile;

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

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

  pinMode(10, OUTPUT);

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

  myFile = SD.open("c.txt");
  if (myFile) {
    Serial.println("c.txt:");

    while (myFile.available()) {
      Serial.write(myFile.read());  //THIS LINE RIGHT HERE
    }
    myFile.close();
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening c.txt");
  }
}

void loop()
{
}

However, if I replace the line Serial.write(myFile.read()); with Serial.println(myFile.read());, then the code doesn't return the correct lines.

It should return numbers similar to this (albeit 3000 of them):

564
564
564
564
564
564
564
464
564
664
564

If I use Serial.println it returns numbers like this (and it doesn't stop at 3000 lines):

13
10
54
54
52
13
10
53
54
52

And if I try to do int(myFile.read()) then the integer becomes the wrong numbers (returned by println), not the right ones (returned by write).\

How do I get a number returned by Serial.write(myFile.read()); to be an integer?

The text file contains the sequential ascii values that spell out the data, not binary data. println in printing the numerical value of each byte. For example, the 10's println prints are '\n' characters. write is printing the ascii character associated with the binary value (the new line). You need to parse the ascii characters into numbers.

Luckily for you the SD library inherits from the Stream class, so it will have the same parseInt function most often used to parse ints from the serial monitor.

You probably want to set myFile.setTimeout(0) first because the file isn't slowly getting characters from the serial bus, so the timeout would just slow you down.

Then you should be able to parse and print out the ascii integers with something like this:

int val = myFile.parseInt();
Serial.println(val);


Why the LED freezes? when I am adding a delay? I am new into arduino and stuff. So i was playing around with the pull up resistor. It worked fine but the problem rised when I used a delay to turn the led on for few seconds before it gets back to low state it stopped working when I pressed the switch multiple times it may work sometimes but maximum time it is not working

here is the code

const int buttonPin = 4;
const int ledPin =  12;
int buttonState = 0;

void setup() {
      pinMode(ledPin, OUTPUT);
      pinMode(buttonPin, INPUT_PULLUP);
}

void loop() {
        buttonState = digitalRead(buttonPin);
      if (buttonState == LOW)
  {
    digitalWrite(ledPin, HIGH);
    delay(5000);
  } else
  {
    digitalWrite(ledPin, LOW);
    delay(5000);
  }
}

Your Arduino does nothing during the delay(5000). So pressing the button during the 5000 mSec that the led is off won't do anything. Or you must be very lucky to press the button in the very small time between one loop and the next.

I learned a lot about timing and delays with this tutorial: Blink Without Delay


Is applying 5 volts to LED dangerous? The Arduino Uno manual (from the kit) instructs to connect a resistor to GND when lighting an LED on the breadboard with the 5V (socket?). The red, green, and yellow LEDs don't light up so brightly... actually they are barely bright enough to detect. Is it safe to apply all 5 volts by connecting the cathode to the ground with a wire? I tried it for a second and it worked... Just don't try it on the blue, I assume that beyond 5V it will explode, it burnt so bright..

Optional: Why does only the blue LED light visibly?

Different color LEDs are not the same.  The are made with different impurities.  And some colors (blue) were really hard to figure out.  So much so that the blue LED inventor was awarded the Nobel Prize!

Consequently, it should not be assume all LEDs operate at the same voltage and current.  As such, when driving an LED with a constant voltage source, derive the proper series resistance for each case.

Example 1:

Given a red LED which may have 1.8 volt drop and may need 20mAmps to operate driven by a 5 volt source, we find the proper series resistor to be...

  V = I * R

  5 - 1.8 = 20mA * R

  R = (5 - 1.8) / 0.020

  R = 160 ohms

Example 2:

Given a blue LED which may have a 3.3 volt drop and may need 20mAmps to operate driven by a 5 volt source, we find the proper series resistor to be...

  V = I * R

  5 - 3.3 = 20mA * R

  R = (5 - 3.3) / 0.020

  R = 85 ohms

Your specific LEDs may have different specifications.  The above are only examples.

Go here for more about calculating the proper LED series resistance.

In general, LEDs that are over driven will grow dimmer and not recover.


Movement and storage of servo positions via bluetooth I am trying to program a 4DOF robotic arm (using 4 servo motors). I would like to move the servos using an Android app, by means of bluetooth (HC-05).
I developed the app, in whose interface there are 7 buttons (Up, Down, Left, Rght, Forward, Backward, Save) and a field in which you can type using the keyboard (I attached an app interface screenshot).
So far, I tried to manage only Up button (which senses 'U' via bluetooth to Arduino) and Down (which sens 'D'), which would move the servo intended for vertical arm movements. That code works quite well, although the app crashes sometimes, but I still can't figure the reason out. Using the println() function I can see that Arduino reads in the bluetooth input the character '⸮ ' , what does it mean? I use a baud rate of 9600.
Then, what I would like to do is: once I have moved the servo and reached a particular position, I'd like to save the position of the motor into an array. In order to allow multiple positions saving, after Save button is pressed, I want Arduino to wait for another input from the bluetooth (so that, it would wait for another button to be clicked from the app or for something typed into the dedicated bar from keyboard) that defines the position within the array, in which I save the servo position (eg: I type '2' into the dedicated app bar and Arduino, which is waiting for an input, receiving it, saves the last servo position into the array servo01pos[2]). I wrote the "case ('S')" code that is quite long and inefficient but, at least, it works.
Thanks in advance to anyone who will help me.
Giammarco

#include <SoftwareSerial.h>
SoftwareSerial bluetooth(10, 11); //BlueTooth RX ,TX
#include <Servo.h> // servo library

unsigned long timestampSend = 0; // BT Write wait period
String readString;
Servo servo01; // servo name
byte pos01 = 90;
#define ANGLE_STEP 10 // 10 degree steps
int servo01pos\[50\];
char data;
char button;
int x = 1;

void setup() {
  Serial.begin(9600);
  bluetooth.begin(9600);
  delay(1000);
  Serial.println("Ready ...");
  Serial.println ("\n");
  servo01.attach(12);
  servo01.write(pos01);
}

void loop() {
  do {
    if (bluetooth.available() > 0) {
      Serial.println(data);
      do {
        delay(500);
        data = bluetooth.read();
        Serial.println(data);
      } while (bluetooth.available() > 0);
      if (data == 'U' || data == 'D' || data == 'L' || data == 'R' || data == 'F' || data == 'B' || data == 'S' || data == 'X') {
        Serial.print("Received value: ");
        Serial.println(data);
        switch (data) {
          case ('S'): //SAVE
            Serial.println("Enter the button you desire to set...");
            do {
              data = 254;
              bluetooth.listen();
              button = bluetooth.read();
              if (button == '0' || button == '1' || button == '2') {
                data = 'S';
              }
            } while (data != 'S');
            Serial.println("SAVING POSITIONS ...");
            if (button == '0') {
              servo01pos\[0\] = pos01;
            } else if (button == '1') {
              servo01pos\[1\] = pos01;
            } else if (button == '2') {
              servo01pos\[2\] = pos01;
            }
            servo01.write(pos01);
            Serial.println(button);
            Serial.println(pos01);
            Serial.println(servo01pos\[1\]);
            Serial.println(servo01pos\[2\]);
            Serial.println(servo01pos\[0\]);
            //}
            break;

          case ('U'):
            Serial.println("UP");
            if (pos01 <= 180 - ANGLE_STEP) {
              pos01 = pos01 + ANGLE_STEP;
              servo01.write(pos01);
              Serial.println(pos01);
              delay(20);
              Serial.println(data);
            }
            break;

          case ('X'):
            Serial.println("EXIT");
            x = 0;
            break;
        }
      }
    }
  } while (x != 0) ;
}

The character '⸮ ' was given everytime there was a power outage. So, it is enough to use an external power supply to power bluetooth and servos (Arduino cannot power all those modules simultaniously).


Do addressable RGB's need to be programmed differently from normal RGB's? I bought these rgb's from Sparkfun, however I have no idea how to hook them up or how to program them. Obviously the data sheet was somewhat helpful, however I have no idea how the IC's in the LED's work themselves or how to control them separately, or even how to string them together. My best guess is currently going for what the led's appear as in the example picture by connecting the first and last pins and putting the respective Vcc and ground pins to Vcc and ground.

Is there any good examples for hooking these up and coding them, or a basic understandable explanation for how they work?

Thanks, I can't find a great resource yet.

These are much different than "normal" RGB LED: they use the WS2812 chip, which is the same as the chip used in famous Adafruit "neopixels" strips, rings...

Wiring is simple. For all LEDs:

GND to 0V
VDD to 5V

For the first LED (connected to Arduino):

DIN to any Arduino logical output pin
DOUT to the 2nd LED you want to address (on its DIN pin)

For all but the first LED:

DIN to the previous LED DOUT
DOUT to the next LED DIN (or left floating for the last LED)

Programming neopixel is quite hard because timing of sent commands must be very precise.

I highly suggest to use Adafruit libraries for that.


TI ADS7250 Read From SPI and SPI1 Simultaneously I'm so confused by the ADS2750 datasheet here, I can't seem to figure the proper bit shift to read data from bits 15-27 properly. I'm not even sure what some of the acronyms mean on page 23 table 1. I get that the first 15 bits are empty while the ADC takes a reading and then the last 12 bits for the 12 bit ADC are the value from that ADC that matches the SPI A or B input. Would someone be willing to explain to me how you would read data based on this datasheet using information from table 2 page 24?
My hardware set up to ADC7250
VCC 5 Volts

D5 SS fro Both SPI & SPI1
D13 SCK for Both SPI & SPI1
D11 MISO SPI_A from ADC
D4 MISO SPI_B from ADC
No MOSI connected

I'm not sure what to send in the SPI.Transfer(0x00). I'm also not sure if I'm setting up the modes properly, SPISettings settings(24*MHZ, MSBFIRST, SPI_MODE1); as I not 100% on the clock speed. I also I'm confused if this is LSB or MSB as the datasheet has two conflicting notes, the transfer function used LSB and then two paragraphs say "MSBs of ADC_A and ADC_B are output"
I'd love some help decoding this data sheet and getting a script that can read data from this chip using both SPI and SPI1 simultaneously.
Working on only reading SPI first the will add SPI1.
unsigned int readRegister(byte thisRegister, int bytesToRead);

const int CS_ADC_ISOLATOR = D5;
__SPISettings settings(24*MHZ, MSBFIRST, SPI_MODE0);
const int buffersize = 30;
unsigned char dataBuffer [buffersize];
const byte READ = 0x22;

// setup() runs once, when the device is first turned on.
void setup() {
  Serial.begin(115200);
  pinMode (CS_ADC_ISOLATOR, OUTPUT);
  digitalWrite (CS_ADC_ISOLATOR, HIGH);
  SPI.begin();
  SPI1.begin();
}

// loop() runs over and over again, as quickly as it can execute.
void loop() {
    digitalWrite (CS_ADC_ISOLATOR, LOW);
    SPI.beginTransaction(settings);
    for(unsigned char i = 0; i < buffersize; i ++)
    {
        dataBuffer[i] = SPI.transfer(0x00 << 14);
    }
    digitalWrite (CS_ADC_ISOLATOR, HIGH);
    SPI.endTransaction();
    for(unsigned char n = 0; n < buffersize; n ++)
    {
        Serial.print(dataBuffer[n]);
    }
    Serial.print("::");
}

You can't use the normal SPI library for communicating with this device properly. Well, you can, but you will only be able to use one channel - the other will be completely ignored.
SPI only works on one MISO pin - you need two.  There are two other types of "SPI" that are used by devices, most notably SPI flash chips: DSPI and QSPI (dual SPI and quad SPI). You want DSPI.
Unfortunately the Arduino doesn't do DSPI, so you will have to "bit bang" it, which means manually manipulating the IO pins to create your own SPI signals in software.
Now... on to the datasheet:
The important part is the timing diagram on page 9. From that you can see that you just send 32 clock pulses and the chip responds, after 15 pulses, with the data.
So if you just do 4 8-bit transfers back-to-back then you get the data. It doesn't matter what you "send" in those transfers since the MOSI pin isn't connected to anything.
As far as speed goes, 24MHz is the maximum speed that it will run at. The actual speed is dictated by the Arduino and how fast you manipulate the SCK pin. That can be as slow as 1x10-1000Hz if you really want.
Data should be read on the falling edge of SCK.
So you could write a little routine that looks like:
uint32_t resa = 0;
uint32_t resb = 0;

pinMode(SCK, OUTPUT);
pinMode(SDI_A, INPUT);
pinMode(SDI_B, INPUT);
pinMode(CS, OUTPUT);
digitalWrite (CS, HIGH);

digitalWrite (CS, LOW);
for (int i = 0; i < 32; i++) {
    digitalWrite(SCK, HIGH);
    digitalWrite(SCK, LOW);
    resa <<= 1;
    resb <<= 1;
    resa |= digitalRead(SDI_A);
    resb |= digitalRead(SDI_B);
}
digitalWrite (CS, HIGH);

Serial.print("A: "); Serial.println(resa);
Serial.print("B: "); Serial.println(resb);

So for 32 iterations you pulse the clock HIGH then LOW, then shift each result 1 bit to the left, and then add in the newly read bit into the lowest bit position.
You could speed up operation by using direct port manipulation and avoiding the slow digitalWrite() and digitalRead() functions.