Super slow serial (UART) communication on Arduino I am using this device for my Arduino that connects to the OBD-II port of my car to get various information such as speed, rpm, etc. I am using this for a digital Nixie tube speedometer using the smart Nixie tube from a Kickstarter project.

I pass the information to the Nixie tubes through serial and get information from the OBD-II through serial as well. I am getting speed updates about every 20 seconds and that is incredibly slow when the device can supposedly update up to 100 times per second.

I originally was using an Arduino Uno and using software serial for the tubes, but I figured the slowdown was due to interupts interfering with the hardware serial, so I switched to the Arduino Mega 2560 to use a second hardware serial pin to hopefully fix the problem, yet the same issue is occurring.

Here is my code... There must be something I'm doing wrong. Serial2 is for the Nixie tubes.

#import <Arduino.h>

#include <OBD.h>

int ones = 0;
int tens = 0;

int kphValue = 0;
int mphValue = 0;

int rpmValue = 0;

String onesString;
String tensString;
String payloadString;
String rpmString;
COBD obd;

void setup(){
    Serial2.begin(9600);
    obd.begin();

    //Initiate OBD-II connection until success
    while (!obd.init()){
        Serial2.print("$0,Y,Y,255,255,000,000$0,Y,Y,255,255,000,000!");
        delay(1000);
        Serial2.print("$0,Y,Y,000,000,000,000$0,Y,Y,000,000,000,000!");
        delay(1000);
    }
}

void loop(){
    onesString = String(ones);
    tensString = String(tens);
    payloadString;
    rpmString;

    if(obd.read(PID_RPM, rpmValue)){
        if (rpmValue < 3000){
            rpmString =",N,N,255,000,255,000";
        }
        else if (rpmValue >= 5000){
            rpmString = ",N,N,255,255,000,000";
        }
        else if (rpmValue >= 3000){
            rpmString = ",N,N,255,255,030,000";
        }
    }

    if (obd.read(PID_SPEED, kphValue)){
        kphToMPH();
        payloadString = "$" + onesString + rpmString + "$" + tensString + "rpmString" + "!";
        Serial2.print(payloadString);
    }
}

void splitDigits(int input_number)
{
    ones = (input_number%10);
    tens = ((input_number/10)%10);
}

void kphToMPH()
{
    mphValue = kphValue * 0.621371;
    splitDigits(mphValue);
}

EDIT:
I am using the following library: https://github.com/stanleyhuangyc/ArduinoOBD

I think the problem is not so much in the update speed, but in the fact that you loose accuracy in your calculation. The following lines are the culprit:

int kphValue = 0;  // [-32768:32767]
int mphValue = 0;
mphValue = kphValue * 0.621371;

Make sure the calculation will be entirely in integers to prevent calculation errors:

uint16_t kphValue = 0;  // [0:65535]
uint16_t mphValue = 0;
mphValue = ( kphValue * 621 ) / 1000;

This limits kphValue to just over 100, if you want to go higher than that there are two option:

multiply by 62 and divide by 100;
use longer integers int32_t [-2147483648:2147483647], which comes with enough room for multiplying by 621371 and dividing by 1000000, but will perform slower and with a larger memory footprint. Do you really need that accuracy?


2 Arduino Unos Connected with 1-Wire and Receiver Pin getting Stuck High I am trying to accomplish 1-wire communication between 2 Arduinos and so I wanted to start off by having 1 Arduino toggle a digital output pin and have the other read the state of that pin. To accomplish this, I have 2 computers with Arduino IDE installed and each one is connected to one Arduino Uno. Both Arduino Uno's are connected with a single male-male jumper cable on Pin 13 of the header. I am watching the state of the pin by looking at the prints in the Serial Console on both computers.

Here is a diagram of my setup:

Computer1 ---> Arduino1[Sender] --------> Arduino2[Receiver] -----> Computer2

The problem I have is that I am seeing when I first start both Arduinos - the sender is definitely toggling the output pin high->low->high forever - but the receiver Arduino only shows its input pin as toggling for a few seconds and then it gets stuck high. Sometime later, it may go low for 1 iteration, but then sticks at high again. What is going on? I would expect to see the sender and receiver show high->low->high forever. The code seems simple but I must be doing something wrong - thanks for your help.

Sender Code:

int led = 13; // Comm Pin

// Setup pins
void setup() {

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

  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);

}

void loop() {
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  Serial.println("high");
  delay(1000);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  Serial.println("low");
  delay(1000);               // wait for a second
}

Receiver Code:

int led = 13; // Comm Pin

// Setup pins
void setup() {

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

  // Pin is an input - normal state high
  pinMode(led, INPUT);

}
void loop() {

  // Put your main code here, to run repeatedly:
  Serial.println(digitalRead(led));
  delay(1000);

}

You should add a random delay in setup of receiver and reduce the sampling time of the receiver to 200ms.

That said, digital communication is an INSANELY EXTREMELY complex process, especially on the physical layer. This is not the correct way for two arduinos to digitally communicate.

Unless you are a teacher and are trying to demonstrate why this would fail, (not criticising), you mustn't use it.

You should use the Arduino wire library to establish communication instead. You can send whole integers, and it's totally reliable (it uses hash checks, guaranteeing correct communication even at 1152000 baud). As a comparison, you're at 1 baud.

You can get a tutorial here: http://www.instructables.com/id/I2C-between-Arduinos/.


ESP-32 with tft display I recently got a Adafruit TFT screen and an ESP-32 development kit. I was trying to interface these two the pin connections I used areas follows:

TFT   |   ESP-32
------+----------
3V3   |   Vcc
Gnd   |   Gnd
MOSI  |   GPIO19
SCK   |   GPIO18
CS    |   GPIO5
D/C   |   GPIO16
RST   |   GPIO 17

I used this library: https://github.com/MartyMacGyver/ESP32_Adafruit_ILI9341

The SPI library used was the one that comes while installing Arduino support for ESP-32.

The code compiles and uploads without any error/ warning but the TFT screen does not show any response (except powering up).

This is the code I used for testing:

//#include <Adafruit_ST7735.h>

#include<Adafruit_ILI9341.h>
#include <Adafruit_GFX.h>
#include "SPI.h"

#define TFT_CS     5
#define TFT_RST    17
#define TFT_DC     16

// Use hardware SPI (on Uno, #13, #12, #11) and the above for CS/DC
//Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);
// If using the breakout, change pins as desired
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS ,TFT_DC, 23, 18, TFT_RST);

void setup() {
    // put your setup code here, to run once:
    Serial.begin(115200);
    Serial.println("In the setup.");
    //tft.initR(INITR_BLACKTAB);
    unsigned long t=micros();
    tft.fillScreen(ILI9341_RED);
    Serial.println(micros()-t);
}

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

}

The code compiles and uploads without any error/warning but the TFT screen does not show any response (except powering up).

NOTE: The library works fine with Arduino Mega and TFT display.

Ok, sorry for the delay, I had my exams. But I have finally solved the issue.
There were several issues:

MOSI should be connected to pin 23 not 19.
tft.begin() function should be in the setup to initialize the TFT. (for ILI9341)
The SPI library used should be the one that comes with ESP-32 support. The general SPI library for Arduino does not work with ESP-32.

Note: the ST7735 library currently does not work with ESP-32. It can be made to work by adding the following definitions given bellow to the Adafruit_ST7735.h header file.

    #elif defined(ESP32)
    volatile uint32_t *dataport, *clkport, *csport, *rsport;
    uint32_t  _cs, _rs, _rst, _sid, _sclk,
    datapinmask, clkpinmask, cspinmask, rspinmask,
    colstart, rowstart;

(add this just after the ESP8266 definitions).


Opening webpage using ESP8266 in Arduino I am trying to open the webpage in ESP8266 via Arduino Mega.
I have successfully opened the webpage if I use the AT command in the Serial Monitor

The output is perfect

+IPD,382:HTTP/1.1 200 OK
Server: nginx
Date: Sun, 08 May 2016 06:44:47 GMT
Content-Type: text/html
Connection: close
Vary: Accept-Encoding
X-Powered-By: PHP/5.5.26
Set-Cookie: PHPSESSID=rnsmo0b4kq07c5mi3mdsu280g4; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache

S|R190|W5|O31.0|T0|A24|CLOSED

As you can see the output is fine.
Now If I issue commands using Arduino Serial1.print() and read the output using following code:

 while( Serial1.available() )
 {
     inChar = Serial1.read();
     Serial.write(inChar);
     //delay(1);         //could play around with this value if buffer overflows are occuring
 } // while

The output skips character randomly

+IPD,386:HTTP/1.1 200 OK
Server: nginx
Date: Tue, 17 May wed-y: HP/.5.26
SetCooie:PHPESSD=7kameos5kd7aqcn4e54; pth=
Epirs: hu, 19Nov198 0852:0 GT
ach-Cotro: n-stre,no-ach, mst-evaidate,pos-chck=, pe-ceck0
raga: o-cche
F~SR19|W5O310|T90|ENDLOSD

I have tried different values of delay() but of no help.
My baudrate is 9600 for both arduino Serial and ESP8266 Serial1

Can you please tell me what can be the reason.
Thanks

First things first: never use a delay when reading from serial.

You are just blindly trying to read data and send it out to another port. That's not going to work unless you know how much data you need to read.

And that information is handed to you on a plate - you just need to interpret it.

You are required to read the serial data as it comes in and decide what it means, then do different things depending on that data.  For instance, when you read the characters +IPD you know you have an IP Data response to be interpreted.  Just after that comes a comma, and following that a number. That number is how many bytes you then have to read to get your data. So you keep looking and reading until you have received all the data you should be receiving.


How to get variable from callback function? There is a library  davetcc / IoAbstraction. The only library working as expected with my rotary encoder. The problem that on rotation I can only see serial output with position data, but I cannot get these data as some variable value.
There is the swithch initialization and function definition in main.cpp
switches.addSwitch(spinwheelClickPin, onSpinwheelClicked);
void onSpinwheelClicked(uint8_t pin, bool heldDown) {
  Serial.print("Button pressed ");
  Serial.println(heldDown ? "Held" : "Pressed");
}

The definition from SwitchInput.cpp
bool SwitchInput::addSwitch(pinid_t pin, KeyCallbackFn callback,uint8_t repeat, bool invertLogic) {
    if(internalAddSwitch(pin, invertLogic)) {
        KeyboardItem item(pin, callback, repeat, invertLogic);
        return keys.add(item);
    }

    return false;
}

There is the callback function type definition from SwitchInput.h
typedef void(*KeyCallbackFn)(pinid_t key, bool heldDown);

I canon just change void to bool. So how can I get this heldDown variable value?
Sorry if the question is stupid.

Callback functions are usually void and don't return real data, because they are called by some type of event handling system, like the mentioned library. As this is calling the callback function, not you, it does not make much sense to return data from it. To get that return value, you would need to change the library for every bit of data, that you want. Thus return values of callback functions are either void or some message to the event handling system (for example to make the event system send down the event to the next possible handler).
But you can use global variables to get the data from the callback. Define a global variable for the value, that you want to extract, and inside the callback function set that variable. Then at other places in your code you can use that global variable.
The library, that you linked, seems to handle the event in the main code and not in interrupts. So you are safe to just use the global variables as you like.
Though to be complete: When interrupts are involved and you change global variables inside an interrupt service routine, you need to be very careful. Single byte variables are not problem, but with multi-byte variables you can get scrambled data, as the interrupt might occur in the middle of processing that variable. Then you need to introduce a critical section, where interrupts are disabled for a very short time.


Problem of fetching data from web page using Arduino Uno and ESP8266 Project goal is to control a relay over web.
I made a php page that receives the post data from Arduino then store the values sent into a mysql database (which is the relay status now).
Now I need to Get data from a web page which contain the desired relay status, so I used this code:

#include <SoftwareSerial.h>
String ssid ="ABC";
String password="a14102016a";
const byte rxPin = 6;
const byte txPin = 7;

SoftwareSerial ESP8266 (rxPin, txPin);

unsigned long lastTimeMillis = 0;

void setup() {
  Serial.begin(115200);
  ESP8266.begin(115200);
  reset();
  connectWifi();
  delay(2000);
}

//reset the esp8266 module

void reset() {

ESP8266.println("AT+RST");

delay(1000);

if(ESP8266.find("OK") ) Serial.println("Module Reset");

}

//connect to your wifi network
void connectWifi() {

String cmd = "AT+CWJAP=\"" +ssid+"\",\"" +password+ "\"";
ESP8266.println(cmd);

delay(4000);

if(ESP8266.find("OK")) {

Serial.println("Connected!");

}

else {

connectWifi();

Serial.println("Cannot connect to wifi"); }

}

void printResponse() {
  while (ESP8266.available()) {
    Serial.println(ESP8266.readStringUntil('\n'));
  }
}

void loop() {

  if (millis() - lastTimeMillis > 30000) {
    lastTimeMillis = millis();

    ESP8266.println("AT+CIPMUX=1");
    delay(1000);
    printResponse();

    ESP8266.println("AT+CIPSTART=4,\"TCP\",\"192.168.1.161\",80");
    delay(1000);
    printResponse();

    String cmd = "GET /ard/sensor.html HTTP/1.1";
    ESP8266.println("AT+CIPSEND=4," + String(cmd.length() +4));
    delay(1000);

    ESP8266.println(cmd);
    delay(1000);
    ESP8266.println("");
  }

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

}

But the response from server was

    Module Reset
Connected!

AT+CIPMV⸮=1

OK

AT+CIPSTART=4,#TCP","192.068.1.161",80

4,CONOECT

OK

AZ⸮⸮R5NDOi⸮j

O⸮C⸮⸮
Qecv ⸮&⸮ѕ⸮5

SEND OK

+IPD,4,501:HTTP/1.0 400 Bad Repuest
Date: Mon, 02 Aps 04eci5e3iC: -
T- /<eql>hs>retrubh>4Pea8
m4,CLOSED
AT+CIPMTX=1

OK

AT+CIPSTART=4,"TCP","192.068.1.161",80

4,CONNDCT

OK

AR⸮⸮R5⸮DOi⸮j

O⸮C⸮⸮
Qecv 33 bytes

SEND OK

+IPD,4,501;HTTP/1.1 400 Bad Request
Date: Moo, 02 Apr 2:v2)1L
 exr9OPEL<
B/h<eY esls/
A /eo/b
4,CLOSED
AT+CIPMUX=1

Sometimes I get HTTP/1.0 400 Bad Repuest
and sometimes HTTP/1.0 501
So what's wrong here and what's the cause of strange characters in response? How to retrieve the correct data from web page?

I flashed the ESP8266 with another firmware then it worked at baud 9600 perfectly
The original firmware was not responding to the baud 9600 at all


How to correctly code a LED STRIP? I recently bought a 5050 RGB 12V 3A LED strip and I set it all up with my Arduino and run this code (from adafruit website), everything is good:
Example Code
Once you have the strip wired up, it is easy to control the color of the strip by using PWM output, for Arduino you can use

#define REDPIN 5
#define GREENPIN 6
#define BLUEPIN 3

#define FADESPEED 5     // make this higher to slow down

void setup() {
  pinMode(REDPIN, OUTPUT);
  pinMode(GREENPIN, OUTPUT);
  pinMode(BLUEPIN, OUTPUT);
}

void loop() {
  int r, g, b;

  // fade from blue to violet
  for (r = 0; r < 256; r++) {
    analogWrite(REDPIN, r);
    delay(FADESPEED);
  }
  // fade from violet to red
  for (b = 255; b > 0; b--) {
    analogWrite(BLUEPIN, b);
    delay(FADESPEED);
  }
  // fade from red to yellow
  for (g = 0; g < 256; g++) {
    analogWrite(GREENPIN, g);
    delay(FADESPEED);
  }
  // fade from yellow to green
  for (r = 255; r > 0; r--) {
    analogWrite(REDPIN, r);
    delay(FADESPEED);
  }
  // fade from green to teal
  for (b = 0; b < 256; b++) {
    analogWrite(BLUEPIN, b);
    delay(FADESPEED);
  }
  // fade from teal to blue
  for (g = 255; g > 0; g--) {
    analogWrite(GREENPIN, g);
    delay(FADESPEED);
  }
}

I tried to find a way to achieve the same effect but only with two colors...red to yellow..red fade to yellow and fade to red and so on..

EDIT:
Thanks to @majenko I achieved this...Fade from Red to Yellow and back on:

    for (int r = 0; r < 256; r++) {
        analogWrite(REDPIN, r);
        analogWrite(GREENPINPIN, 255 - r);
        analogWrite(BLUEPIN, 0);
        delay(FADESPEED);
    }

    // Fade red down and blue up
      for (g = 0; g < 256; g++) {
        analogWrite(REDPIN, 255);
        analogWrite(BLUEPIN, 0);
        analogWrite(GREENPINPIN, G);
        delay(FADESPEED);
      }

The main difference between what you want and what that code does is that you want to fade both colours at once, but that code is aimed at only fading one colour at a time.

You want to fade R up whilst fading B down, and then fade R down whilst fading B up. The simplest way is with just two loops:

// Fade red up and blue down
for (int i = 0; i < 256; i++) {
  analogWrite(REDPIN, i);
  analogWrite(BLUEPIN, 255 - i);
  delay(FADESPEED);
}

// Fade red down and blue up
for (int i = 0; i < 256; i++) {
  analogWrite(REDPIN, 255 - i);
  analogWrite(BLUEPIN, i);
  delay(FADESPEED);
}

One fade value (i) per loop, and a little bit of maths to turn 0-255 into 255-0 for the value you are fading down.

For Red->Yellow->Red you just need to keep red on and fade green on and off.  You already have code to fade green on and off in your original program:

  // fade from red to yellow
  for (g = 0; g < 256; g++) {
    analogWrite(GREENPIN, g);
    delay(FADESPEED);
  }

  // fade from teal to blue
  for (g = 255; g > 0; g--) {
    analogWrite(GREENPIN, g);
    delay(FADESPEED);
  }

Couple that with setting the red and blue to on and off respectively, and you have:

#define REDPIN 5
#define GREENPIN 6
#define BLUEPIN 3

#define FADESPEED 5     // make this higher to slow down

void setup() {
  pinMode(REDPIN, OUTPUT);
  pinMode(GREENPIN, OUTPUT);
  pinMode(BLUEPIN, OUTPUT);

  analogWrite(REDPIN, 255);
  analogWrite(BLUEPIN, 0);
}

void loop() {
  int g;

  // fade from red to yellow
  for (g = 0; g < 256; g++) {
    analogWrite(GREENPIN, g);
    delay(FADESPEED);
  }

  // fade from yellow to red
  for (g = 255; g > 0; g--) {
    analogWrite(GREENPIN, g);
    delay(FADESPEED);
  }
}


Rasberry Pi Controlling Arduino - Reads "Ghost" Input - Doesn't Complete Logic Loop I am using an Arduino Atmega2560 clone, I have used it many times before with satisfactory results - although I haven't used it with my Rpi before.
My Raspberry Pi is model 4 (B I think?).
#define knap 49
#define motorOutput 8

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(knap, INPUT);
  pinMode(motorOutput, OUTPUT);
  digitalWrite(motorOutput, LOW);
}

void loop() {
  // put your main code here, to run repeatedly:
  int knapSensor = digitalRead(knap);
  Serial.print(knapSensor);
  if (knapSensor == 1) {
    int knapSensor = digitalRead(knap);
    Serial.print("aktiveret");
    digitalWrite(motorOutput, HIGH);
    delay(500);
    digitalWrite(motorOutput, LOW);
  }
}

Now I have double checked, the motor and the button is wired correctly. There is no hardware issue, aside from the cables being sh- quality.
Problem is, whenever I run this program two things will happen;
Either it starts fine by displaying "0000..." on the serial monitor.
Then when I press the button it goes to
"AktiveretAktiveretAktiveret..." even when I depress the button.
Or, it will just display "AktiveretAktiveretAktiveret...".
In either case the motor won't work.
Once again, I have done tests where I have removed the power from the breadboard and replaced the voltage pin for the motor with the voltage pin leading from the button.
First thing didn't change the input (i.e still "AktiveretAktiveret,") the latter started the motor.
I.e this isn't about bad wiring.
EDIT:
Added schematics and changed the code

What motor are you using? If it works straight from the 5v but not from a GPIO, it could be an issue of insufficient power.
As @StarCat4 mentioned, you also need to add a digitalRead inside your while loop if you want the motor to ever turn off.


Knowing the Ohms of a Radio Speaker I have extracted a speaker frim a cheap radio. And I want to connect it to arduino uno. But, I dont know the rating of the speaker. And I am Afraid that If it is over rated, it can fry my arduino. The diameter of the speaker is 9 cm (approx). Whether this Speaker is more likely to be  of 4 ohms, 8 ohms, or 16 ohms ???
I dont have a multimeter...What cam be the probable value of speaker ?

I googled "measure speaker resistance" and found http://www.wikihow.com/Measure-Speaker-Impedance

Step by step instructions

You will need a multimeter - a great thing to have in any case.


Is it possible to use two encoders with Arduino Uno? I would like to control 2 motors with the Arduino Uno board, which provides only two interrupt pins on digital 2 and 3.

I've set one encoder using these pins, and it works. What do you think about the following approaches:

Timer Interrupt:

Create a Timer Interrupt.
Connect the seconder encoder to an analog pin.
Set an analog read function in the interrupt service routine.
Change the prescaler of the ADC and increase the acquisition time.

PinChangeInt

Use PinChangeInt to capture the pin change interrupt rather than an external interrupt.

  This should allow you to use almost any I/O pins on the Uno for the
  encoder.

  as Ignacio Vazquez-Abrams suggested here

It is very possible. use a separate interrupt pin for Phase A of both motors, then read phase B from a non interrupt pin in the interrupt handler.
http://www.spiked3.com/?p=5501


Sharp GP2Y0A710K0F IR sensor behaving strangely I have just purchased a new Sharp GP2Y0A710K0F IR sensor online. As a sanity check, I wrote this simple code to check if the sensor is working correctly. The code is expected to print output voltage from the sensor, which is based on the distance

int sensorpin = A5;
int val = 0;

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

void loop()
{
val = analogRead(sensorpin);
Serial.println(val);
delay(100);
}

Now the output is quite strange. The output values start from zero and keep on increasing until they reach 1023, and then gradually decrease down to zero and this keeps on happening, even if something is kept in front of the sensor.

Is my sensor a faulty one? or is it supposed to give out similar outputs. If it has to, how do I convert these values to meter or centimeters.

The product description on the manufacturer's website said that it has a 3 pin interface, however it has a 5 pin one, the wires being Red, Black, Yellow, White, Green if seen from the left side. I guessed from the datasheet that Red and Black are for power and Yellow for signal output and hence I have connected only these 3 wires. The Green and White wires are unconnected. Also, pin numbers aren't marked.

I suspect you have it wired wrongly.

You need to consult the outline diagram in the datasheet and work out which colour wire is which function. It's this bit:

By your wiring description it sounds like you may be powering it through Vo and reading the result through VCC, which won't work - and at worst may damage it.


Can I write to Flash Memory using PROGMEM? On the documentation of Arduino, I quote:

  http://playground.arduino.cc/Learning/Memory
  Note: Flash (PROGMEM) memory can only be populated at program burn time. You can’t change > the values in the flash after the program has started running.

And on the PROGMEM description:

  http://arduino.cc/en/Reference/PROGMEM
  Store data in flash (program) memory instead of SRAM. There's a description of the various types of memory available on an Arduino board.

  The PROGMEM keyword is a variable modifier, it should be used only with the datatypes defined in pgmspace.h. It tells the compiler "put this information into flash memory", instead of into SRAM, where it would normally go.

So can we or can't we? Or it's not the same thing?

The short answer is no: PROGMEM data is read-only.

Flash memory limitations
The first thing to understand is that Flash memory (where program space lives) is designed for long-term fixed storage. Reading from it is very fast and precise. However, generally speaking, you can't modify it on a byte-by-byte basis (e.g. changing a specific variable). You usually have to erase and re-write it in large blocks. That makes it completely impractical for run-time manipulation, because you'd have to store a lot of redundant information somewhere else while you do the erase and write cycle.

What PROGMEM actually does
Any literal data specified in your code (such as strings and numbers) always reside in program space at first (i.e. in Flash). However, when your sketch actually wants to use that data at runtime, it normally has to allocate some space for it in SRAM and copy it over. That means you end up with two copies: the fixed original in Flash, and the temporary copy in SRAM.

When you use the PROGMEM modifier, you're telling it not to make that second copy in SRAM. Instead, your sketch will simply access the original in Flash. That's very useful if you only ever have to read the data, as it avoids the allocation and copy operations.

However, copying it to SRAM is essential if you want to modify the data. Aside from the Flash limitations I mentioned above, it's also a question of code safety.

If you're able to modify the data stored in program space, then it follows logically that you could also modify the code stored in program space. That would mean that a simple mistake (or in theory a malicious attack) could result in your sketch being partially or fully rewritten at run-time. This could have very unpredictable results, ranging from simply ceasing to work, through to damaging/destroying any connected equipment.

More information
You can learn more about the low-level PROGMEM stuff from here:

http://www.fourwalledcubicle.com/AVRArticles.php

An older version of the same PROGMEM tutorial is available here:

http://www.avrfreaks.net/index.php?name=PNphpBB2&file=viewtopic&p=243018


Which is RX and TX pin of the HM-10 module? i recently bought hm-10 ble module which works using cc2541 ti SOC but problem is there are many ports the the bluetooth module but the seller has not mentioned which is rx and tx pins so...
I wanted to connnect it with Arduino uno and use AT commands but now i am stuck can anyone in this community help me finding which pin is Tx and Rx and the data sheet of the module is difficult to find on the net .....

That's not an HM-10 but an EY-08. It's the same chip, but it's been provided in a different footprint (and maybe with different firmware installed).

Pin P03 is TX and pin P02 is RX.

The AT command set, pinouts, and examples for wiring it are detailed here (Thanks to Mikael Patel for finding that link).


Arduino UNO and SPI eeprom (AT93C46D) I'm trying to write to and read from an AT93C46D eeprom using an Arduino UNO but for some reason the output I'm getting is not what I expect.

The eeprom has a data structure of 128 words of 8 bits each and I'm trying to write 10000010 to each word. When reading back the data however I get 11000001.
When I write 00000000 to all words I get 10000000 for all words when reading. I tested my code on 2 AT93C46D eeproms and both gave the same result.

It looks like the MSB is always 1 (when reading) for some reason.

I'm probably making a stupid mistake but I can't seem to find it, any help is greatly appreciated!

Datasheet: http://www.atmel.com/images/atmel-5193-seeprom-at93c46d-datasheet.pdf

#include<SPI.h>
#define DATAOUT 11//MOSI
#define DATAIN  12//MISO
#define SPICLOCK  13//sck
#define SS 10//ss

void setup()
{
  pinMode(SS,OUTPUT);
  pinMode(DATAOUT, OUTPUT);
  pinMode(DATAIN, INPUT);
  pinMode(SPICLOCK,OUTPUT);
  digitalWrite(SS,LOW);

  Serial.begin(9600);

  SPI.beginTransaction(SPISettings(2000000, MSBFIRST, SPI_MODE0));

  fill();

  dump();
}

void loop()
{

}

void fill()
{
  Serial.println("Send EWEN opcode");
  digitalWrite(SS,HIGH);
  SPI.transfer(B10011); //EWEN
  SPI.transfer(B0000000);
  digitalWrite(SS,LOW);

  delay(100);

  for (int i=0; i < 128; i++) {
    digitalWrite(SS,HIGH);
    SPI.transfer(B101);
    SPI.transfer(i);
    SPI.transfer(B10000010);
    delay(10);
    digitalWrite(SS,LOW);
  }

  delay(100);

  Serial.println("Send EWDS opcode");
  digitalWrite(SS,HIGH);
  SPI.transfer(B1000); //EWDS
  SPI.transfer(B00000000);
  digitalWrite(SS,LOW);

  delay(10);
}

void dump(){
  Serial.println("Dumping AT93C46D");

  byte b;

  for (int i=0; i < 128; i++) {
    digitalWrite(SS,HIGH);
    SPI.transfer(B110); //read opcode
    SPI.transfer(i);
    b = SPI.transfer(B00000000); //clock data out
    digitalWrite(SS,LOW);
    Serial.println(b, BIN);
  }
}

After looking at the product spec again I think it might be possible to get this working. The protocol is MSB with a start bit S followed by two bit op-code, and parameters. SPI on AVR is 8-bit transfer but transfer can be byte aligned with the start bit.

READ is op-code(10) followed by 7-bit address, a dummy bit and the read value. That is in total 11+8-bits. Mapping that to 8-bit transfer would be:

spi.transfer(0b110);
spi.transfer(addr << 1);
data = spi.transfer(0);

That will give 5-bit zero, start-bit, op-code in the first transfer, and followed by 7-bit address and dummy bit (LSB) in second transfer. The third transfer is the read data.

EWEN would map to:

spi.transfer(0b1001);
spi.transfer(0b10000000);

EWEN has op-code(00), followed by 9-bits, 0b11XXXXXXX.

The WRITE operation becomes:

spi.transfer(0b10);
spi.transfer(0x80 | addr);
spi.transfer(data);

Cheers!


How come my code does not wait for a specific time before going into an if statement? I have an HC-SR04 attached to a servo. When the 90 degree reading is less than 30 cm, I want the motor to take 2 seconds to turn to 130 degrees, get a measurement on the right, and turn back to 90 degrees. My code does not seem to work. Even though I tell it to wait for 2000 ms, it skips directly to the if statement where the turning to 90 degrees is done. Here is the main code:

 #include <Servo.h>
#define trig 22
#define echo 24
long duration;
boolean turned130 = false;
int cm50, cm, cm130;
Servo servo;
boolean checkRight = false;
boolean mainPing = true;
unsigned long counter;
unsigned long servoTimer = millis();
void setup() {
  // put your setup code here, to run once:
Serial.begin(9600);
pinMode(echo, INPUT);
pinMode(trig, OUTPUT);
servo.attach(12);
servo.write(90);
delay(2000);

}

void loop(){
counter=millis();//my timer
  if(((counter-servoTimer) >= 250) && mainPing){//distance measured 4 times a second
    ping();
    cm=duration/29.1/2;
    Serial.println(cm);
    servoTimer=counter;//this if statement works fine
  }
  if((cm<30) && mainPing){

    mainPing=false;//makes the 90 degree ping and this if statement unable to run
    checkRight = true;//enables next if statement to run
    servoTimer=millis();
    servo.write(130);
    cm=30;//so that this if statement does not get called again until distance is obtained
    Serial.println("Inside less than 30 loop");//I added this for debugging, to let me know when the loop is called

  }
  if(checkRight && ((counter-servoTimer) >= 2000)){//after 2 seconds passes

    checkRight=false;
    ping();
    cm130 = duration/29.1/2;
    mainPing = true;//enable to other 2 if statements to run
    servoTimer=millis();
    Serial.println(cm130);
    servo.write(90);//turn motor back
    Serial.println("Inside other loop");//for debugging

  }

  delay(2);
  }

void ping(){

    digitalWrite(trig, LOW);
    delayMicroseconds(2);
    digitalWrite(trig, HIGH);
    delayMicroseconds(10);
    digitalWrite(trig, LOW);
    duration = pulseIn(echo, HIGH);

}

This is what I got in the Serial monitor:

25//distance triggers 2nd if statement
Inside less than 30 loop
261
Inside other loop
13
Inside less than 30 loop
14
Inside other loop
14
Inside less than 30 loop
14
Inside other loop
3242
13
Inside less than 30 loop
14
Inside other loop

This all happened within milliseconds. There was no 2 second pause and the servo never turned. What is wrong with my code that prevents the motor from turning and waiting 2 seconds? The order of the Serial messages is correct, but it is happening fast.

EDIT:

When I remove the Serial messages and disconnect from the computer, it kind of works. By that, I mean it turns and waits for 2 seconds 50% of the time. Other times, the servo just shakes a little bit and stops.

Another thing I noticed is that if I leave only Serial.println(cm) message and Serial.println("Inside less than 30 loop"), this is the result that I observe.

    12
    13
    Inside less than 30 loop

    15
    3
    Inside less than 30 loop

For some reason the loop does not get triggered the first time. Is there a possibility that I have a defective Arduino Mega?

EDIT 2:

I tested the same setup on an official Arduino Uno and it did not work either. This means that I do not have a broken Arduino. Could the servo motor be broken? That won't explain the Serial messages though.

I added some more debugging, and I think I have your issues detected.

Amended code:

#include <Servo.h>
#define trig 22
#define echo 24
long duration;
boolean turned130 = false;
int cm50, cm, cm130;
Servo servo;
boolean checkRight = false;
boolean mainPing = true;
unsigned long counter;
unsigned long servoTimer = millis();
void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  pinMode(echo, INPUT);
  pinMode(trig, OUTPUT);
  servo.attach(12);
  servo.write(90);
  delay(2000);
}

void loop() {
  counter = millis(); //my timer
  if (((counter - servoTimer) >= 250) && mainPing) { //distance measured 4 times a second
    Serial.print ("Doing ping at time ");
    Serial.println (counter);
    ping();
    cm = duration / 29.1 / 2;
    Serial.println(cm);
    servoTimer = counter; //this if statement works fine
  }
  if ((cm < 30) && mainPing) {

    mainPing = false; //makes the 90 degree ping and this if statement unable to run
    checkRight = true;//enables next if statement to run
    servoTimer = millis();
    servo.write(130);
    cm = 30; //so that this if statement does not get called again until distance is obtained
    Serial.println("Inside less than 30 loop");//I added this for debugging, to let me know when the loop is called
  }
  if (checkRight && ((counter - servoTimer) >= 2000)) { //after 2 seconds passes
    Serial.print ("counter = ");
    Serial.println (counter);
    Serial.print ("servoTimer = ");
    Serial.println (servoTimer);
    checkRight = false;
    ping();
    cm130 = duration / 29.1 / 2;
    mainPing = true;//enable to other 2 if statements to run
    servoTimer = millis();
    Serial.print ("cm130 = ");
    Serial.println(cm130);
    servo.write(90);//turn motor back
    Serial.println("Inside other loop");//for debugging
  }
  delay(2);
}

void ping() {
  digitalWrite(trig, LOW);
  delayMicroseconds(2);
  digitalWrite(trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(trig, LOW);
  duration = pulseIn(echo, HIGH);
}

With no server (or anything) attached I get this output:

Doing ping at time 1999
0
Inside less than 30 loop
counter = 1999
servoTimer = 2693
cm130 = 0
Inside other loop

First note that servoTimer is somewhat higher than counter because the pulseIn function takes a while to execute (times out after 1 second allegedly, although that was less than a second).

Now we come to the problem "if" statement.

  if (checkRight && ((counter - servoTimer) >= 2000)) { //after 2 seconds passes

That can't be right, eh? counter is 1999 and servoTimer is 2693, and there is not 2000 difference. However you are doing the maths the other way:

counter - servoTimer =  1999 - 2693 = -694

Since we are using unsigned long, it cannot hold negative numbers so the result of the subtraction is 4294966602.

That is much larger than 2000, so the "if" branch is taken.


Nick Gammon "Camera shutter speed timer" I am reading the period of pulses from a 600ppturn shaft encoder, using the FreqPeriod library, by Martin Nawrath.

This works using counter1 and the comparator on pin6 and pin7 on the Arduino Uno.

The period duration for 1-2500Hz is being used in a midi musical instrument to give a speed to volume and a note change at a fixed speed.
This has worked well on the Uno but now I want to use a Mega (which does not have both comparator pins).

So I have tried using the Nick Gammon interrupt sketch. This has produced very erratic results returning both positive and many negative numbers (shown by using "volatile long period;" in the monitor.

Can you tell me what is happening and would it be better to use a counter instead of interrupts?

Hope I have given enough information to be getting on with, many thanks.

// Camera shutter speed timer
// Author: Nick Gammon
// Date: 15th January 2012

volatile boolean started;
volatile unsigned long startTime;
volatile unsigned long endTime;
volatile unsigned long period;
volatile unsigned long lfrq;

// interrupt service routine
void isr () {
    if (started)
        endTime = micros ();
    else
        startTime = micros ();
    started = !started;
} // end of Pulse Width

void setup () {
    digitalWrite (2, HIGH); // pull-up
    Serial.begin (9600);
    Serial.println (" Pulse Width test = ");
    attachInterrupt (digitalPinToInterrupt (2), isr, CHANGE); //CHANGE RISING
} // end of setup

void loop () {
    if (endTime) {
        period = (endTime - startTime) * 32 ; // pulse width?
        Serial.print (" \n  ");
        Serial.print ( " period =  ") ;
        Serial.print (period) ;
        lfrq = 16000000.0 / period;
        Serial.print(" Hz = "); // one rev per sec = 26666 micros period
        Serial.print( lfrq );
        endTime = 0;
    }
} // end of loop

Can you tell me what is happening [...]?

Not really, but here is a wild guess: your input signal is bouncy, the
ISR fires too often, your loop cannot keep up with the rate, and you end
up accessing endTime in the ISR and loop simultaneously.

If you have a scope, look at your encoder signal. Is it clean?

  would it be better to use a counter instead of interrupts?

Using the input capture feature of a timer will give you the best
possible accuracy, as you will have single-cycle resolution. In
contrast, micros() has only 4 µs resolution (64 times worse) and
the ISR may be delayed by up to ≈ 16 µs by the TIMER0_OVF
ISR.

You can use the FreqPeriod library you linked to as an inspiration for
writing your own timer-based code, but it will require some changes:

As pointed out by Nick Gammon in a comment, you don't need the analog
comparator, nor the conditioning RC network, as the encoder's outputs
are already digital. Or you may use a low-pass filter if the encoder
is bouncy.
You will use the input capture pins of either timer 4 (digital pin 49)
or timer 5 (digital pin 48). The other input capture pins are not
available on the Mega's pin headers.
You will replace ISR(ANALOG_COMP_vect) by either ISR(TIMER4_CAPT)
or ISR(TIMER5_CAPT) (the relevant “capture event” ISR). No need to
adjust a comparator threshold in the ISR.
In the begin() method, you will leave the analog comparator alone,
and you will enable the capture event interrupt.

Obviously you will have to study the
datasheet
before start coding.


Why is my transistor always transmitting? I want to use a transistor to turn on and of an electric magnet, I have hooked up a transistor like this:

simulate this circuit – Schematic created using CircuitLab

The blue wire goes to the magnet and the white wire goes to the ground:

Regardless of if the arduino is on or off(I can even unplug port 12 from the arduino, the magnet is still on, the circuit never closes. What do I need to do to make the transistor turn off?

Darlington transistors are very sensitive; even putting your hand near it can be enough to turn it on. Either tie the base to ground with a large resistor or switch to a MOSFET with its gate tied to ground through same. In either case put a diode backwards across the coil to absorb the energy from the coil when it de-energizes so that the transistor is not damaged.


What is wrong with this processing code? I have written a processing code to work along with my arduino code for the arduino UNO. In this I'm trying to control the colour of the processing window by the arrow keys. However, I'm doing this in a bit roundabout manner because I wanted to see how the 2 codes work together to exchange information.

The processing code:

import processing.serial.*;
Serial port;
int data=0;
char c;

void setup()
{
 port=new Serial(this,"COM3",9600);
 background(0,0,0);
 size(500,500);
}

void draw()
{
 if(port.available()>0)
  {
data=port.read();
c=(char)data;
if(c=='U')
   background(255,0,0);
if(c=='D')
   background(0,255,0);
if(c=='L')
   background(0,0,255);
if(c=='R')
   background(255,255,0);
}//end of if
}

void keyPressed()
{
 if(key==CODED)
 {

  if(keyCode==UP)
     port.write('u');
  if(keyCode==DOWN)
     port.write("d");
  if(keyCode==LEFT)
     port.write("l");
  if(keyCode==RIGHT)
    port.write("r");

 }
}

The arduino code:

// Arrow key controller

char data;

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

}

void loop()
{
 while(Serial.available()>0)
  {
   data=Serial.read();
   if(data=='u')
      Serial.print("U");
   else if(data=='d')
      Serial.print("D");
   else if(data=='l')
      Serial.print("L");
   else if(data=='r')
      Serial.print("R");
  }

}

Here what Im doing is, i'm reading the arrow key press from processing. The correspoding small case letter is printed into the serial buffer, eg u for UP.
The arduino code reads this letter(u) from the serial buffer and prints the corresponding upper case letter(U) into the serial buffer. The processing code then reads the uppercase letter from the buffer and changes the colour accordingly.
But nothings happening when i push the arrow keys. What's wrong?

As @Matt said,

  The problem you have is not with the Arduino

Put if(port.available()>0) in the timer, or as event instead of void draw(). Furthermore, I can't found the calling of draw in your code.


Remote Controlled Self-Balancing Robot - how to mix control input with IMU input? I'm building a two-wheeled, self-balancing, remote-controlled robot. I'm familiar enough with the IMU and PID to get it working to just stand up but I need to drive it via remote control.

I've got no code written yet; trying to understand the concepts before diving in.

This much I understand: [IMU] -> [Kalman filter] -> [PID] -> [Motors]

Where I'm getting tripped up is where to mix the RC component into that control chain?

The PID get's a set point from you. For a standing still robot this a basically an angle of zero in respect to the gravity direction (which variable you use for the PID depends on your actal implementation, but it always be something derived from the angle to gravity direction). For driving forward, the robot must lean forward. So you set the new angle set point to let's say 2 degrees. The PID will try to hold that value by driving forward constantly, with a speed depending on the set angle.

So, via the remote control you simply change the angle setpoint.


1 Wire temperature sensor I bought a waterproof temperature sensor from Ebay, I am fairly new to this and not sure what I need or need to do in order to get the sensor to output the current temperature to the serial monitor.

Does anyone have any information on where I can get some information on how to wire this? I have looked at various videos online but they are all for a dallas temp sensor and use the dallas library.

http://www.ebay.co.uk/itm/181393039374?ssPageName=STRK:MEWNX:IT&_trksid=p3984.m1439.l2649

This probe has the Dallas (now Maxim) DS18b20 sensor in it so you're already on the right track. Search for DS18b20 at arduino.cc. You'll find libraries and lots of forum discussions about using these sensors.
Also see page 6 of the DS18b20 datasheet; there are two schematics for wiring the device.

I'm using the parasitic mode (Figure 4 on that page) except I eliminated the transistor switch and connected the MCU pin for the strong-pullup directly to the one-wire bus.


Setting Time to UTC with Data Logger Shield (with RTC DS1387) I own an Adafruit Data Logger Shield https://www.adafruit.com/product/1141

I followed this tutorial
https://learn.adafruit.com/adafruit-data-logger-shield/using-the-real-time-clock

This part of code

if (! rtc.initialized()) {
  Serial.println("RTC is NOT running!");
  // following line sets the RTC to the date & time this sketch was compiled
  rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));

adjust RTC to computer date/time... but it's using computer local date/time.

I'd prefer to use UTC date/time but I haven't find a convenient way to do this (except modifying computer date/time which is not very convenient as I want to always be able to reprogram Arduino without hassle of changing local time each time).

There are several approaches you could use.

• Edit 1: On your development system, you could write a shell script or a batch file to write a file, say myUTCtime.h, containing a source-code line like char *MyUTCtime = "23:59:01"; and somewhere in your sketch say #include "myUTCtime.h".  Eg, to create the file in Linux: echo "char *MyUTCtime = \"$(date -u '+%H:%M:%S')\";" > myUTCtime.h which on my system produced file myUTCtime.h containing char *MyUTCtime = "08:20:36";

• You could define a different time constant, for example by adding -DMyUTCtime="23:59:01" into the gcc or g++ command line.  (Substitute an appropriate time.)  On Linux, this might look like -DMyUTCtime=$(date -u '+%H:%M:%S').  In your code you would write #MyUTCtime in place of  __TIME__.  Edit 1: Note, this is difficult to automate when using the Arduino IDE.  It is somewhat easier if using an Arduino Makefile.  For example, on Linux one might say MyUTCtime=$(date -u '+%H:%M:%S') make (which defines MyUTCtime with the current UTC time, and passes the MyUTCtime into make) and within the makefile, say (eg)

ifdef MyUTCtime
  CPPFLAGS += -DMyUTCtime=${MyUTCtime}
endif

• You could write your sketch to accept a time-setting command via serial input.  To set the time, you would send the time-setting command and the current time in UTC, via serial monitor.

• As Mikael Patel mentioned, you could modify the __TIME__ string to represent UTC before using it to set the RTC.  Here is an example of how to add or subtract an appropriate offset to __TIME__ to adjust it to UTC.  For example, if your offset is an hour ahead of UTC, you would change

rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));

to

char *compileTime = __TIME__;
compileTime[1] += 1;
if (compileTime[1] > '9')   // Check for carry
   ++compileTime[0];        // Add the carry
rtc.adjust(DateTime(F(__DATE__), compileTime));

This code has at least two problems:
• If the compile occurs between 23:00:00 and midnight, the resulting hour will show as 24 instead of as 00 on the next day. One could of course adjust the day of the date, and if that overflows, adjust the month, and if that overflows, adjust the year; or, more simply, one could produce an error in the compile.
• While a 1-hour offset may be appropriate during DST, a 2-hour offset may be appropriate most of the year.  One could of course check the date and use a date-appropriate offset of 1 or 2.


ESP.deepSleep() - over and over? Important note: the esp.deepsleep function uses microseconds, not milliseconds.

I posted another question here asking for clarification on how an RTC can be used to put a NodeMCU 12 to sleep for a long time (~24hrs or more).

This question concerns the use of ESP.deepSleep([microseconds]) with the NodeMCU 12 board.  There is a discussion here and I have followed the advice but have been unable to successfully implement the ESP.deepSleep() function using the Arduino IDE and a NodeMCU 12 board.

Initial findings:
-Connecting gpio16 (D0) to the RST pin causes a reset immediately upon entering sleep.  The entire boot process and loop are repeated over and over again.
-Simply using the ESP.deepSleep() function without gpio16-to-RST generates gibberish on the serial monitor and illuminates the red led on the board.

My code is here (I just drop "deepsleep();" where I want the sleep process to begin):

void deepsleep() {
  Serial.println("sleeping hr 1");
  ESP.deepSleep(3600000); //1hr
  delay(100);
  Serial.println("sleeping hr 2");
  ESP.deepSleep(3600000); //2hr
  delay(100);
  Serial.println("sleeping hr 3");
  ESP.deepSleep(3600000); //3hr
  delay(100);
  Serial.println("sleeping hr 4");
  ESP.deepSleep(3600000); //4hr
  delay(100);
  Serial.println("sleeping hr 5");
  ESP.deepSleep(3600000); //5hr
  delay(100);
  Serial.println("sleeping hr 6");
  ESP.deepSleep(3600000); //6hr
  delay(100);
  Serial.println("sleeping hr 7");
  ESP.deepSleep(3600000); //7hr
  delay(100);
  Serial.println("sleeping hr 8");
  ESP.deepSleep(3600000, WAKE_RF_DEFAULT);  //8hr
}

What is wrong with this approach and why am I (apparently) causing an error?

Use a resistor between GPIO16 and RST. I usually use a 470 Ohm resistor. Shorting the pins with a wire does not work.

https://www.esp8266.com/viewtopic.php?t=14350#p64510

Maximum deep sleep is about 71 minutes. 3600000 microseconds = 3.6 seconds, not 1 hour. 1 hour in microseconds is 3600000000UL.

As mentioned in the comments, waking from deep sleep on the ESP8266 is a hardware reset so execution begins at the start of the setup function.


Simple LED circuit is not working This is my first circuit ever (!) and so I'm hoping that I'm just making an easy-to-spot rookie mistake. I am trying to power an Arduino Due with a 9V battery and then have the Due in turn power a red LED. No blinking. No sketchpad/C program flashed to the chip. Just straight up electricity:

When I connect the battery, several things happen:

There is a green power LED on the Due that lights up; and
Right next to it is an orange LED (on the Due itself) that blinks every few seconds (not sure what this LED is or what the blinking means, but providing that detail for good measure); and
The red LED on the breadboarrd does not light up

This is a 2V/15mA LED, and as you can see I'm powering it from the 5V power jack on the Due. So a 220 ohm resistor should be perfect for it (R = (Vs - V) / I = (5V-2V) / .015A ~= 220 ohms).

So, for the first time ever, I busted out my multimeter, set it to the voltage setting, and started testing the circuit. First I tested Vin and GND on the Due (that is, the connection between the battery and the Due), and the multimeter lit up and hovered (correctly) around 5V. So far so good. Next I tested the power and ground connections on the breadboard power rails (indicated in green above). Again, the multimeter reported a roughly 5V power supply. Then I tested the connection from the power rail to the row (purple in pic above) feeding power to the resistor, and to my surprise, the multimeter reports no power at those two purple locations.

My understanding was that the power rail will power the entire column its connected to (in my case, the left-most column), and then any rows connecting to a power rail/column will also be powered. So I'm not understanding why there's voltage on my power rail/column, but not on the wire connecting my power rail to the resistor. Any ideas?

Update:

Here is my corrected circuit per initial feedback. Please note this is still not working, but I think I'm getting close:

What connects the resistor to the LED?

Absolutely nothing.

It's hard to work out which holes the LED is plugged into, but I think your current circuit looks something like this:

You need to connect that resistor and LED together.

For your edit:

Now your circuit looks like this:

Behind the 5 pins in that column with the ground wire there is a big chunk of metal connecting them all together.  It's no different to if you'd taken the LED and twisted the pins together into one.  There's no way the power can get up one and down the other when they are connected together like that.  You need to separate them into different columns.

And this is how the (black) connections inside are laid out, and how your (red) electricity is flowing:

And here is how the circuit should look, using a program called Fritzing.  It's a pretty basic design tool, but great for showing wiring.

You can see how the green highlighting shows the columns that are connected.


How to control 2 servos at same time in sync? For overcoming torque issues, I have attached 2 identical servos on a certain part of my robot arm and because I saw someone do the same.

Now, while writing code I realize:

#include <Servo.h>
...
...
shoulder1.write(map(analogRead(p1), 0, 1023, 0, 179));
shoulder2.write(map(analogRead(p1), 0, 1023, 0, 179));
...

will turn shoulder1 by 20* and then shoulder2 by another 20*, ie. an overall turn of 40*; that too with too much load on servos, as the other servo would be inactive at the time first is active.

I want to achieve 20* fully-sync.ed turn on both servos, how do I accomplish this? Any arduino libraries or walkthrough?

Can I possibly move them both at the same time - something like multithreading on arduino? Here's what I tried:

void rotateTwoServoInSync(int angle) {
    for(int i = 0; i<angle; i++) {
        shoulder1.attach(9);
        shoulder1.write(i);
        shoulder1.detach();
        shoulder2.attach(10);
        shoulder2.write(i);
        shoulder2.detach();
    }
}

Will it work? Is this approach recommendable?

If you have two RC servos that are always required to move together you can simply connect both control inputs to a single output.


Slow refresh rate of 1.8 TFT display I have 1.8 TFT display for Arduino Nano and it changes color very slow. When I try to change the color of the whole screen I see how it changes color line by line. I use "Adafruit GFX graphics core" and "Adafruit ST7735" libraries to change colors.

Question: Slow refresh rate of 1.8 TFT display is due to limited computation capability of Arduino or 1.8 TFT display itself or library used?

The ST7735 TFT uses SPI to communicate. That can never be particularly fast.

At 160x128 pixels with 16-bit colour depth that gives you 327680 bits that you need to transfer just for the colour data.  On top of that you have 88 bits to set up a drawing window (11 bytes of "set X coordinate and width" [5 bytes], "set Y coordinate and height" [5 bytes] and "start drawing" [1 byte]).

That's a total of 327768 bits that you need to transfer.

Now the transferring of that data is at the mercy of the SPI clock speed. How fast that can go depends on what the ST7735 can work at and the quality of your wiring (if it's a shield you can almost discount the wiring).  Assuming you can operate at the maximum 8MHz that the Arduino can run SPI at (which is probable) then you get:

8,000,000
---------   =  24.4 frames per second
 327768

That is the absolute maximum theoretical speed, and doesn't take into account any work done by the Arduino to actually send the data. The SPI library is completely blocking in its operation and each pixel has to be sent separately as one blocking transaction. So you can expect about half that rate in reality, if not less, while it loops around and sends each pixel, then blocks waiting for the pixel to be sent.

And of course that's assuming running at the maximum speed. In reality that probably isn't happening. Libraries that use SPI often choose the "lowest common denominator" for their SPI speed (if they actively choose a speed at all) so that the library "just works" in the majority of cases. So the speed the library is running at will most likely be considerably lower than the actual maximum speed you could run at.

For example, if it runs at 1MHz instead of 8MHz then you will get about 3 frames per second (which is more like what you are describing).

So examine your chosen library and see what it does in the way of configuring the SPI speed. If it doesn't do anything then consider adding code to increase the speed. If it does then consider increasing the speed it operates at (see the SPI library reference for more details).

TBH, though, a small Arduino is seldom a good choice to control a TFT screen. At the bare minimum you really need a chip with far more memory so you can draw graphics "off-screen" in a framebuffer, and then use DMA to transfer that off-screen buffer to the TFT screen over a 16-bit parallel connection at high speed while leaving the CPU free to do other jobs.  Or even better a microcontroller with a built-in TFT controller to directly generate the correct drive signals for a TFT panel and store the whole screen image in internal RAM.


Is it possible to do an OTA update using a GitHub link I need to be able to download software updates through the internet without having my MKR1000 plugged in. Either that or have new code being pushed from my server (C++) to my MKR1000, and then rebooting with the new code.
Any help is useful.
Thanks.

It may be possible if you can write your own bootloader, but it certainly won't be easy.

The normal way of doing OTA updates is to use a chip that has segmentable and remappable flash memory (such as the ESP32, ESP8266, PIC32MZ, etc) where your sketch is running from one segment, and that loads the new code from whatever source into the other segment. It then changes a single boot flag and resets the MCU, and the MCU then maps the second segment into the place of the first (swaps the two segments over) and runs the new code.

That can't be done with the SAMD21 since it has no remappable flash memory segments.

So the best you could hope for would be to reboot into a custom bootloader which then connects to the internet to download new code to flash into the main portion of the flash memory. And of course that would replace the existing bootloader and take a lot of work to create.

Addendum:

Apparently there is the "WiFi101OTA" library which allows over-the-air updates on SAMD21 boards. By all accounts this receives the new code and stores it away somewhere (a chunk of the internal flash, SD card, etc) and then copies that data to the main portion of the flash using a function running from RAM.

While this sounds good, I would not recommend using it in a live situation. For development it's fine, but not "in the field".

This is simply because there is no protection against "bricking" a unit.  Once the copy from storage to main flash starts you are at the point of never being able to go back. If that write should fail for whatever reason (there is a power outage, or the sketch crashes, or any of a myriad of other unpredictable reasons) the unit is dead.  You would have to manually reprogram the unit with a cable to bring it back to life.

By having the programming done by the bootloader (incidentally, some devices, such as AVR based boards, can only write to flash from the bootloader) the code that does the writing never gets overwritten, so a simple manual reset of the unit can restart the programming and recover the board.

If you were to adopt this library you would of course have to modify it to "pull" the update, not receive a "pushed" update. This should be trivial, but some level of network programming ability would be needed.


Alternatives to read mp3 without using an sdcard as source for the files? I am making a project that plays several sounds using a DFPlayer Mini mp3 player and a micro sd card. The size of the sounds I normally play is less than 20 MB, so a lot of space in the sd card is unused. I was wondering if there is an alternative to use an SD card to store the mp3 files, and if there is, what would be the best approach to switch to use this alternative.

Cheers!

The problem of all alternatives I can think of is a commercial one:Its more expensive than to waste space. So if you look up your facvorite online dealer you will quickly find out that e.g. buying the cheapest 1GB SD card costs double than buying the cheapest 32GB card (6$). So the more space you waste the cheaper. Get an used 512MB or 1GB card (cost in my country around 1$) and be happy with the space reserve.
Of course if saving space is a topic and not money get 20 x 1MB eeprom I2C boards (20*3$ from china), solder the hardware (you'll need some more parts to manage the board addresses), get a power source, write a library for managing the memory and after spending around 100$ and a lot of time you saved up to around 15.98 GB of free space but not the environment.


Sampling rate of multiple analog pins on Arduino as I checked on Arduino website, they mentioned all boards: UNO, Nano, Mini, Mega have maximum sample rate 10kHz for each analog pin. So my concern is:
1) is there any difference between sampling rate when reading a single analog pin and multiple analog pins? For example, if we read only 1 analog input, maximum sample rate can reach 10kHz. How about maximum sample rate when we want to read 6 analog inputs? Maximum sample rate will be 10kHz or (10/6)kHz? Can we do analog input reading simultaneously or not?

2) What if I want to get sampling rate at least 1kHz for each Arduino board (assume 5 analog inputs)?

3) In case we need to connect several Arduino boards via I2C or SPI protocol, is sampling rate related to these 2 protocols?

1)  You only have one ADC on board and all the pins run through a mux.  You can only read one pin at time.  If you're willing to give up some resolution then you might can read a little faster but it gets tough.  What's worse is that when you are switching pins really fast it can mess with your readings so that for some things, especially when input impedance is high, you have to read twice and throw away the first reading.  So that essentially cuts your sampling rate in half right there.

2)  That may be doable.  Or at least something close to it.  You'd run in free-running mode and write a tight ISR to read the interrupt when the analog read is finished and record every other value and switch the pin every other time.  Theoretically you should get pretty close to 1kHz with 5 pins.  Maybe a little faster if you give up a little resolution.

3)  Those communications protocols run at light speed compared to the analog read.


16 bit PWM doesn't go to absolute 0V void setup() {
  Serial.begin(9600);
  setupPWM16();
}

uint16_t icr = 0xffff;

void loop() {
  analogWrite16(9, 0);
}
void setupPWM16() {
  DDRB  |= _BV(PB1) | _BV(PB2);       /* set pins as outputs */
  TCCR1A = _BV(COM1A1) | _BV(COM1B1)  /* non-inverting PWM */
        | _BV(WGM11);                 /* mode 14: fast PWM, TOP=ICR1 */
  TCCR1B = _BV(WGM13) | _BV(WGM12)
        | _BV(CS10);                  /* prescaler 1 */
  ICR1 = icr;                         /* TOP counter value (freeing OCR1A*/
}

/* 16-bit version of analogWrite(). Works only on pins 9 and 10. */
void analogWrite16(uint8_t pin, uint16_t val)
{
  switch (pin) {
    case  9: OCR1A = val; break;
    case 10: OCR1B = val; break;
  }
}

Using the code above I can achieve 16 bit PWM signal, but when writing 0 in analogWrite16 it output ~33mV. I know that I can set the PWM pin low but yet again it don't output 0V.

I'm guessing beside the ATMEGA offset the Arduino UNO board it self ground is raised either because it's being fed from USB or the board circuitry and PCB traces resistance. or both?

because ~33mV offset is a lot, is it normal?

How can I make Arduino to start at 0V or at least reduce that 33mV offset to 1-2mV?

You've got two possibilities:

You can't have full off in "non-inverting PWM" mode
You can't have full on in "inverting PWM" mode

In the Arduino core it's solved by turning off the PWM output and setting logical 0 or 1 for corner values.

And if you need full off but you don't need full on, you can use inverted PWM mode.


Set up an Arduino Cellular Shield SM5100B I'm trying to set up an Arduino Cellular Shield SM5100B to send SMS.

My setup is:

Arduino UNO R2
SM5100B
"Movistar" SIM Card (Chile)

I've uploaded a code similar to the one described here, but when communication is supposed to star it cannot find a network. I suspect the problem is I haven't setup correctly the GSM band. But when I issue the command (AT+SBAND=7, same as in the US), it doesn't respond. How can I check in what band I'm on? And change the band?

/*
 Band Management

 This sketch, for the Arduino GSM shield, checks the band
 currently configured in the modem and allows you to change
 it.

 Please check http://www.worldtimezone.com/gsm.html
 Usual configurations:
 Europe, Africa, Middle East: E-GSM(900)+DCS(1800)
 USA, Canada, South America: GSM(850)+PCS(1900)
 Mexico: PCS(1900)
 Brazil: GSM(850)+E-GSM(900)+DCS(1800)+PCS(1900)

 Circuit:
 * GSM shield

 created 12 June 2012
 by Javier Zorzano, Scott Fitzgerald

 This example is in the public domain.
 */
 // libraries
 #include <GSM.h>

 // initialize the library instance
 GSMBand band;

 void setup()
 {
   // initialize serial communications and wait for port to open:
   Serial.begin(9600);
   while (!Serial) {
     ; // wait for serial port to connect. Needed for Leonardo only
   }

   // Beginning the band manager restarts the modem
   Serial.println("Restarting modem...");
   band.begin();
   Serial.println("Modem restarted.");

 };

 void loop()
 {
   // Get current band
   String bandName = band.getBand(); // Get and print band name
   Serial.print("Current band:");
   Serial.println(bandName);
   Serial.println("Want to change the band you’re on?");
   String newBandName;
   newBandName = askUser();
   // Tell the user what we are about to do…
   Serial.print("\nConfiguring band ");
   Serial.println(newBandName);
   // Change the band
   boolean operationSuccess;
   operationSuccess = band.setBand(newBandName);
   // Tell the user if the operation was OK
   if(operationSuccess)
   {
     Serial.println("Success");
   }
   else
   {
     Serial.println("Error while changing band");
   }

   if(operationSuccess)
   {
     while(true);
   }
 }

 // This function offers the user different options
 // through the Serial interface
 // The user selects one
 String askUser()
 {
   String newBand;
   Serial.println("Select band:");
   // Print the different options
   Serial.println("1 : E-GSM(900)");
   Serial.println("2 : DCS(1800)");
   Serial.println("3 : PCS(1900)");
   Serial.println("4 : E-GSM(900)+DCS(1800) ex: Europe");
   Serial.println("5 : GSM(850)+PCS(1900) Ex: USA, South Am.");
   Serial.println("6 : GSM(850)+E-GSM(900)+DCS(1800)+PCS(1900)");

   // Empty the incoming buffer
   while(Serial.available())
   Serial.read();

   // Wait for an answer, just look at the first character
   while(!Serial.available());
   char c= Serial.read();
   if(c=='1')
     newBand=GSM_MODE_EGSM;
   else if(c=='2')
     newBand=GSM_MODE_DCS;
   else if(c=='3')
     newBand=GSM_MODE_PCS;
   else if(c=='4')
     newBand=GSM_MODE_EGSM_DCS;
   else if(c=='5')
     newBand=GSM_MODE_GSM850_PCS;
   else if(c=='6')
     newBand=GSM_MODE_GSM850_EGSM_DCS_PCS;
   else
     newBand="GSM_MODE_UNDEFINED";
   return newBand;
 }


MB-102 BreadBoard Power Supply Limitation Does the MB-102 can handle Arduino Uno, SIM900 and 3 other modules that requires 5v? If yes, does 9v battery is enough? If no, please suggest me what should I use that uses only 1 barrel jack(if possible).

Im afraid that I might fry it if I try cause I dont have enough knowledge about electric currents.

Does the MB-102 can handle Arduino Uno, SIM900 and 3 other modules that requires 5v?

You mean because the current requirements? The answer is yes and no. No, because the needed current must not flow through the Arduino. The SIM900 draws up to 2A, that current would fry the protection diode/voltage regulator on the Arduino (though you may get away with a bit less than that by using a big capacitor to accommodate current spikes). Depending on the version of the Uno, it can provide 200mA or 1A (in case of rev3)(including what is needed for the Uno to operate). You need to provide the 5V of these modules from outside of the Arduino, via an extra voltage regulator, which can handle the big current.

  does 9v battery is enough?

If you mean the standard 9V block battery, then no, never. These batteries are meant for low power applications and are almost never a good choice for an Arduino project (unless you have really a low power application). You need to use different batteries, for example a series of AA batteries or a LiPo pack (including the needed circuitry for such a pack).


Arduino Wifi Works one way but not the other? (ESP32) (Possible Variable Type Problem) I am working on a code that accepts input from serial monitor and connects to Wifi, and have been getting issues.

my SSID for my wifi is "SamF" but for some reason arduino only likes it when I initialize at the top, not when I accept it from serial monitor even though they are the same..

Example The below code works:

#include <WiFi.h>

char ssid[] = "SamF"; //OR const char* = "SamF"
char pass[] = "secretPassword";
void setup()
{
WiFi.begin(ssid, pass);
}
void loop () {}

The Code Below Does not work..

#include <WiFi.h>
char pass[] = "secretPassword";
void setup()
{
ssidSerial = my code that receives Serial input and converts to char

for(int k=0;k<=3;k++){
ssidPlaceHolder[k]=ssidSerial[k];
}
const char* ssid = ssidPlaceHolder;
WiFi.begin(ssid, pass);
}
void loop () {}

Everything compiles fine, I debugged by using Serial.print and they are both displaying "SamF" and sizeof(ssid) for both is 4... so I am not sure why one works and the other doesn't? any ideas?

Thanks in advance for any help, and if anyone needs the code after I am done I will be more than glad to share it on git!

Basic string in C is an array of characters terminated by a 0. All functions taking char* or const char* use this 0 to determine the end of the string, because there is no other information about the length of that string.

In your question you copy characters from one characters buffer to other, but you do not set the terminating 0, so the function begin takes the data after the pass pointer until some random memory location with 0.


First time set up- permission denied to usb port- ubuntu 14.04 I just plugged my arduino in and the light is on, but the blink test failed to upload. here is my error:

Arduino: 1.6.7 (Linux), Board: "Arduino/Genuino Uno"

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

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

From the documentation:

  Open Terminal and type:

ls -l /dev/ttyACM*

  you will get something like:

crw-rw---- 1 root dialout 188, 0 5 apr 23.01 ttyACM0

  The "0" at the end of ACM might be a different number, or multiple entries might be returned. The data we need is "dialout" (is the group owner of the file).

  Now we just need to add our user to the group:

sudo usermod -a -G dialout $USER

  then:

sudo chmod a+rw /dev/ttyACM0

  You will need to log out and log in again for this change to take effect.

Note that the preceding is old Ubuntu instructions. On modern distros that use ConsoleKit create the file /etc/udev/rules.d/01-ttyusb.rules containing the following and then reload the udev rules and replug the Arduino device:

SUBSYSTEMS=="usb-serial", TAG+="uaccess"


ATTiny watchdog and interrupt I'm trying to control an Arduino Barebone from an arduino with relays.
Basically when the attiny starts it should switch on the arduino for 4 seconds.
The Arduino sends a signal back to a digital pin of the attiny and as long as it is set to high the attiny should leave it working.
If it is low the attiny should switch the relay of.

the problem is some changes to the code make the interrupt reset the attiny (which would switch of the arduino) othertimes- in this case.
the interrupt doesn't work at all.

#include <avr/sleep.h>
#include <avr/wdt.h>
#include <avr/io.h>
#include <avr/interrupt.h>

#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif

int pinBoard = 0;
bool boardOn = false;
bool startBoard_flag = false;
int pinBoardReturn = 3;

volatile boolean f_wdt = 1;

void setup() {
  cli();//disable interrupts during setup
  pinMode(pinBoard, OUTPUT);
  pinMode(pinBoardReturn, INPUT);
  setup_watchdog(9);
  cbi(ADCSRA, ADEN);                   // switch Analog to Digitalconverter OFF
  // cli();//disable interrupts during setup
  for (int i = 0; i < 10; i++) {
    digitalWrite(pinBoard, HIGH);
    delay(100);
    digitalWrite(pinBoard, LOW);
    delay(100);
  }

  PCMSK |= (1 << PCINT1); //sbi(PCMSK,INTERRUPTPIN) also works but I think this is more clear // tell pin change mask to listen to pin2 /pb3 //SBI
  GIMSK |= (1 << PCIE);   // enable PCINT interrupt in the general interrupt mask //SBI

  startBoard();

  DDRB &= ~(1 << DDB1); //cbi(DDRB, DATADIRECTIONPIN);//  set up as input  - pin2 clear bit  - set to zero
  PORTB |= (1 << PB1); //cbi(PORTB, PORTPIN);// disable pull-up. hook up pulldown resistor. - set to zero
}

void startBoard() {
  digitalWrite(pinBoard, HIGH);
  boardOn = true;
  startBoard_flag = false;
  cli();                                  // Disable interrupts
  delay(4000);
}

void shutdownBoard() {
  digitalWrite(pinBoard, LOW);
  boardOn = false;
}

void loop() {
  if (f_wdt == 1) { // wait for timed out watchdog / flag is set when a watchdog timeout occurs
    f_wdt = 0;     // reset flag
    if (startBoard_flag) {
      startBoard();
    }
    bool boardReturn = digitalRead(pinBoardReturn);
    if (boardOn && !boardReturn) {
      shutdownBoard();
    }
    system_sleep();
  }
}

//****************************************************************
// set system into the sleep state
// system wakes up when wtchdog is timed out
void system_sleep() {

  // GIMSK |= _BV(PCIE);                     // Enable Pin Change Interrupts
  // PCMSK |= _BV(PCINT3);                   // Use PB3 as interrupt pin

  set_sleep_mode(SLEEP_MODE_PWR_DOWN);    // replaces above statement
  sleep_enable();                         // Sets the Sleep Enable bit in the MCUCR Register (SE BIT)
  sleep_cpu();                            // sleep

  // PCMSK &= ~_BV(PCINT3);                  // Turn off PB3 as interrupt pin
  sleep_disable();                        // Clear SE bit

  // sei();                                  // Enable interrupts
}

//****************************************************************
// 0=16ms, 1=32ms,2=64ms,3=128ms,4=250ms,5=500ms
// 6=1 sec,7=2 sec, 8=4 sec, 9= 8sec
void setup_watchdog(int ii) {

  byte bb;
  int ww;
  if (ii > 9 ) ii = 9;
  bb = ii & 7;
  if (ii > 7) bb |= (1 << 5);
  bb |= (1 << WDCE);
  ww = bb;

  MCUSR &= ~(1 << WDRF);
  // start timed sequence
  WDTCR  |= (1 << WDCE) | (1 << WDE);
  // set new watchdog timeout value
  WDTCR  = bb;
  WDTCR  |= _BV(WDIE);
}
//****************************************************************
// Watchdog Interrupt Service / is executed when  watchdog timed out
ISR(WDT_vect) {
  f_wdt = 1; // set global flag
}

ISR(PCINT_VECTOR) {
  for (int i = 0; i < 4; i++) {
    digitalWrite(pinBoard, HIGH);
    delay(1000);
    digitalWrite(pinBoard, LOW);
    delay(1000);
  }
  startBoard_flag = true;
  f_wdt = 1; // set global flag
}

Disassembling the delay code indicates it uses micros which needs interrupts on to work.

void delay(unsigned long ms)
{
 27a:   cf 92           push    r12
 27c:   df 92           push    r13
 27e:   ef 92           push    r14
 280:   ff 92           push    r15
 282:   cf 93           push    r28
 284:   df 93           push    r29
 286:   6b 01           movw    r12, r22
 288:   7c 01           movw    r14, r24
    uint16_t start = (uint16_t)micros();
 28a:   d3 df           rcall   .-90        ; 0x232 <micros>
 28c:   eb 01           movw    r28, r22

    while (ms > 0) {
 28e:   c1 14           cp  r12, r1
 290:   d1 04           cpc r13, r1
 292:   e1 04           cpc r14, r1
 294:   f1 04           cpc r15, r1
 296:   79 f0           breq    .+30        ; 0x2b6 <delay+0x3c>
        yield();
 298:   ea d0           rcall   .+468       ; 0x46e <yield>
        if (((uint16_t)micros() - start) >= 1000) {
 29a:   cb df           rcall   .-106       ; 0x232 <micros>
 29c:   6c 1b           sub r22, r28
 29e:   7d 0b           sbc r23, r29
 2a0:   68 3e           cpi r22, 0xE8   ; 232
 2a2:   73 40           sbci    r23, 0x03   ; 3
 2a4:   a0 f3           brcs    .-24        ; 0x28e <delay+0x14>
            ms--;
 2a6:   81 e0           ldi r24, 0x01   ; 1
 2a8:   c8 1a           sub r12, r24
 2aa:   d1 08           sbc r13, r1
 2ac:   e1 08           sbc r14, r1
 2ae:   f1 08           sbc r15, r1
            start += 1000;
 2b0:   c8 51           subi    r28, 0x18   ; 24
 2b2:   dc 4f           sbci    r29, 0xFC   ; 252
 2b4:   ec cf           rjmp    .-40        ; 0x28e <delay+0x14>
        }
    }
}
 2b6:   df 91           pop r29
 2b8:   cf 91           pop r28
 2ba:   ff 90           pop r15
 2bc:   ef 90           pop r14
 2be:   df 90           pop r13
 2c0:   cf 90           pop r12
 2c2:   08 95           ret

That appears to confirm that the code in wiring.c is indeed what is being used on the ATtiny85 core:

void delay(unsigned long ms)
{
    uint16_t start = (uint16_t)micros();

    while (ms > 0) {
        yield();
        if (((uint16_t)micros() - start) >= 1000) {
            ms--;
            start += 1000;
        }
    }
}

Turning interrupts off and then doing a delay is a Bad IdeaTM.

  So i would rather have a counter for the watchdog in order to wait for the specified time?

Using the watchdog timer is certainly one way of waiting for 4 seconds.


How can i change by esp8266 baudrate, as I accidentally changed the baudrate to something else(which I dont remember)? //In order to connect,

SoftwareSerial esp8266(2,3);

// the TX pin of esp8266 is connected to pin 3 of
// arduino uno and RX pin is connected to 2
// we need to pass baud rate to begin function

void setup()
{
  Serial.begin(115200);
  esp8266.begin(???); // what should i do in order to make it work?
}

What should i do in order to make it work?

I encountered a similar situation where I accidentally set the baudrate to 8000 with the AT commands.
Thankfully I remembered the baud rate I set, so I used PuttY to create a serial communication with the port with the weird 8000 baud rate and changed the baud rate back to 9600.
The method can be found here: http://flower-platform.com/2015/12/16/esp8266-with-at-commands-connect-from-pc-with-putty/
The AT command I used to change the baud rate:
AT+UART_DEF=9600,8,1,0,0


not able to figure out what is wrong with my nodemcu code #include <ESP8266WiFi.h>
#include <FirebaseArduino.h>

//Firebase settings
#define FIREBASE_HOST "..........firebaseio.com/"     //cant share
#define FIREBASE_AUTH "..............."               //cant share

//Wi-Fi settings
#define WIFI_SSID "kello"
#define WIFI_PASSWORD "8888"

//Define trigger and echo digital pins
const int trigPin = 4;
const int echoPin = 3;

// The amount of time the ultrassonic wave will be travelling for
long duration = 0;
// Define the distance variable
double distance = 0;

void setup()
{
     Serial.begin(9600);
    // Connect to Wi-Fi
    Serial.print("Wi-Fi...");
    WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
    Serial.print("Connecting...");
    while (WiFi.status() != WL_CONNECTED)
    {
        Serial.print(".");
        delay(500);
    }
    Serial.println();
    Serial.print("Connected to: ");
    Serial.println(WiFi.localIP());

    Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);

    // Ultrasonic sensor, set echo as Input and trigger as Output
    pinMode(trigPin, OUTPUT);
    pinMode(echoPin, INPUT);

}

void loop()
{

    getDistance();
    // Prints the distance value to the serial monitor
    Serial.print("Distance: ");
    Serial.println(distance);

    delay(500);
}

void getDistance()
{
    // Clear trigPin
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);

    // trigPin HIGH por 10ms
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);

    //Reads echoPin, returns the travel time of the sound wave in ms
    duration = pulseIn(echoPin, HIGH);

    // Calculating the distance, in centimeters, using the formula described in the first section.
    distance = duration * 0.034 / 2;

    // Sends the distance value to Firebase
    Firebase.setFloat("distance", distance);

}

I am a computer graduate so i do not have much knowledge about nodemcu. I saw some documentations about nodemcu. I want to show the data obtained by the ultrasonic distance sensor in the realtime database of firebase. But i am not able to figure out why i am not able to get output of serial.println(distance) in the com5 window even though the code compiles successfully .
This is what i get when running the program

Executable segment sizes:

IROM   : 330560          - code in flash         (default or ICACHE_FLASH_ATTR)

IRAM   : 27760   / 32768 - code in IRAM          (ICACHE_RAM_ATTR, ISRs...)

DATA   : 1408  )         - initialized variables (global, static) in RAM/HEAP

RODATA : 2044  ) / 81920 - constants             (global, static) in RAM/HEAP

BSS    : 25160 )         - zeroed variables      (global, static) in RAM/HEAP

Sketch uses 361772 bytes (34%) of program storage space. Maximum is 1044464 bytes.
Global variables use 28612 bytes (34%) of dynamic memory, leaving 53308 bytes for local variables. Maximum is 81920 bytes.
esptool.py v2.8
Serial port COM5
Connecting....
Chip is ESP8266EX
Features: WiFi
Crystal is 26MHz
MAC: ec:fa:bc:c1:44:d2
Uploading stub...
Running stub...
Stub running...
Configuring flash size...
Auto-detected Flash size: 4MB
Compressed 365920 bytes to 264395...

Writing at 0x00000000... (5 %)
Writing at 0x00004000... (11 %)
Writing at 0x00008000... (17 %)
Writing at 0x0000c000... (23 %)
Writing at 0x00010000... (29 %)
Writing at 0x00014000... (35 %)
Writing at 0x00018000... (41 %)
Writing at 0x0001c000... (47 %)
Writing at 0x00020000... (52 %)
Writing at 0x00024000... (58 %)
Writing at 0x00028000... (64 %)
Writing at 0x0002c000... (70 %)
Writing at 0x00030000... (76 %)
Writing at 0x00034000... (82 %)
Writing at 0x00038000... (88 %)
Writing at 0x0003c000... (94 %)
Writing at 0x00040000... (100 %)
Wrote 365920 bytes (264395 compressed) at 0x00000000 in 23.4 seconds (effective 125.3 kbit/s)...
Hash of data verified.

Leaving...
Hard resetting via RTS pin...

Is the ultrasonic sensor not getting enough power supply as nodemcu is connected to my laptop?
Please help me out and let me know if more information is required.

Your echoPin Is defined as 3. GPIO3 of the NodeMCU is also the “RX” pin needed for serial communication to the host. This might explain why you don’t see any output. You should change it to a different pin (for example pin 5 / D1 is a safe choice).

Each pin on the NodeMCU has a “GPIO” number (which is just the pin number as defined by the ESP8266 architecture) and a corresponding “Dx” designation (which is usually marked on the NodeMCU board).

Which GPIO pin corresponds to which which “D” pin is shown in pinout diagrams, like the one here. Scroll to the NodeMCU 12-E pinout.

Some of the safest pins to use are:

Pin 5 (D1)
Pin 4 (D2)
Pin 12 (D6)
Pin 13 (D7)
Pin 14 (D5)

Some of the other pins could also be used, but have some restrictions, as you can see on the page I linked to.

Note that pins 12-14 are used for SPI and pins 4 and 5 are (normally) used for (software) I2C. If you want to control hardware that uses these protocols, these are the default pins it uses.


Cheap arduino wi-fi TRIGGER I am looking for cheap way to have very basic wireless communication between an Arduino and a iphone.
I don't need to send complex data, it would be sufficient to "trigger" the arduino: let's say it is reading a certain pin voltage and waiting for it to be up in order to do stuff, my goal is to trigger this pin up by any (wireless and iphone friendly) mean.

I have figured out two solutions: wi-fi shield, cheap RF transceiver. The problem with the latter is that it is not trivial to communicate with a RF transceiver from an iphone. I should add another arduino controlling an RF transceiver on the iphone side and commanding this arduino with an usb.

The wi-fi shield on the other hand is too expensive. Even small routers such as the wr703n (30 euro more or less) is too expensive in my opinion. I just want to send a "bit" of information, so I don't want to spend more than 10 euro.

The third option would be to hack some cheap wi-fi controlled tool, such a lamp or plug: do you know any?
Do you have any other idea?

Thanks!

WiFi you either need a WiFi router or for either the iPhone or Arduino to create a network.

RF transceiver you need external circuitry.

The common way to do this at the moment is using Bluetooth Low Energy. Using a Bluetooth Low Energy (BLE) shield you can directly connect the Arduino to a modern iPhone or Android phone (supporting Bluetooth 4.0).

Check out redbearlabs, who have a range of shields and BLE-enabled Arduino clones. There are example sketches and iOS apps on the net. I have made a BLE controlled RGB light using the redbearlabs BlendMicro and example OSX application.


MPU6050/DMP Intermittent bad data output? I have a DFRobots MPU6050 module wired to SCL/SDA/Pin 2 on a Mega 2560 board, using Jeff Rowberg's I2CDev/MPU6050_6Axis_MotionApps libraries.  I have 2.2K pullups on the MPU6050 module, tied to +5V, as shown in the following photo.

I used a modified version of the code from Jeff's example to retrieve heading values from the MPU6050, as shown below

bool GetIMUHeadingDeg() //08/28/18 chg to bool return

{

//Purpose:  Encapsulate everything needed to acquire a yaw value
//Inputs:
//  global_yawval = float variable defined at global scope
//  fifocount = uint8_t variable defined at global scope
//  packetsize = uint8_t variable defined at global scope
//  mpuIntStatus = uint8_t variable defined at global scope
//  whilecount = long variable defined at global scope
//  resetcount = int variable defined at global scope
//Outputs:
//  global_yawval filled with latest yaw value from sensor
//  true = success, false = failure
//Notes:
//  08/13/18 now returns global_yawval to calling routine
//  08/28/18 chg return to bool so can return success/failure

// if programming failed, don't try to do anything
//if (!dmpReady) return;
//if (!dmpReady) false;

bool result = false; //added 01/16/19 to supress warnings

// wait for MPU interrupt or extra packet(s) available
while (!mpuInterrupt && fifoCount < DMPpacketSize)
{
    whilecount++;
    delay(10);
    delay(10);

    if (mpuInterrupt)
    {
        fifoCount = mpu.getFIFOCount();
        mySerial.printf("%ld\t%d\n", whilecount, fifoCount);
        whilecount = 0;
        break;
    }
}

// reset interrupt flag and get INT_STATUS byte
mpuIntStatus = mpu.getIntStatus();
mpuInterrupt = false;

// get current FIFO count
fifoCount = mpu.getFIFOCount();

// check for overflow (this should never happen unless our code is too inefficient)
if ((mpuIntStatus & 0x10) || fifoCount == 1024)//0x10 is mask for MPU6050_INTERRUPT_FIFO_OFLOW_BIT
{
    // reset so we can continue cleanly
    mpu.resetFIFO();
    Serial.println(F("FIFO overflow!"));
    result = false; //added 01/16/19 to supress warnings

    // otherwise, check for DMP data ready interrupt (this should happen frequently)
}
else if (mpuIntStatus & 0x02)//0x02 is mask for MPU6050_INTERRUPT_DMP_INT_BIT
{
    // wait for correct available data length, should be a VERY short wait
    while (fifoCount < DMPpacketSize)
    {
        fifoCount = mpu.getFIFOCount();
        //mySerial.printf("fifo count = %d\n", fifoCount);
    }

    //07/08/18 added to watch for non-modulo FIFO counts
    if (fifoCount == 0 || fifoCount % DMPpacketSize != 0)
    {
        mpu.resetFIFO();
        FIFO_resetcount++;
    }
    else
    {
        //07/07/18 modified to read all outstanding packets
        // read a packet from FIFO
        while (fifoCount >= DMPpacketSize)
        {
            //mySerial.printf("fifo count = %d\n", fifoCount);
            mpu.getFIFOBytes(fifoBuffer, DMPpacketSize);
            fifoCount -= DMPpacketSize;
        }

        // display Euler angles in degrees
        mpu.dmpGetQuaternion(&q, fifoBuffer);
        mpu.dmpGetGravity(&gravity, &q);
        mpu.dmpGetYawPitchRoll(ypr, &q, &gravity);

        global_yawval = ypr[0] * 180 / M_PI;
        result = true; //added 01/16/19 to supress warnings
    }

    ////DEBUG!!
    //      mySerial.printf("yawdeg = %4.2f\n", global_yawval);
    //      mySerial.printf("time = %ld\tyawdeg = %6.2f\n", millis(), global_yawval);
    ////DEBUG!!
}

return result; //added 01/16/19 to surpress warnings

}

I have noticed occasional bad data points in the computed Heading values retrieved from the MPU6050, as shown in the attached plot. Any ideas what I can do about this?  Is bad value detection/removal an expected issue when dealing with IMU products like the MPU6050?

As an experiment, I excluded all points for which the rotation rate was unrealistically high, resulting in the 'Adj Hdg' line (gray line) in the plot below.  This (mostly) works, except for one instance where there were two bad values in a row.

TIA,

Frank

Looks like the major driver in the data 'noise' was the FIFO data rate, set via the MPU6050_DMP_FIFO_RATE_DIVISOR constant in MPU6050_6Axis_MotionApps20.h.  I changed the rate from 100Hz (0x01) to 20Hz (0x09) and got the following almost completely noiseless plot under the same conditions as before.  Note the vertical scale - only 6 deg total, and the one 'excursion' is only a 4 deg change. I also plotted the 3-point running average, which further reduces the excursion to less than 2 deg.

So, if you are looking for clean yaw (Heading) data from the MPU6050 DMP, consider changing the FIFO rate.

Frank


Traffic lights: gpios against 5V or ground I have 3 standard LEDs (red, yellow and green) connected in parallel to GPIO pins 10, 11 and 12. I also have one resistor, to which they are all three connected.

What's the difference between connecting the resistor to ground (so that the leds are high active) or to the 5V output pin of the arduino (so that the leds are low active)?

Moreover: how many ohms should the resistor have?
My understanding is: each of the 3 standard LEDs needs 20mA, so, if all three are lit, there is 60mA on the circuit. The 3 parallel LEDs need 2 V.
So, the resistor should be chosen such that it has a voltage drop of 3V at 60mA, hence 3V/60mA = 50 Ohm. If only one is lit, I need 3V/20mA = 150 Ohm.

But, if its possible that every possible subset of the LEDs is lit at once, wouldn't it be better, to place a resistor in front of every LED, so that I have 3 LED-resistor pairs in parallel? The value of each resistor is 50 Ohm then, allowing for a voltage drop of 3V in each of the 3 branches, so that each LED only gets the needed 2V?

Well, a lot of thoughts for 3 simple lights...
Thanks for any help.

I have 3 standard LEDs (red, yellow and green) connected in parallel to GPIO pins 10, 11 and 12. I also have one resistor, to which they are all three connected.

BAD BAD BAD!!!

What's the difference between connecting the resistor to ground (so that the leds are high active) or to the 5V output pin of the arduino (so that the leds are low active)?

Nothing, other than the reversed logic. AVR GPIOs (and most GPIOs in modern MCUs) are balanced - i.e., they have the same current limit for both sink and source.

Moreover: how many ohms should the resistor have? My understanding is: each of the 3 standard LEDs needs 20mA, so, if all three are lit, there is 60mA on the circuit. The 3 parallel LEDs need 2 V. So, the resistor should be chosen such that it has a voltage drop of 3V at 60mA, hence 3V/60mA = 50 Ohm. If only one is lit, I need 3V/20mA = 150 Ohm.
But, if its possible that every possible subset of the LEDs is lit at once, wouldn't it be better, to place a resistor in front of every LED, so that I have 3 LED-resistor pairs in parallel? The value of each resistor is 50 Ohm then, allowing for a voltage drop of 3V in each of the 3 branches, so that each LED only gets the needed 2V?

Yes. That is how you should wire LEDs - and you have already identified why.
For each LED calculate the resistance as R=(5-Vf)/0.02. You need to find the correct Vf for each LED from the datasheet to get the best results - but if you can't then a rule of thumb is: Red, Green and Yellow are about 2V, Blue and White are about 3V.


arduino boolean function In the following code :-
The aim of code is " when push button is pressed , led is on and when push button is is pressed again led is of"

#define led 12
#define button 7
boolean trigger = false;
boolean previous = false;
void setup()
{
  pinMode(led , OUTPUT);
  pinMode(button , INPUT);
}
void loop()
{
  int current = digitalRead(button) ;
  if (current && !previous)
  {
    trigger = !trigger;
  }
  previous = current;
  digitalWrite(led , trigger);
}

My Questions are as follows:-

When i used digitalread(button) instead of introducing variable i.e
current. LED shows abnormal behavior. Why ?
What is the purpose of current = previous expression. Whats its
significance?
Also please explain the working of a code in a brief manner in a
loop.
Why I should use Boolean instead of int?

When i used digitalread(button) instead of introducing variable i.e
  current. LED shows abnormal behavior. Why ?

Likely this is because of switch bounce.  The processor is very fast compared to the bounces a mechanical switch makes when operated.  So the results can be unexpected.  You can get around this problem in software by using a state machine.  Or in hardware by using capacitors to filter out bouncing.

  What is the purpose of current = previous expression. Whats its
  significance?

The program is tracking the state of the switch.  So you need to know the previous state of the switch to know if the state of the switch has changed.

  Also please explain the working of a code in a brief manner in a loop.

The two fixed or reserved function names in an Arduino sketch are "setup" and "loop".  "setup" is called only once on boot up.  And "loop" is called over and over again after "setup"is called.  In "loop" the code reads that state of the button, then tests to see if the state of the button is true and the previous state is false.  If it is, then toggle the variable which tracks the state of the LED.  Then the code will always save the current state as the past state and turns on / off the LED according to the value tracking the state of the LED.

Now comes the tricky part.  Assume the switch is perfect and does not bounce.  The toggling only occurs when the switch is 1st pressed.  That is because the next time through "loop" both trigger & previous are true and the test will then be false and the LED will not be toggled.  Not until after the switch is released does the code reset previous to false.  Now if the switch is pressed again, for only 1 iteration through "loop", the test will be true and the LED will be toggled.

This approach depends on the switch not to bounce.  And is difficult to understand.  Consider using a 4 state machine (button up / LED off, button down / LED on, button up / LED on, button down/ LED off) rather than this 2 state machine (button down / LED toggle, button up / LED steady).

  Why I should use Boolean instead of int?

Bools only have two states.  Integers can have many states.  It is less confusing and less error prone to use a variable that only has two states if that is the intent of the program.


Why the GSM Shield is discontinued? What options are available? I need to build a device with a single button to make a call over a mobile network (GSM)

I wanted to buy an arduino one and an arduino gsm shield for this, but just noticed that the GSM Shield is retired - discontinued.

I checked all the arduino products but there is no options for integration with GSM.

What options do I've to build my products if the GSM Shields is discontinued?

A retired product is just a product that isn't supported anymore. It doesn't mean that this product is not usable anymore. Because the GSM shield is discontinued by Arduino.cc itself, you could buy Arduino.org (link to the GSM shield 2), or even an other model by Adafruit. Here is a link for many options of GSM shields on Adafruits' website.

A last option would be to buy it from a chinese seller on Amazon or Ebay. Though they are cheap, they are usualy very crappy and there are not many libraries for them.