#define macro not in scope when i try to use IR library My code keeps saying that that Button_8 and the rest of the #define macros are out of scope.

#include <IRLib.h>
#include <Servo.h>

#define MY_PROTOCOL SONY
#define RIGHT_ARROW   0xfd50af //Move several clockwise
#define LEFT_ARROW    0xfd10ef //Move servo counterclockwise
#define SELECT_BUTTON 0xfd906f //Center the servo
#define UP_ARROW      0xfda05f //Increased number of degrees servo
#define DOWN_ARROW    0xfdb04f //Decrease number of degrees servo moves
#define BUTTON_0 0xfd30cf  //Pushing buttons 0-9 moves to fixed  positions
#define BUTTON_1 0xfd08f7  // each 20 degrees greater
#define BUTTON_2 0xfd8877
#define BUTTON_3 0xfd48b7
#define BUTTON_4 0xfd28d7
#define BUTTON_5 0xfda857
#define BUTTON_6 0xfd6897
#define BUTTON_7 0xfd18e7
#define BUTTON_8 0xfd9867
#define BUTTON_9 0xfd58a7

IRrecv My_Receiver(11);//Receive on pin 11
IRdecode My_Decoder;
long Previous;
Servo myservo2;
Servo myservo;

void setup()
{
myservo.attach(8);
myservo2.attach(3);
My_Receiver.enableIRIn();
}

void loop()
{

  if (My_Receiver.GetResults(&My_Decoder))
{
   My_Decoder.decode();
   if(My_Decoder.decode_type==MY_PROTOCOL)
   {
       if(My_Decoder.value==0xFFFFFFFF)
       My_Decoder.value= Previous;
       if(My_Decoder.value == Button_9)
       {
       myservo.write(0);
       myservo2.write(180);
       }
     else if(My_Decoder.value == Button_8)
      {
         myservo.write(180);
          myservo2.write(180);
       }

    }
}
}

when i use a switch statement instead of the 4 and 5 if statement like so:

switch(My_Decoder.value) {
        case Button_8:   //do something; break;

it works, but i dont know why.

C++ is case-sensitive. Button_8 is different from BUTTON_8.


Analog pins all reading same value I'm trying to read 5 analog inputs, but all the pins are reading the same as pin A0, plus or minus a couple points. I tried using pulldown resistors on all 5 pins and it made no difference. The board is a Leonardo. Thanks for any ideas/help!

void setup() {
    Serial.begin(115200);
    analogReference(EXTERNAL);
}

void loop() {
    int A0, A1,A2,A3,A4;
    delay(200);
    A0= analogRead(A0);
    A1= analogRead(A1);
    A2= analogRead(A2);
    A3= analogRead(A3);
    A4= analogRead(A4);

    Serial.print(A0);
    Serial.print(" ");
    Serial.print(A1);
    Serial.print(" ");
    Serial.print(A2);
    Serial.print(" ");
    Serial.print(A3);
    Serial.print(" ");
    Serial.print(A4);
    Serial.print("\n");
}

int A0, A1,A2,A3,A4;
delay(200);
A0= analogRead(A0);
A1= analogRead(A1);
A2= analogRead(A2);
A3= analogRead(A3);
A4= analogRead(A4);

Your local variables (A0 through A4) are shadowing the global variables for the pins (A0 through A4). Give your local variables different names.


Connect optocoupler 4N35 to Arduino Uno to control LED light strips I want to use an Arduino Uno to control the LED light strips, based on the input signal from a robot controller. The robot controller sends a digital signal with "HIGH" of 24 V and "LOW" of 0 V.  I have thought of using an optocoupler between the robot controller and the Arduino to reduce the voltage from 24 V to 5 V, suitable for the Arduino pin.

Can I connect the optocoupler's emitter to the Arduino ground?

The LED strips work on 12V DC and at 2000mA. If I power the Arduino with 12V DC power source connected to the DC jack, can I give the power to the LED's also using the V-in pin of the Arduino?

Please look at my circuit and tell me where I went wrong and why?

Can i connect the optocoupler's emmitter to the arduino ground?

Yes. Don't forget to either enable the internal pullup on the GPIO pin or use an external pullup on the collector.

  If i power the arduino with 12 V D.C power source connected to the D.C jack, can i give the power to the LEDs also using the V-in pin of the arduino?

Not at the current rating you are talking about, no. The header is only rated for 1A, and the diode on the barrel jack input is also rated for only 1A.  You would need to split the LED power off from the incoming power before it goes into the Arduino.

The way you have your MOSFETs wired at the moment is wrong. The moment you turn one on it will let the Magic Smoke escape. You are using them to short circuit the LEDs, which is very very bad.

Each one should be wired in series with the LED between the cathode and ground:

simulate this circuit – Schematic created using CircuitLab


arduino weather shield with gps I have Arduino Mega and Weather shield and GPS Receiver - GP-635T (50 Channel).

here is my code for GPS

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

TinyGPSPlus gps;

static const int RXPin = 5, TXPin = 4;
SoftwareSerial ss(RXPin, TXPin);

const byte GPS_PWRCTL = 6;

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

  pinMode(GPS_PWRCTL, OUTPUT);
  digitalWrite(GPS_PWRCTL, HIGH);
}

void loop()
{
  smartdelay(800);
}

And print weather with this code

void printWeather()
{
  Serial.print("lat=");
  Serial.print(gps.location.lat(), 6);
  Serial.print("lat=");
  Serial.print(gps.location.lng(), 6);
  Serial.print("altitude=");
  Serial.print(gps.altitude.meters());
  Serial.print("sats=");
  Serial.print(gps.satellites.value());

  char sz[32];
  Serial.print("date=");
  sprintf(sz, "%02d/%02d/%02d", gps.date.month(), gps.date.day(),gps.date.year());
  Serial.print(sz);

  Serial.print("time=");
  sprintf(sz, "%02d:%02d:%02d", gps.time.hour(), gps.time.minute(), gps.time.second());
  Serial.print(sz);
}

But I see only zero for location and date and time. What should I do?

Until you have the correct baud rate and good satellite reception, many fields will be zero or empty.  I wrote a diagnostic program for NeoGPS that will try different baud rates and confirm that the GPS device is functioning.  The example program is in this directory:

examples/NMEAdiagnostic

Installation instructions are here.

If you're inside, you may not be able to receive anything.  Move next to a window or go outside.


Getting the voltage of an 18650 battery with an Arduino I'm using a Arduino Pro Mini (5v) to sense the voltage of an 18650 battery. The battery (that is being sensed)is also used to power the Pro Mini but the MCU is behind a boost-converter which outputs 5.05v. Would I be able sense the right voltage of the battery?

simulate this circuit – Schematic created using CircuitLab

The boost converter has an input voltage ranges to 0.9 to 5 volts and current of 600mA.

Yes, if Vin- and Vout- are joined together inside the boost converter or share a common ground on the boost converter circuit board such as this one:


Can Bus Shield Not Receiving Data I am trying to connect my Arduino Uno board with SeeedStudio Can Bus Shield to my 2006 325i BMW. After compiling and uploading the example program by SeeedStudio, the serial monitor returns "Can Bus Shield Init ok!"

// demo: CAN-BUS Shield, receive data with check mode
// send data coming to fast, such as less than 10ms, you can use this way
// loovee, 2014-6-13

#include <SPI.h>
#include "mcp_can.h"

// the cs pin of the version after v1.1 is default to D9
// v0.9b and v1.0 is default D10
const int SPI_CS_PIN = 9;

MCP_CAN CAN(SPI_CS_PIN); // Set CS pin

void setup() {
  Serial.begin(115200);
START_INIT:
  if(CAN_OK == CAN.begin(CAN_500KBPS)) {
  // init can bus : baudrate = 500k
    Serial.println("CAN BUS Shield init ok!");
  } else {
    Serial.println("CAN BUS Shield init fail");
    Serial.println("Init CAN BUS Shield again");
    delay(100);
    goto START_INIT;
  }
}

void loop(){
  unsigned char len = 0;
  unsigned char buf[8];
  if(CAN_MSGAVAIL == CAN.checkReceive()) {
    // check if data coming
    CAN.readMsgBuf(&len, buf);
    // read data,  len: data length, buf: data buf
    unsigned char canId = CAN.getCanId();
    Serial.println("-----------------------------");
    Serial.println("get data from ID: ");
    Serial.println(canId);
    for(int i = 0; i<len; i++) {
      // print the data
      Serial.print(buf[i]);
      Serial.print("\t");
    }
    Serial.println();
  }
}

So I get the initialize statement returned but I'm not receiving any data. It seems like the if(CAN_MSGAVAIL == CAN.checkReceive()) statement isn't executed. I found my vehicle's Can high and Can low wires and inserted them into my Can Bus Shield. So I'm not sure if it's a code problem or if the wires aren't transmitting the data to the shield. Any help would be great.

It may be a dumb question, but are you sure your car CAN bus is 500kbps?
Have a look at this:
pdfLink
Maybe try different speeds? 100kbps maybe?

Also, look at the schematics of your shield? Is the bus termination resistor soldered on the board?


Arduino, problem with interrupt and SSD1306 OLED I'm not that good at this. Calculates RPM through Peripheral Speed and Interrupt.
Everything works fine when I show this in the IDE with Serial.print without OLED. When I connect an SSD1306 OLED I2C, the interrupt stops working. No serial.print.
If I uncomment the display.display(), Same problem with display.setRotation(90): everything is fine and serial.print starts working, but of course not the OLED.
In the code I have a void addressing, visadisplay(). If I put this addressing in void loop () then everything works but then there is a risk of unsynchronization, wrong values. I have also removed visadisplay(); without change.
Help...
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 32 // OLED display height, in pixels

// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
#define SCREEN_ADDRESS 0x3C ///< See datasheet for Address; 0x3D for 128x64, 0x3C for 128x32
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

// Function for serial display.
// Connections for Nano.
// Hall sensor connection: (Signal out) --- (D2).
// Display connection: (SDA) --- (4A) / (SCL) --- (A5)

volatile unsigned long PulsTid = 0UL;
volatile unsigned long StartTid = 0;
volatile unsigned long SlutTid = 0;
volatile unsigned long CalcTid = 0;
volatile float omkrets = 7.5;
volatile float HastighetPerferi = 0;
volatile unsigned long Rpm = 0;
volatile float Vinkel = 0UL;

void isr() { // interrupt service routine
  Vinkel = 0;
  StartTid = millis();
  CalcTid = SlutTid;

  detachInterrupt(0);             //detaches the interrupt while calculating

  PulsTid = (StartTid - SlutTid);
  HastighetPerferi = (omkrets / PulsTid);
  SlutTid = StartTid;
  Rpm = ((HastighetPerferi / (omkrets / 1000) * 60) / 2); // Calculate speed

  visadisplay();
  attachInterrupt(0, isr, FALLING);  //attaching the interrupt again
}

void visadisplay(void) {
  Serial.print("Varvtal: ");
  Serial.println(Rpm);

  display.setRotation(90);
  display.clearDisplay();
  display.setTextSize(1);              // Text size.
  display.setTextColor(SSD1306_WHITE); // White text.
  display.setCursor(0, 0);             // Start position
  display.println("RPM: ");
  display.setCursor(40, 10);
  display.setTextSize(2);
  display.print(Rpm);
  display.display();
}

void setup() {
  Serial.begin(115200);
  attachInterrupt(0, isr, FALLING);  //attaching the interrupt

  //SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
  if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3C for 128x32
    Serial.println(F("SSD1306 allocation failed"));
    for(;;); // Don't proceed, loop forever
  }
}

void loop(){
}

Your problem is (most likely) that you are doing everything from an interrupt. That is not only bad practice, but on Arduinos it is generally impossible.
On small microcontrollers you typically only have one interrupt priority (occasionally two). That means that only one interrupt can run at a time, and if an interrupt is running then no other interrupt can interrupt it.
So anything that relies on interrupts to operate can never be used inside an interrupt service routine, or it will never function.
That includes things like delay() and, depending on the implementation, such things as Wire (I2C) and SPI.
Instead your ISR really should be as short as possible. It should at most do any short calculations and store results, and then indicate (through the use of a semaphore) to the main thread that it should do some work.
The simplest "fix" to your problem would be to move visadisplay() into loop() and in isr() simply set a bool flag when there is data to display. Your loop() then checks that flag and, if set, resets it and calls visadisplay().
Also, you don't need to detach and re-attach the interrupt all the time - if the ISR is running then interrupts can't happen anyway.
// ... snip ...
volatile bool doDisplay = false;

void isr()          //interrupt service routine
{
  Vinkel = 0;
  StartTid = millis();
  CalcTid = SlutTid;

  PulsTid = (StartTid - SlutTid);
  HastighetPerferi = (omkrets/PulsTid);
  SlutTid = StartTid;
  Rpm = ((HastighetPerferi/(omkrets/1000)* 60)/2);  //Calculate speed

  doDisplay = true; // Signal to the main thread there's data to display
}

// ... snip ...

void loop() {
    if (doDisplay) {       // If there is something to display
        doDisplay = false; // then clear the flag for next time
        visadisplay();     // and display the data.
    }
}


Is there any way that the two 'different' programs of arduino can be run one after another keeping each one separate? I have made a 8*8*8 led cube using arduino. I have found two different codes from different developers having different animations in them. i wanted to combine them and get to run all the animations at once. Both the codes have some similar function names and some are different as well. I wanted to know if i can keep both these separate from each other yet run them one after another. Almost all parameters are different including setup() of both codes. Please help

You can achieve this fairly simply by using namespaces. Inside a namespace, symbols are relative to that space. So you could put all of your first sketch into the namespace sketch1, and all of the second sketch into the namespace sketch2 (assuming it all fits, of course).

Now you can call the first sketch's setup and then loop, by qualifying it with the namespace name as illustrated below.

// FIRST SKETCH

namespace sketch1
{

  // FUNCTION PROTOTYPES

  void func1(int a, int b);
  void func2();

  void setup()
  {
    Serial.begin (115200);
    Serial.println ("Inside sketch1 setup");
    func1 (5, 6);
  }

  void loop()
  {
    Serial.println ("Inside sketch1 loop");
    delay (1000);
    func2 ();
  }

  void func1(int a, int b)
  {
    // some function
  }

  void func2()
  {
    // some other function
  }

} // end of namespace sketch1

// SECOND SKETCH

namespace sketch2
{

  // DECLARE FUNCTIONS BEFORE CALLING THEM

  void func3(int a, int b)
  {
    // some function
  }

  void func4()
  {
    // some other function
  }

  void setup()
  {
    Serial.begin (115200);
    Serial.println ("Inside sketch2 setup");
    func3 (7, 8);
  }

  void loop()
  {
    Serial.println ("Inside sketch2 loop");
    delay (1000);
    func4 ();
  }

} // end of namespace sketch2

// MAIN LOOP AND SETUP

void setup()
{
  pinMode (10, INPUT_PULLUP);
  if (digitalRead (10) == HIGH)
  {
    sketch1::setup ();
    while (true)
      sketch1::loop ();
  }
  else
  {
    sketch2::setup ();
    while (true)
      sketch2::loop ();
  }
}   // end of setup

void loop()
{

} // end of loop

In my example I am testing a pin (10) to see if sketch1 or sketch2 should run.

  yet run them one after another

Yes, well sketches normally keep running inside loop forever, so you would need a way of deciding when to exit the sketch and run the other one. My example shows how you can choose between one or the other based on a digital input.

  I tried it but it is showing that the functions are not declared in this scope.

Important note re function prototypes

It looks like the IDE's automatic generation of function prototypes doesn't work inside namespaces. Thus you need to do either:

Make your own function prototypes (that is the function declaration without the actual function code) - see sketch 1 above; or
Declare a function before it is used (sketch 2 above)

If this is someone else's code you may find it easier to just add the function prototypes as required. When you get the error message, find the function it is referring to, copy the "declaration" part, eg.

void foo (int a, int b)

Add a semicolon, eg.

void foo (int a, int b);

Then put that before it is called. Make sure it is still inside the namespace.

  can I call the setup if first namespace then some func. respective to that namespace then call the setup of second namespace and call func. from that namespace and keep all this in an infinite loop?

Well, you can do that, but you need to realize what each sketch is doing. For example if sketch1 turns some pins to output, but sketch2 assumes they are still inputs, then you need to undo that.

  And what is it to wrapup a function and 'how' to do it.

You need to inspect the sketches and see what they have done, so you can "undo" it. For example:

void wrapup ()
  {
  // set all pins to inputs and LOW
  for (int i = 0; i < 20; i++)
    {
    pinMode (i, INPUT);
    digitalWrite (i, LOW);
    }
  // if Serial used
  Serial.flush ();  // flush output
  Seral.end ();    // stop serial hardware

  // and so on

  }   // end of wrapup


EEPROM endurance and page size I would like to estimate the effective (minimum) endurance of the EEPROM of the Arduino in terms of single-byte writes.

The datasheet of the ATmega used on many Arduino boards says (page 20):

  The ATmega48A/PA/88A/PA/168A/PA/328/P contains 256/512/512/1Kbytes of data EEPROM memory. It is organized as a separate data space, in which single bytes can be read and written. The EEPROM has an endurance of at least 100,000 write/erase cycles.

Consider the ATmega328P with 1 kB of EEPROM. As I can write single bytes, if I loop through the EEPROM, writing every byte position the same number of times, that would make 1024 * 100,000 writes (assuming the nominal endurance).

But as far as I know not single bytes are erased before a write, but pages / cells. On page 285 / table 28.12 of the datasheet, the page size is specified to be 4 bytes. Does that mean the specified minimum endurance amounts to 1024 * 100,000 / 4 single-byte writes?

Testing a single byte write

I ran some test code overnight to try to get to the bottom of this. Somewhat surprisingly perhaps, I got up to over 11 million writes before a read-back failed:

Current count = 11514199
Writes per minute: 17550
....................
Current count = 11538199
Writes per minute: 17550
....................
Current count = 11562199
Writes per minute: 17549
...................
Failed readback!
Expected: FF
Got: 7F
Current count = 11585314
Halted.

So, 11.5 M writes. Still, as pointed out on the AVR Freaks thread, the guarantee of 100,000 writes to EEPROM gives you a data retention time of 20 years. Possibly if you exceed that limit, the data retention time will go down. It isn't particularly practical for me to test whether or not the EEPROM will still be valid after 20 years. ;)

Interestingly, the next day (as I write this) the EEPROM seems to have recovered and is now still writing and reading back OK. So it would appear that after 11 M writes you may sometimes get a bad read-back.

On the AVR Freaks thread they seemed to get somewhere between 5 M and 8 M writes before failure.

A number of hours later (2.4 hours), the same byte failed again, after a further 2,559,219 writes!

Current count = 14033314
Writes per minute: 17549
....................
Current count = 14057314
Writes per minute: 17549
....................
Current count = 14081314
Writes per minute: 17549
....................
Current count = 14105314
Writes per minute: 17549
....................
Current count = 14129314
Writes per minute: 17549
............
Failed readback!
Expected: FF
Got: 7F
Current count = 14144533
Halted.

Somewhat more quickly the third failure after a further 149,703 writes:

Current count = 14312533
Writes per minute: 17550
....
Failed readback!
Expected: FF
Got: 7F
Current count = 14318236
Halted.

And another failure (in 2.3 minutes) after a further 41757 writes:

Starting.
Current count = 14318236
Waiting for pin 2 to go LOW.
Started.
....................
Current count = 14342236
Writes per minute: 17551
..............
Failed readback!
Expected: FF
Got: 7F
Current count = 14359993
Halted.

Testing the adjacent byte

Now that I got a failure fairly quickly on the somewhat overworked byte, I adjusted the code to write to the next one up (1021) which would be in the same 4-byte "page".

Four hours later, the adjacent byte has been written to 4.36 million times without any errors, so this would appear to support the idea that each byte of EEPROM can be written individually without affecting its neighbours.

Next morning

The adjacent byte (address 1021) finally failed after 12,161,565 writes. So the proposition that each byte can be individually addressed, and has an individual lifetime, seems to be supported.

Current count = 12120000
Writes per minute: 17562
....................
Current count = 12144000
Writes per minute: 17562
..............
Failed readback!
Expected: FF
Got: 7F
Current count = 12161565
Halted.

Code

Main sketch

// EEPROM tester

// Author: Nick Gammon
// Date: 22 August 2015

// Connect a jumper from GND to pin D2 when ready to run.
// Remove the jumper for a clean wrap-up (saving the current count into EEPROM)

// Single flash, repeated every half second: ready to go
// Two flashes, stopped on request
// Three flashes, error
// Occasional flash: working

#include <EEPROMAnything.h>
#include <EEPROM.h>

const unsigned int WRITE_COUNT_ADDRESS = 1010;
const unsigned int TEST_ADDRESS = 1020;
const unsigned int ITERATIONS = 200;
const unsigned long MAX_DOTS = 20;
const byte TESTS [] = { 0x55, 0x00, 0xFF, 0x66, 0xAA, 0x11 };
const byte ACTIVATE_PIN = 2;
const byte LED = 13;

unsigned long dots = 0;
unsigned long writeCount;
unsigned long startTime;
unsigned long initialCount;

void showCount ()
  {
  Serial.print ("Current count = ");
  Serial.println (writeCount);
  } // end of showCount

// flash the LED the required number of times
void flashLED (const int times,
               const unsigned long interval = 100,
               const unsigned long delayTime = 500)
  {
  for (int i = 0; i < times; i++)
    {
    digitalWrite (LED, HIGH);
    delay (interval);
    digitalWrite (LED, LOW);
    delay (interval);
    }  // end of for each iteration
  delay (delayTime);  // delay between iterations
  }  // end of flashLED

// check our memory agrees with what we expect
void checkMemory (const byte target)
  {
  byte found = EEPROM.read (TEST_ADDRESS);
  if (found != target)
    {
    Serial.println ();
    Serial.println ("Failed readback!");
    Serial.print ("Expected: ");
    Serial.println ((int) target, HEX);
    Serial.print ("Got: ");
    Serial.println ((int) found, HEX);
    showCount ();
    EEPROM_writeAnything (WRITE_COUNT_ADDRESS, writeCount);
    Serial.print ("Halted.");
    Serial.flush ();
    while (true)
      flashLED (3);  // three flashes
    }
  }   // end of checkMemory

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();

  // get write count from previous run
  EEPROM_readAnything (WRITE_COUNT_ADDRESS, writeCount);
  initialCount = writeCount;

  // if all 1 bits, variable was never initialized
  if (writeCount == 0xFFFFFFFF)
    writeCount = 0;

  // tell them we are starting
  Serial.println ("Starting.");
  pinMode (2, INPUT_PULLUP);
  pinMode (LED, OUTPUT);
  showCount ();

  // wait for them to unplug pin 2
  Serial.println ("Waiting for pin 2 to go LOW.");
  while (digitalRead (ACTIVATE_PIN) == HIGH)
    flashLED (1);  // one flash

  Serial.println ("Started.");
  startTime = millis ();
  }  // end of setup

void loop ()
  {

  // write to EEPROM, checking each write
  for (unsigned int i = 0; i < ITERATIONS; i++)
    {
    for (unsigned int j = 0; j < sizeof (TESTS); j++)
      {
      EEPROM.write (TEST_ADDRESS, TESTS [j]);
      writeCount++;
      checkMemory (TESTS [j]);
      }  // end of doing each test pattern
    }  // end of loop of x ITERATIONS

  // save the current write count so we can pick up the count next time
  EEPROM_writeAnything (WRITE_COUNT_ADDRESS, writeCount);
  Serial.print (".");
  dots++;

  // confirming we are working
  flashLED (1, 10, 0);  // flash once, for 10 ms, no extra delay

  // newline, show counter
  if (dots >= MAX_DOTS)
    {
    Serial.println ();
    dots = 0;
    showCount ();
    unsigned long writes = writeCount - initialCount;
    unsigned long timeTaken = millis () - startTime;
    float writesPerMinute = float (writes) / float (timeTaken) * 60.0 * 1000.0;
    Serial.print ("Writes per minute: ");
    Serial.println ((int) writesPerMinute);
    }  // end of needing a newline and counter output

  // check if user wants us to stop by disconnecting the jumper from Gnd to D2
  if (digitalRead (ACTIVATE_PIN) == HIGH)
    {
    Serial.println ();
    Serial.println ("Stop request detected.");
    showCount ();
    Serial.print ("Halted.");
    Serial.flush ();
    while (true)
      flashLED (2);  // two flashes
    }
  }  // end of loop

EEPROMAnything.h

#include <Arduino.h>  // for type definitions
#include <EEPROM.h>

template <typename T> unsigned int EEPROM_writeAnything (int ee, const T& value)
{
    const byte* p = (const byte*)&value;
    unsigned int i;
    for (i = 0; i < sizeof(value); i++)
        EEPROM.write(ee++, *p++);
    return i;
}

template <typename T> unsigned int EEPROM_readAnything (int ee, T& value)
{
    byte* p = (byte*)&value;
    unsigned int i;
    for (i = 0; i < sizeof(value); i++)
        *p++ = EEPROM.read(ee++);
    return i;
}

The code is designed to wait until you connect pin 2 (digital pin 2) to ground before starting. This is to stop it executing immediately after being uploaded, before you start the serial monitor. So, upload the code, open the serial monitor, and then connect Gnd to pin D2, and watch the results.

Error correction

If the concern is that the EEPROM reads may deteriorate, once could use Reed Solomon error correction to recover. That is the method used for correcting bad reads on compact disks, and also QR codes. It can recover from a number of errors (you choose the level of error correction you want - the more error correction, the more memory it takes).

My tests so far have shown that failure involves single bits (as did the AVR Freaks tests) so this may well be a way of extending EEPROM life and reliability.

Testing of some Reed Solomon code that I found, would appear to indicate that adding the encoding and decoding would take around 4800 bytes of program memory, plus around 600 bytes of RAM (512 bytes needed for the internal tables, plus some extra work space). In addition you need 256 bytes of RAM for the code block. Those figures could be reduced by using less bits per "symbol". For example, if you stored 4-bit symbols (such as BCD numbers) then the memory requirements would reduce somewhat.


Switch between ntc resistor sensors time based for other device We have a heating system that uses an ntc resistor to measure water temperature. I would like to replace that ntc resistor by a fixed one (low enough to disable heating) temporary on a 5 minute schedule, or any other.

It's to prevent the warm water using up all the heat and not leaving any for the central heating of the building. We got fooled by the contractor and a proper upgrade would now cost several thousands, so we just want to trick the system. ;p

The arduino is not supposed to measure anything, just to connect one of the two resistors to the heating system.

Is an arduino the right choice for that? If yes, which model? What extra elements would I need? Transistors? Relays? They shouldn't have too much own resistance to not influence the measuring of the heating system when the NTC is connected.

Just a simple connection of the extra resistor would work too because the resulting resistance would be lower and still indicate "water is hot enough" to the heating system.

Any help is welcome, even if it is not arduino based.

It sounds like what you want is a small SPDT relay (maybe a reed relay).

simulate this circuit – Schematic created using CircuitLab

Turn on the GPIO, the MOSFET (or NPN BJT if you choose - increase R1 if you do) turns on, which energises the relay. The relay then switches between the NTC and the resistor being connected into the circuit.


Use ESP8266 GPIOs after Flash Startup I'm a bit confused about the ESP8266 launching and GPIO behaviour.

When I'm programming the ESP8266 I have to set GPIO2 high and GPIO0 low.
But when I want to use the ESP8266 in my project I have to set GPIO2 and GPIO0 to HIGH, but if they are both high I can't use them as inputs or outputs. So my question is how can I use atleast of the GPIO as an output and starting the ESP8266 without reprogramming it.

ESP8266 was developed for 'Serial over WiFi' as system-on-chip based on the Tensilica processor. The GPIO pins of Tensilica where used for different purposes of the system, like antena, flash memory connection, boot setup etc.

The more general use of the ep8266 as micro-controller with WiFi has evolved, but needs to accept the legacy of the original concept. Smart people even found a way how to share SPI with the flash memory of the system.

If you want to use the IO pins of the esp8266 (they are not called GPIO in datasheet), you must accept the required boot state and use only circuit,
sensor or actuator that doesn't disturb it and can handle it.

io0 LOW tels the esp8266 to boot into bootloader flashing mode. It is evaluated by ROM software in the boot process. Pull-up circuit is required to achieve normal boot. So if you want to attach something to this pin, it must accept this conditions. For button it is ideal.

If you want to use io 0 or io 2 as output, use logic that is normally HIGH and make sure it is not connected direct or indirect to ground at startup.


How to write http response from HttpClient to Serial monitor with a ESP32 (Wemos Lolin32)? With my ESP32 Board, Wemos Lolin32, I would like to make a http GET request to "http://www.arduino.cc/asciilogo.txt", read the text file and print the text file to the serial monitor.

The question is: Why isn't basically the txt file written to the serial monitor? How can it be achieved? Do I need some kind of conversion of the char?

I am using similar code to that from this example https://www.arduino.cc/en/Tutorial/HttpClient.
Basically the code can be reduced to this minimal example:

#include <WiFi.h>
#include <HttpClient.h>

void setup() {

  Serial.begin(9600);

  WiFi.begin(ssid, password);
  Serial.println("Connecting to WiFi..");
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println(".");
  }
  Serial.println("Connected to the WiFi network");

  pinMode(LED_BUILTIN, OUTPUT);
  Serial.println("SETUP FINISHED");
}

void loop() {
  Serial.println("Connecting to httpClient");

 HttpClient httpClient;
  httpClient.get("http://arduino.cc/asciilogo.txt");
  while (httpClient.available()) {
    char c = httpClient.read();
    //Serial.print(c);
    Serial.write(c);
  }
}

The expected result is: I would like to see the characters from the txt file (https://www.arduino.cc/asciilogo.txt) in the serial monitor.

The actual result is: The connection to the WiFi can be established. In the serial monitor either question marks or strange symbols are displayed.

I have checked the baud and it is the same in the code and in the monitor. I tried to change this value, but it did not help.

it is http://arduino.cc/asciilogo.txt. without www. www is redirected to https. you can verify it from a browser


Problems with detecting button digital state I am trying to start an event after pressing and holding the FLASH built-in Nodemcu button for a specific time, I wrote two functions, one for debouncing and detecting the state, the other is to detect the pressing time, I'm not getting any result unless I decrease the input pressing time to less than 1s, which makes the button works as a single-push button, I think i have a problem with debouncing the button, I can't figure out where it is?
/**
* @brief debounces the button and returns the current level high or low
*
* @return int the button state 0: low, 1: high, -1 indetermined
*/
int button_state(int btn)
{
    int const DEBOUNCE = 200;
    static int hi = DEBOUNCE;
    static int lo = 0;
    if (digitalRead(buttonPin[btn]))
    {
        if (hi < DEBOUNCE)
        {
            hi++;
        }
        if (lo > 0)
        {
            lo--;
        }
    }
    else
    {
        if (lo < DEBOUNCE)
        {
            lo++;
        }
        if (hi > 0)
        {
            hi--;
        }
    }

    if (hi == DEBOUNCE)
    {
        return 1;
    }
    else if (lo == DEBOUNCE)
    {
        return 0;
    }
    else
    {
        return -1;
    }
}
/**
 * @brief Detects the button state and starts a time to calculate pressing duration
 *
 * @param btn input button pin
 * @param PressTime Desired pressing duration to compare to
 * @return int returns 1 when PressTime is reached
 */
int PressNHold(int btn, int PressTime)
{
    int lastButtonState = 0, Startpressed = 0, endPressed = 0, holdTime = 0,
    buttonState = button_state(btn);
    if(buttonState != -1)
    {
        if (buttonState != lastButtonState)
        {
            if (buttonState == 1)
            {
                Startpressed = millis();
            }
            else
            {
                endPressed = millis();
                holdTime = endPressed - Startpressed;
                if (holdTime >= PressTime)
                {
                    Serial.printf("Button %d pressed for %ds or more\n", btn, holdTime);
                    holdTime = 0;
                    return 1;
                }
            }
        }
    }
    lastButtonState = buttonState;
}
.....

void loop {

if (PressNHold(buttonPin[1], 5 * 1000) == 1)
  {
   //launch your event
  }

turns out that it is very simple, I shouldn't put buttonPin[1] a variable for PressNHold, I had to put just1, buttonPin was used already in button_state, also, PressnHold local variables should be declared static to not get a reset after function execution.


analogRead over a certain time I would like to read an analog value using analogRead, save this value and compare it to an analogRead value 5 ms later. How would this code look? Because giving a variable the value of analogRead(A0); would mean it is constantly changing, making it impossible to compare two values.

thanks in advance

The simplest and crudest method:

int val1 = analogRead(A0);
delay(5);
int val2 = analogRead(A0);

if (val2 > val1) {
    // It went up (for example).
}


Controlling multiple solenoids with arduino I was wondering how I could connect multiple 12v solenoids (more than the 53 allowed on mega because of the pins) on the Arduino Mega 2560 to get it to control the keys on a piano/keyboard/organ. Would 74HC595 shift register work for it with the 12v? (Many of them) Because there are so many high voltage solenoids is it possible to control a few of them at a time? I was wondering if someone has a link to somewhere that I could refer to. Thanks

Arduino I/O pins, and the output pins of 74HC595 shift registers are logic-level outputs, and are not intended to drive power-hungry items like solenoids. In either case (direct I/O or shift registers) you need to use the logic signal from the output pin to drive something else that switches the 12V source.

That something else can be a MOSFET or a relay, though often even relay coils are themselves driven by a MOSFET or other transistor that is switched by a microcontroller output pin.

One of the many search results that describe this is at http://hades.mech.northwestern.edu/index.php/Driving_using_a_single_MOSFET


Would Arduino Nano be good for Bluetooth + Sound So I've been browsing around for a whole looking for a good microcontroller that's super small. So far the smallest one I found was an Arduino Nano. But before I go buying it, there are some questions I have about it.

Is Bluetooth compatible with it and if so where would I get the Bluetooth code?
Is there anything smaller than it that's Bluetooth compatible?
Would an Arduino Nano (Or the device in the question above) be able to play sounds?

There are Bluetooth boards and chips that you can connect to a Nano.

You can play sounds with a Nano. Crudely with PWM and a direct connection, for finely with an external digital-to-analog converter.

But if super-smallness is what you are after, there may be better options.

The Blue Bean is a complete  BLE microcontroller on a single board that is smaller than a Nano+board.

If you want even smaller, you could get something like the new Cypress EZ-BLE module...

http://www.cypress.com/products/ez-ble-module-bluetooth-smart

It is a complete programmable BLE system on a tiny module. It is hard to imagine anything smaller than that!


Identifying Bootloader ttyACM# device I'm using a modified version of Arduino Zero Bootloader. I am trying to write software to automatically detect which USB device the bootloader is currently running on in order to execute bossac.

I have noticed a few unique characteristics when using "lsusb -v". Things like "bDeviceClass" is always 2. and "bDeviceSubClass" is always 0; However, I do not feel confident in using these traits to identify the bootloader. Is there any clear indication of bootloader so I can find the correct ttyACM#?

The only things you have at your disposal are what is in lsusb -v. Using those you can craft a udev rule to create a symlink to a unique device name. I do that with all my boards so that they all get a unique name.

Here is one of my rules:

ATTRS{idVendor}=="2341", ATTRS{idProduct}=="0042",
  ATTRS{serial}=="95336333635351F091B1", KERNEL=="ttyACM*",
  MODE="0660", GROUP="plugdev", SYMLINK+="board/arduino/mega2560"

That links /dev/board/arduino/mega2560 to whatever /dev/ttyACM* node got created when it was plugged in.  That is in /etc/udev/rules.d/50-boards.rules

More on udev here: http://playground.arduino.cc/Linux/Udev

A useful command is udevadm info -a -n /dev/ttyACM0 which lists all the attributes for that device which you can then use in the udev rule.


Arduino Nano USB Serial Bypass I have a Nano clone here, that sporadically fails to get detected by my banana pi. This is annoying, because it works for days and hours, but fails to work randomly.

The Nano gets it's own power via VIN and thus should have enough power.

I thought of bypassing the FTDI and make a Serial connection via 2 Wires. Alternatively: Is there a way to force the arduino to use external Power over USB. I have the feeling, the the arduino wrongly decides, that USB is the better power source and uses it, causing the errors ( device not accepting address 21, error -62 )

P.S.: There is also a touch-screen connected to the banana pi via USB. Whatever port I use, It works and never failed. Just the Nano fails from time to time.

To answer this question

The arduino in question was broken. Shortly after asking I was not even able to connect it to my PC successfully. I replaced it with a new one and everything runs smoothly now for months.

Since this unit survived a whole product development-process I am not surprised at all. In fact I had three and expected one to get killed in action.


From Wiring to pure C I'm using the Teensy 2.0 (atmega32u4) and decided to switch from Arduino IDE with Wiring to pure C. I think it's much more useful to master programming microcontrollers on that level. Wiring seems to be quite limited at some point.

It was really easy to use some basic libraries such as avr/io, or util/delay and write simple programs like "arduino hello world".

My problem comes with more complex tasks such as acting as usb mouse. On http://pjrc.com are references just to use with arduino ide/wiring. I couldn't find anything useful on google. Is there any good reference for pure C programming tennsy/arduino and/or using libraries such as "usb_mouse.h" (from pjrc.com) with pure C?

EDIT 1

Let me add some details (based of @st2000 answer).. Yes, Tennsy (and Arduino) are microcontrollers, not microprocessors. Programming avr chips in pure C doesn't require so much work as programming microprocessors. This is the simplest avr C program I could come with (typical blinky):

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

int main(void) {
        (CLKPR = 0x80, CLKPR = 0x00);
        DDRD |= (1<<6);
        PORTD &= ~(1<<6);

        int sviti = 0;

        while (1) {
                if (sviti)
                        PORTD |= (1<<6);
                else
                        PORTD &= ~(1<<6);
                sviti ^= 1;
                _delay_ms(40000);
        }
}

As you can see (@st2000), there are no dozens of setting up registers. It does not require any expensive equipment to upload resultant .HEX file - for teensy the only thing you need is a USB cable.

If you want a concrete example, I want to use this library with pure C, but it's obviously meant for wiring and arduino IDE primary. So how to use this library with pure C? And back to my main question, how to generally use libraries of this kind with pure C avr programming?

And back to my main question, how to generally use libraries of this kind with pure C avr programming?

just as how you would write under arduino ide -> arduino ide is nothing but pure c/c++ plus a set of canned libraries. so what you are trying to do is no different from what you are doing with arduino right now, maybe with your own libraries or libraries from folks other than the arduino folks.

nothing magic about going in "pure c".


Explanation please, of hardware and software serial links I am starting to use a Seeeduino GPRS shield (please see note), which is essentially an Arduino Leonardo that, among other things, can be used as a mobile 'phone for sending and receiving texts. I have successfully tried the "blink an led" and "fade an led" sketches, so the compiling and uploading are ok

I am using a desktop computer with Linux Fedora 20.

Now I want to go on to use the cell phone network to communicate with my mobile 'phone. However I am puzzled by something I assume everybody else understands already, and that is the references to "select either software serial port or hardware serial port to be connected to GPRS Shield". Please could someone explain what "software or hardware serial port" is, in simple terms, or point me to a web site that does so? Do I need any wired connection with my PC other than the USB link I use for uploading sketches?

Note: I bought a discounted GPRS shield labelled version 1.0a2. All the information on the 'net is of version 1.0 or 2.0 (with no "a2") and photos and diagrams do not correspond with what I have. I am awaiting official documentation, but meanwhile treating it as an Arduino Leonardo seems to be working.

Most small micro controllers, AVR's included, have dedicated hardware for communicating with different serial devices. In arduino these are referenced with "Serial", "Serial1", "Serial2" and so on, depending on how many hardware serial ports your particular arduino has.

Leonardo's are an exception, the first hardware port is "Serial1" and "Serial" refers to the PC's usb connection. On the other arduinos that I know of "Serial" is hardware serial used for PC comms, so using it for other hardware requires sacraficing your PC link.

Software serial ports use the processors more generic pin-change interrupt system to communicate on any pins that support said interrupts, but they have a higher processing overhead and often cannot support the same high speeds as the hardware serial. There are different libraries for Software Serial that have different approaches giving different advantages and drawbacks.

To use a software Serial port you will need to make one to be used in your code, which will look something like this, depending on the type name the library you include uses:

SoftwareSerial softSerial( txPinNumber, rxPinNumber);

So in short, your processor has dedicated hardware for communicating over serial that should be used first, but if you need more ports the processor can simulate some extras which is referred to as "Software Serial". The documentation to your GPRS shield implies that either will work just fine. You should look at the arduino documentation for your board to see how many ports you have and which pins can be used for serial.

The documentation does not imply you will need any special link to your computer outside of the USB connection.


Arduino simultaneous push button for a counter I am a newbie with arduino. I am trying to have a counter with 3 buttons. Each Button when pressed will increase the number of counts. The counter should still count if button 2 is pressed while button 1 has not been released, and button 3 should also be able to increase the counter even if button 2 and button 1 are still pressed.

My code below counts if only one button is pressed at a time.

#include <LiquidCrystal.h>
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
int pbutton1 = 2;
int pbutton2 = 3;
int pbutton3 = 4;
int count = 0;

void setup() {
  lcd.begin(16, 2);
  pinMode (pbutton1, INPUT);
  pinMode (pbutton2, INPUT);
  pinMode (pbutton3, INPUT);

  lcd.print("My Counter");
}

void loop() {

  lcd.setCursor(0, 1);
  lcd.print("Total ");
  if (digitalRead(pbutton1) == HIGH) {
    lcd.print(count++);
    while (digitalRead(pbutton1) == HIGH); //monitor button to avoid continous count
  }

  if (digitalRead(pbutton2) == HIGH) {
    lcd.print(count++);
    while (digitalRead(pbutton2) == HIGH); //monitor button to avoid continous count
  }

  if (digitalRead(pbutton3) == HIGH) {
    lcd.print(count++);
    while (digitalRead(pbutton3) == HIGH); //monitor button to avoid continous count
  }
}

while (digitalRead(pbutton1) == HIGH); This blocks execution so nothing else can happen while the button is pressed. To avoid continous updating of the var while the button is pressed, create 3 booleans that keep track of the button state.

bool button1_is_pressed = false;
....
// If the button is pressed AND it was not previously pressed
if (digitalRead(pbutton1) == HIGH && !button1_is_pressed) {
    button1_is_pressed = true;
    lcd.print(count++);
}
// Not pressed - reset state variable
else if (digitalRead(pbutton1) == LOW) {
    button1_is_pressed = false;
}

Do this for the other buttons as well.


Buying Arduino Parts Different Manufacturers I'm looking to buy my first arduino kit. However I have a concern.

If my Arduino Mega is bought from one manufacturer, then can I buy shields or other parts from other manufacturers? Are there any incompatibility issues

Thanks!

Of course you can. In just the same way that you can buy a car from one manufacturer and bumper stickers from another.

That's the whole point of the Arduino platform - mix and match to make things -just like LEGO®.


Generating analog signals is there a way to make the Arduino act as a voltage source, by generating sinusoidal, triangular and other kinds of signals? If so, can it be done using LabVIEW? (I've already managed reading analog signals using VISA)

Thank you!

The Due (and similar SAM based boards) have a DAC built in which can be set to different voltages (I forget the range off hand, maybe 0-Vcc at 12-bit resolution). Change that voltage fast enough, and you have a waveform.

Other Arduinos have PWM outputs which, when filtered through a low-pass filter, give a voltage proportional to the duty cycle of the PWM. Again, change the duty cycle fast enough and you have a waveform (limited by the carrier frequency of the PWM).

Can you do it from LabVIEW? Who knows? I have never used it.


Why I get error on string concatination? exit status 1
invalid operands of types 'const char [5]' and 'const char [2]' to binary 'operator+'

  String message = "Page not found\n\n";
  message += "URI: " + HTTP.uri() + "\n";
  message += "Method: " + (HTTP.method() == HTTP_GET)? "GET": "POST" + "\n";
  message += "Arguments: " + HTTP.args() + "\n";

The operators of the class String apply only for an instance of String. In your expression you concatenate two c-strings "POST" + "\n"


Reading CMPS10 raw values I've got a cmps10 compass module hooked up to my arduino due through a logic level converter. I am writing code to convert the raw magnetometer readings into a bearing that I can use but have run into a huge problem. My bearings are all funky for some reason. They are totally unrelated to the actual bearing of the robot. I know the sensor is fine because I am able to get the tilt compensated reading from it and it works great. One thing I noticed is that the magnetometer reading on the X-axis is always positive could this be the problem? The X-axis high byte generally between 0x00 and 0x03. My code is below (i2cBus = &Wire)

i2cBus->beginTransmission(I2C_Address);
i2cBus->write(byte(10));
i2cBus->endTransmission();

i2cBus->requestFrom(I2C_Address, 4);
xMagHighByte = i2cBus->read();
xMagLowByte = i2cBus->read();
yMagHighByte = i2cBus->read();
yMagLowByte = i2cBus->read();

xMag = short(xMagHighByte<<8);
xMag |= xMagLowByte;
yMag = short(yMagHighByte<<8);
yMag |= yMagLowByte;

if(yMag!=0){
  magBearing = (atan2(xMag,yMag)*180.0)/3.141592654;
}
else if(xMag>0) magBearing=0.0;
else if(xMag<0) magBearing=180.0;
else magBearing = 1000;
if(magBearing < 0) magBearing+=360;
magBearing=360-magBearing;
return magBearing;

Compass modules are highly susceptible to interference from ferrous deposits underground and metals in or around your robot. To correct for them, you need to shift and scale both axis.

But first, test if the sensor's X axis is working by watching the value while moving a small magnet around the sensor. If should overpower any stationary field and bias in the sensor, if it can't then there may be a problem with the sensor.

To calibrate the compass, first find the min and max value for each axis. Do this by reading all the outputs of an axis when moving the sensor in a complete circle in the environment you will be using it in. Making the robot drive in a circle when first turned on to calibrate itself is not a bad idea. Anyway, the shift is the negative average and the scale is half the difference between maximums. what really matters is that this "distance" is the same on both axis, but normalizing both is easier. For example,

float Scale, Shift, Value;
Scale =  (max-min)/2;
Shift = -(max+min)/2;
Value = float(raw+Shift)/Scale;

Once both axis are corrected the atan2() function can work properly. If you were to plot the x and y points on a graph, they should trace a unit circle at the origin.


How to Read ADC value without Common GND ? (Possible or not !) I want to Read external signal with the microcontroller.

But the problem is that ADC does not work because the signal GND and the microcontroller are not Common,

My question is, have you encountered such a problem? Is there a way to do it?

The solution is to always use at least 2 electrodes. You need 1 electrode, that you connect to ground. You can put this electrode to somewhere neutral (this instructable suggest connecting it to your leg, but I don't know, if that position is really good).

An ADC measures voltage and voltage is the difference in potential between 2 points, so to measure voltage you by definition need 2 points/connections.

Note: The voltages from the EEG electrodes are normally very low, so that they completely vanish in the noise. To really get something useful, you need to amplify the signal. I think there are many tutorials out there, that explain how to do this.


How to find the pin map for the LCD 1602 I2C adapter module? I'm working with I2C to work with my LCD 1602 and the I2C adapter.
This module has 16 pins and I don't know how to communicate with it.
I2C sends 8-bit packets. What are the commands to deal with this module, because it has 16 pins?
This is my current code:
void I2C_init(void);
void I2C_start(void);
void I2C_stop(void);
void I2C_tx(uint8_t data);
void I2C_TWSR_Check(void);

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  I2C_init();
  I2C_TWSR_Check();
  I2C_start();
  I2C_TWSR_Check();
  I2C_tx(0x20);
  I2C_TWSR_Check();
}

void loop() {
  uint8_t i;

  for (i = 0; i < 5; i++)
  {
    I2C_tx(0xff);
    I2C_TWSR_Check();
    _delay_ms(500);
  }
}

void I2C_init(void) {
  //set SCL to 100kHz
  TWSR = 0x00;
  TWBR = 0x48;
  //enable TWI
  TWCR = (1 << TWEN);
}

void I2C_start(void) {
  TWCR = (1 << TWINT) | (1 << TWSTA) | (1 << TWEN);
  while (!(TWCR & (1 << TWINT)));
}

void I2C_stop(void) {
  TWCR = (1 << TWINT) | (1 << TWSTO) | (1 << TWEN);
}

void I2C_tx(uint8_t u8data) {
  TWDR = u8data;
  while (!(TWCR & (1 << TWINT)));
}

void I2C_TWSR_Check(void) {
  uint8_t Status;
  Status = TWSR & 0xF8;
  switch (Status)   {
    case 0x08:    // start OK
      Serial.println("Start is OK");
      break;
    case 0x10:    // Re start
      Serial.println("Re start");
      break;
    case 0x18:        // SLA+W OK ACK
      Serial.println("SLA+W OK ACK");
      break;
    case 0x20:        // SLA+W no ACK
      Serial.println("SLA+W no ACK");
      break;
    case 0x28:        // data OK ACK
      Serial.println("data OK ACK");
      break;
    case 0x30:        // data OK no ACK
      Serial.println("data OK no ACK");
      break;
    case 0x38:        // arbitration lost in SLA+W or data TX
      Serial.println("arbitration lost in SLA+W or data TX");
      break;
    default:
      Serial.println("Error");
      break;
  }
}

I don't know I get first case working all the time. I can't proceed to sending the data.
This is the most I got from google images:
PCF8574 I2C backpacks for HD44780 Compatible LCD Module Arduino Raspberry

The ￼tronixstuff page about PCF8574-based backpacks for LCD modules and Arduino (with material that also appears in an instructable) includes a sketch that most likely will work with that backpack.

Once you've identified which I2C library to use, and the appropriate object instantiation, most of the general API description (that is, “the commands to deal with this module”) as shown at arduino.cc's LCDi2c Library page and at arduino.cc's LCD API 1.0 page will apply.

The I2C library-include and the appropriate object instantiation for the backpack shown in your link probably will look much like:

#include <LiquidCrystal_I2C.h>
...
LiquidCrystal_I2C lcd(0x27,2,1,0,4,5,6,7);

For documentation of what the numbers mean, see lines 82 to 90 of LiquidCrystal_I2C.h:

@param      lcd_Addr[in] I2C address of the IO expansion module. [...]
@param      En[in] LCD En (Enable) pin connected to the IO extender module
@param      Rw[in] LCD Rw (Read/write) pin connected to the IO extender module
@param      Rs[in] LCD Rs (Reset) pin connected to the IO extender module
@param      d4[in] LCD data 0 pin map on IO extender module
@param      d5[in] LCD data 1 pin map on IO extender module
@param      d6[in] LCD data 2 pin map on IO extender module
@param      d7[in] LCD data 3 pin map on IO extender module

Briefly, 0x27 is the I2C address of the PCF8574 chip on the backpack.  Note, if your backpack has a PCF8574A, its address is 0x3F.

The other seven numbers describe which PCF8574 output pin is connected for each designated purpose.  Most PCF8574/PCF8574A I2C backpacks are wired the same and numbers 2,1,0,4,5,6,7 are appropriate.

Edit 1: If you write an LCD-with-backpack library of your own and expect to publish it, it is reasonable to comply with the LCD API mentioned earlier.  By using standard interface functions, you will make it possible for users to plug in your library in place of others with the same interface.  In addition, the availability of sketches using the LCD API provides you with a range of test material to verify your drivers.

In writing an LCD-with-backpack library, start by solidifying your understanding of each of the parts – LCD and backpack – separately.

LCD:  Get some HD44780-based LCD units; hook one up using direct wiring or a shield rather than a backpack; install a known-good library and sketch; run tests to verify the wiring.  With the wiring known to work, develop an LCD control library.  This may require detailed study of the Hitachi HD44780U data sheet or other HD44780 data sheets.  The necessary timing for LCD control is picky enough that it would be a fool's errand to not verify the wiring using known-good software before writing your own.

Backpack:  Plug the 16 pins of a backpack into a breadboard, and attach LED cathodes to all the breadboard pins that connect to PCF8574 output pins.  Use appropriate resistors to V+ on the anode sides of the LEDs.  Connect the backpack's SDA, SCL, V+, and ground to that of your Arduino.  Write simple test software using Wire.h calls to send data to the PCF8574, verifying proper operation using the LEDs.  This may require detailed study of the Texas Instruments PCF8574 Remote 8-Bit I/O Expander for I2C Bus data sheet.  Write your PCF8574 control library.  Adapt your LCD control software to send data via the PCF8574 library instead of via direct wiring.


I2C potentiometer mess I bought a few MCP4651 dual 8 bit I2C pots for a project. After browsing the arduino libraries and finding nothing,"No big deal" I thought to myself ... I've already written I2C libraries for other parts that were much more complicated! (e.g: ADS1219 24 bit ADC)! so just load up the datasheet and watch the memory maps and commands! ok, there are some stuff on page 49 which seem useful! oh boy was I ever wrong! this data sheet looks like nightmare! the worst documentation for any I2C device I've seen so far. The commands I wrote based on that did absolutely nothing!

I found a code for controlling an I2C pot in one of the arduino examples which is something like this:

#include <Wire.h>

void setup() {
  Wire.begin(); // join i2c bus (address optional for master)
}

byte val = 0;

void loop() {
  Wire.beginTransmission(44); // transmit to device #44 (0x2c)
  // device address is specified in datasheet
  Wire.write(byte(0x00));            // sends instruction byte
  Wire.write(val);             // sends potentiometer value byte
  Wire.endTransmission();     // stop transmitting

  val++;        // increment value
  if (val == 64) { // if reached 64th position (max)
    val = 0;    // start over from lowest value
  }
  delay(500);
}

I decided to just try it and see what happens (changed the address to the correct value) and crazy enough it actually worked! so I hacked this piece of code to get the first pot to work!

void setPot0(int n){
  if (n>256) n=256;
  if (n<0) n=0;
  Wire.beginTransmission(address);
  if (n<256){
    Wire.write(0x00);
    Wire.write(n);
  } else{
    Wire.write(0x01);
    Wire.write(0);
  }
  Wire.endTransmission();
}

and somehow this works! I still can't find this pattern in any of the pages on datasheet, but hey! it works so I'm not gonna complain about that?
I still haven't managed to make the pot1 to work, only pot0 ... if you can make sense of how the commands and data bytes should be like, please help me. It's so much more clear in T.I datasheets; you just use the command to write to the register you want and they detail what each register does:

Edit: here is a link to the datasheet: http://ww1.microchip.com/downloads/en/DeviceDoc/22096b.pdf

The registers are listed in table 4-1. Clearly enough.

The command byte format is shown in chapter 6. That command byte includes the operation and the register number, as well as upper bits for registers that expect more than 8 bits of data.

Two bytes are needed to set a register.  The first 4 bits are the register number (0000 for wiper 0, 0001 for wiper 1, and 0100 for the TCON register).  The next two bits are the operation as shown in figure 7-1. 00 for a simple write. The next two bits are the upper 2 bits of the data.  Following that are the lower 8 bits of data.

So to write a pot 0 value of 0x23 you would write:

0x00 0x23

To write a pot 1 value of 0x65 you would write:

0x10 0x65

To write a pot 1 value of 0x13D you would write:

0x11 0x3D

You can make a simpler function to wrap it for you:

void writePot(uint8_t address, uint8_t pot, uint16_t val) {
    Wire.beginTransmission(address);
    Wire.write((pot & 3) << 4 | ((val >> 8) & 3));
    Wire.write(val & 0xFF);
    Wire.endTransmission();
}


Is it possible for Arduino to send a message to the internet without using a GSM shield? I need an Arduino to send a message, to be displayed on the web, after pressing a push button, which is connected to an Arduino [or shield], without using a GSM shield.

I need to send a message just by using HTML/PHP code included in the Arduino IDE. This displayed message should contain two buttons. One button is used to turn a LED ON/OFF and the other to open a streaming video.

Can anyone help me with the Arduino code and explain how I should do that? Is there any third party device, apart from a GSM shield, that can help me to send that message?

Use this example to open a webpage using a push button, you need Python installed on your Windows.

Step 01:

Upload this sketch to your arduino:

const int buttonPin = 2; // the number of the pushbutton pin
int buttonState = 0;

void setup() {
  Serial.begin(9600);
  pinMode(buttonPin, INPUT);
}

void loop() {
  buttonState = digitalRead(buttonPin);
  if (buttonState == HIGH) {
  Serial.println("OpenWebPage");
  }
}

The Circuit:

pushbutton attached to pin 2 from +5V
10K resistor attached to pin 2 from ground

Step 02:

Open a text editor and paste this code to a new file:

import serial
from subprocess import call

ser = serial.Serial(
    port='COM5', # Change this to your COM port number
    baudrate=9600,
    parity=serial.PARITY_ODD,
    stopbits=serial.STOPBITS_TWO,
    bytesize=serial.SEVENBITS
)

if (ser.isOpen()):
    print "Serial Port is Open..."
    print "Waiting for a command ..."
    while 1:
        cmd = ser.readline()
        if cmd.strip() == "OpenWebPage":
            print "Received command from Arduino..."
            print "Opening webpage..."
            call(["explorer", "http://www.google.com"]) #change it the address you want

Save the file to your desktop, name it : SerialListener.py

Step 03

Now open a Command Prompt window.
Navigate to your desktop folder and execute this command: python SerialListener.py.
You should see Serial Port is Open... Waiting for a command ...
Press the push button, and a webpage should open in your default browser.


Problem in AT+CIPSEND(CTRL-Z) GPRS GMS A6 I am using GPRS GSM A6 with arduino uno to post data to web server. After sending AT commands to module I get OK response after every command,

AT+CIPMUX=0

OK
AT+CGATT=1

OK
AT+CSTT="internet","",""

OK
AT+CIICR

OK
AT+CIFSR

10.65.87.210

OK
AT+CIPSTART="TCP","xxx.xxx.xxx.xxx", 80

CONNECT OK

OK
AT+CIPSEND

> POST http://xxx.xxx.xxx.xxx/Code/ HTTP/1.1
Host: xxx.xxx.xxx.xxx
Content-Type: application/x-www-form-urlencoded
Content-Length: 18

Data=GPS Data Sent
AT+CIPCLOSE

>

To terminate AT+CIPSEND you have to send CTRL-Z. I am sending CTRL-Z using this statement in code,

Serial.write(0x1A)

But the module doesnot respond to this, and treats the next command (AT+CIPCLOSE) as data.

Please Help... Thanks in Advance!!!

RTFM: https://github.com/espressif/esp8266_at/wiki/CIPSEND

You need to close the input steam with "+++" to return to command mode.


Is AREF a stable output Ref voltage with analogReference(INTERNAL) I'm using an analog input on a NANO board to measure the midpoint between two photo resistive (Cadmium) cells, with the two outside ends tied to GND and a source voltage. Basically a simple voltage divider. So it almost wouldn't matter what reference voltage I used in a case like that, as long as the AnalogReference() was correctly set corresponding to the reference voltage, AND the load did not pull down that voltage.

Well if I used the 5V for my source, and set AnalogReference(DEFAULT), then assuming a worst case load of 4K-ohm, the total load on the 5V regulator is still only 1.25mA. But even so, I figured I could minimize the system load even more by setting AnalogReference(INTERNAL), and using the VREF pin as a source for my voltage divider.

Well it seems to work fine, but I don't know that I've seen any actual examples of what I'm doing, which is using the AREF pin as a source output voltage for my voltage divider. Using vREF as a source, a 4K load would only draw 27.5 microamps with a 1.1V source. But I can't find any spec for the max current I should avoid exceeding, That has me worried maybe I'm not even supposed to be doing that!

So is it acceptable to use the VREF pin as an output for light loads, when using the INTERNAL AnalogReference?

Thoughts?

EDIT: After receiving a "no" answer yesterday, I did some bench checking. I configured my NANO board for Internal, and connected a fully open 100K linear pot from AREF to Ground, with a DVM in parallel. The AREF terminal output was about 1.076, with or without the 100K load. Not quite the 1.1 specified but close enough. I then slowly rotated the pot to increase load. At just under 9K the voltage dropped a somewhat insignificant amount, to 1.075. From there on there were additional small decreases, down to about 1K, at which point i measured about 1.062V. Below 1K, there was a very steep decrease.

Note that this was a "quickie" test, done while powering the NANO from a USB port. However, repeating the test with 12V on the DV input did not alter the results significantly.

Even considering the USB source, from this test I conclude:

1) There does appear to be some buffering on the VREF output. It certainly did not behave as there was a simple case of a 1.1V source in series with a high impedance.

2) Up to a load of 10K, the VREF output seems at least as stable as the 5.0V regulator output.

3) Since a 1.062 drop from an initial no-load voltage of 1.076 equates to less than a 2% difference, I have to conclude that a load on VREF (to ground) greater than 1K (lets say 2K for margin) makes VREF probably useful in cases like i described, with a worst case load of 4K.

4) I repeated my test with a second NANO board. This time the initial no-load voltage was salightly higher, 1.084. However, the response to increasing load and the K point where the slope changed dramatically were unchanged.

Again, this is an arduino NANO board, and probably a clone. Can anyone else verify or disprove my results? I'm sure someone else will need to consider using VREF as I did, and it would be good to know.

No, it is not acceptable.

The datasheet states:

  AVCC is connected to the ADC through a passive switch. The internal 1.1V reference is generated from the internal bandgap reference (VBG) through an internal amplifier. In either case, the external AREF pin is directly connected to the ADC, and the reference voltage can be made more immune to noise by connecting a capacitor between the AREF pin and ground. VREF can also be measured at the AREF pin with a high impedance voltmeter. Note that VREF is a high impedance source, and only a capacitive load should be connected in a system.

The 1.1V reference is only presented on the AREF pin for the purpose of adding an external bypass capacitor, or for measuring it using a very high impedance meter. Any load applied to the pin will cause the reference voltage to droop.

While it may work in certain circumstances it's certainly not recommended. If you want to use it externally you should buffer it through a high-impedance unity-gain voltage follower:

simulate this circuit – Schematic created using CircuitLab


NEED Help With Servo motor I have just bought a MG90s tower pro servo for my school project and there is a problem. As soon as I connect my servo to the cnc shield or directly arduino, the whole arduino board turns off. I believe the motor is aking very high power. I even tried to power the motor with a 5v 2amps adapter, but still it turns off.I checked the resistance between the input wires and the wires to DC motor which was very high. As soon as I connected motor to external supply, there was a huge voltage drop. The voltage became almost negligible. DC motor was working fine alone. The servo hasn't even rotated for 1 degree. Please give me a quick solution as I am in a hurry for school deadline is coming. Should I buy a new servo or am I doing something wrong?
Please be quick.
Thank you.
Circuit diagram is below...]1

The code is below -

#include <Servo.h>

Servo name_servo;

int servo_position = 0;

void setup() {

name_servo.attach (9);

}

void loop() {

  for (servo_position = 0; servo_position <=180; servo_position +=1){

    name_servo.write(servo_position);
    delay(10);
  }

  for (servo_position=180; servo_position >= 0; servo_position -=1){

    name_servo.write(servo_position);
    delay(10);
  }
}

Your conclusion is correct. The servo motor is asking a lot of current.

You need a power supply that is more than 2amps. Connect the grounds (the servo black wire to the Arduino GND). Don't let the current for the servo motor go through the Arduino board. Use wires for the servo motor that can handle high currents. Don't let the power for the servo motor go via a breadboard, because the small metal contacts of a breadboard are not for high currents.

Can you get a smaller servo motor?

Could there be something wrong with the 2 A power supply? Is it a certified and good quality power supply?

Tower Pro does not tell what the stall current of the MG90S is: www.towerpro.com.tw/product/mg90s-3/


delay(time); vs if(millis()-previous>time); and drift Going through an old project, I had code on two Arduino Due that looked like this

void loop()
{
  foo();
  delay(time);
}

taking to heart the majority of literature on using delay(); I recoded this as

void loop()
{
  static unsigned long PrevTime;
  if(millis()-PrevTime>time)
  {
    foo();
    PrevTime=millis();
  }
}

However, this seems to have created a situation where the two devices drift over a period of time when they didn't previously

My question is twofold:

Why would if(millis()-PrevTime>time) cause more drift than
    delay(time)?
Is there a way to prevent this drift without going back to delay(time)?

There's one important thing that you need to remember when working with time on an Arudino of any form:

Every operation takes time.

Your foo() function will take an amount of time. What that time is, we cannot say.

The most reliable way of dealing with time is to only rely on the time for triggering, not for working out when the next triggering should be.

For instance, take the following:

if (millis() - last > interval) {
    doSomething();
    last = millis();
}

The variable last will be the time the routine triggered *plus the time doSomething took to run. So say interval is 100, and doSomething takes 10ms to run, you will get triggerings at 101ms, 212ms, 323ms, etc. Not the 100ms you were expecting.

So one thing you can do is to always use the same time regardless by remembering it at once specific point (as Juraj suggests):

uint32_t time = millis();

if (time - last > interval) {
    doSomething();
    last = time;
}

Now the time that doSomething() takes will have no effect on anything. So you will get triggerings at 101ms, 202ms, 303ms, etc. Still not quite the 100ms you wanted - because you're looking for more that 100ms having passed - and that means 101ms or more.  Instead you should use >=:

uint32_t time = millis();

if (time - last >= interval) {
    doSomething();
    last = time;
}

Now, assuming that nothing else happens in your loop you get triggerings at 100ms, 200ms, 300ms, etc.  But note that bit: "as long as nothing else happens in your loop"...

What happens if an operation that takes 5ms happens to occur at 99ms...? Your next triggering will be delayed until 104ms. That's a drift. But it's easy to combat. Instead of saying "The recorded time is now" you say "The recorded time is 100ms later than it was". That means that no matter what delays you get in your code your triggering will always be at 100ms intervals, or drift within a 100ms tick.

if (millis() - last >= interval) {
    doSomething();
    last += interval;
}

Now you will get triggerings at 100ms, 200ms, 300ms, etc. Or if there are delays in other bits of code you may get 100ms, 204ms, 300ms, 408ms, 503ms, 600ms, etc.  It always tries to run it as close to the interval as possible regardless of delays.  And if you have delays that are greater than the interval it will automatically run your routine enough times to catch up with the current time.

Before you had drift. Now you have jitter.


Triggering an ultrasonic sensor I made a smart blind stick for my class project. It uses an ultrasonic sensor to detect obstacles and I was asked this question in VIVA...

Why is it necessary for giving a digital high for 10 μS on the trigger (Trig) pin of an ultrasonic sensor ?

Why 10 μS only?

I changed it to 5 μS then to 20 μS and to 50 μS and it still works fine! Why so?

The specification1 says (emphasis is mine):

using IO trigger distance, the high signal to at least 10us.

So, longer than 10 μS is not a problem.
With respect to less than 10 μS, well 5 μS may also work, but it is out-of-spec and therefore not guaranteed to work and so may not always work correctly, or as expected.
From Source 1:

From Source 2:

As to why must it be 10 μS, well that is probably (at a guess) down to the design of the logic upon the silicon and the resultant propagation delay through the logic gates. Most, if not all, logic ICs specify a minimum amount of time required for a signal level, in order to allow the signal to propagate through the transistors that make up the logic, so that they switch correctly. PN junctions require a finite time for the electrons and holes to move, and when there are a number of them in sequential stages, that time is multiplied by the number of stages that the signal needs to propagate through. That is a very simplified way of looking at it.
To confirm this, you would need to speak to either the designers, or take a look at the mask used to fabricate the IC. Test simulations were probably run during the design phase, and they suggested a minimum trigger pulse of 10 μS. The figure could also be arrived at by simply looking at the design and counting the number of stages and multiplying that by the propagation delay per stage.
However, as Valbhav points out, the HC-SR04 is controlled by a STM8 (actually it is a STC11F), and after having looked at the STM8 programming manual, it is more related to instruction cycles. The Trig pin is, I assume, an interrupt, and from section 3.2 CPU registers

When an interrupt occurs, the CPU registers (CC, X, Y, A, PC) are pushed onto the stack.
This operation takes 9 CPU cycles and uses 9 bytes in RAM

So, 9 CPU cycles just begin to to service the interrupt, and then however many needed to actually do the rest. I can't find any timing diagrams in the Programming Manual which would show the minimum interrupt signal length.  This information, is however in the Reference Manual
The length of a CPU cycle will obviously depend upon the clock frequency., which according to this schematic, from An Ultrasonic Shortcut – Getting the HC-SR04 Transducer Up and Running Fast!, is 4 MHz:

So, 10 μS is 40 CPU cycles.

1 Sources for downloading HC-SR04 pdf datasheet:

Source 1
Source 2

HC-SR04 Specifications

Working Voltage: DC 5V
Working Current: 15mA
Working Frequency: 40Hz
Max Range: 4m
Min Range: 2cm
Measuring Angle: 15 degree
Trigger Input Signal: 10µS TTL pulse
Echo Output Signal Input TTL lever signal and the range in proportion
Dimension 45 * 20 * 15mm


Cant find Sdl and Sca pins in lcd display My project is of non contact temperature sensor.I am using RG1602A lcd display and mlx90164 temperature sensor.
But the problem is, there's no sdl , sca pins in my lcd display.
Is there any way, to overcome?

You will need an I2C adapter board like this to interface your LCD 1602 via I2C.


About ATTINY85 Development Board I am thinking to buy one of "ATTINY85 Development Board"...

Before buying I was checking details/Advantages of it.

First I thought this is just a breakout board & USB for power.

But, then found It can be programmed with "Digispark driver & board manager" directly by the USB.

I checked this Question: EBay “Development Programmer Board for ATtiny”

Someone said there:

  "While limited, this type of board can be useful for "blink an LED on
  USB command" type tasks"

My Main question is:

Is it really programmable withut any TTL/ICSP/FTDI extention?

If so, is it possible to program other AVR chip (Attiny/Atmega) with simple codes directly via USB...?

(with same method)

Is it really programmable withut any TTL/ICSP/FTDI extention?

Only if you use an ATTiny chip that has the "Micronucleus" bootloader already installed.

  If so, is it possible to program other AVR chip (Attiny/Atmega) with simple codes directly via USB...?

Some can, but most need a bootloader installing. The ATMega32U4, for example, has a "DFU" mode, which is essentially a bootloader in ROM, that you can use directly over USB.  In general, though, the answer is "Not without installing an appropriate bootloader with some hardware programmer first".


How to read and write EEPROM in ESP8266 I need to know how I can write integer values in EEPROM and retain the value on power on.

char *Red = strstr(myTestUrl, "/R");
if (Red) {
  int RedValue  = atoi(Red + 2);
  analogWrite(12, RedValue);
  Serial.println("Red :");
  Serial.println(RedValue);
}

I want to write RedValue in EEPROM. How can it be done?

While EEPROM.read and EEPROM.write are valid methods, it's like mopping the floor with a toothbrush. Use EEPROM.put and EEPROM.get instead.

For example:

#include <EEPROM.h>

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

  uint addr = 0;

  // fake data
  struct {
    uint val = 0;
    char str[20] = "";
  } data;

  // commit 512 bytes of ESP8266 flash (for "EEPROM" emulation)
  // this step actually loads the content (512 bytes) of flash into
  // a 512-byte-array cache in RAM
  EEPROM.begin(512);

  // read bytes (i.e. sizeof(data) from "EEPROM"),
  // in reality, reads from byte-array cache
  // cast bytes into structure called data
  EEPROM.get(addr,data);
  Serial.println("Old values are: "+String(data.val)+","+String(data.str));

  // fiddle with the data "read" from EEPROM
  data.val += 5;
  if ( strcmp(data.str,"hello") == 0 )
      strncpy(data.str, "jerry",20);
  else
      strncpy(data.str, "hello",20);

  // replace values in byte-array cache with modified data
  // no changes made to flash, all in local byte-array cache
  EEPROM.put(addr,data);

  // actually write the content of byte-array cache to
  // hardware flash.  flash write occurs if and only if one or more byte
  // in byte-array cache has been changed, but if so, ALL 512 bytes are
  // written to flash
  EEPROM.commit();

  // clear 'data' structure
  data.val = 0;
  strncpy(data.str,"",20);

  // reload data for EEPROM, see the change
  //   OOPS, not actually reading flash, but reading byte-array cache (in RAM),
  //   power cycle ESP8266 to really see the flash/"EEPROM" updated
  EEPROM.get(addr,data);
  Serial.println("New values are: "+String(data.val)+","+String(data.str));
}

void loop()
{
  delay(1000);
}

UPDATE:  If you want to understand how the "EEPROM" is emulated in the ESP8266, you might want to reference https://github.com/esp8266/Arduino/tree/master/libraries/EEPROM, specifically, EEPROM.h.

Also, EEPROM.end is not needed, it simply clears the local byte-array cache of the flash/EEPROM from RAM.  It serves on other function.


Arduino CH340 Driver Problem I'm trying to connect my Arduino Uno to the Arduino IDE in Windows, but the only way it works is with a CH340 driver.
I am concerned about this as I can only find a download of it published by two Chinese companies- wch.cn or Jiangsu Qinheng Co., Ltd.- maybe they're both 1 company; even when Windows looked for a driver on the web that was the one it downloaded.
When I went to Device Manager to look for the driver in the official Arduino download zip, Windows said it couldn't find any drivers.
I am concerned about the security implications of the driver being Chinese and wonder if there are any other CH340 drivers (unless CH stands for China...)
Anyway thx for answering!!! :)

WCH is the manufacturing company that first produced the CH340. They are Chinese.


Sending a character 'A' through blinking led How do i code to send a character 'A' to the arduino through a blinking led?
   i am doing a project about data transmission. i really need help&some guide.
   Material used are arduino uno r3,white led and a resistor.

MY OUPUT IN SERIAL MONITOR

Insert letter:

01000001 65  - Character A

00001010 10  - when i send/enter

CODE

 int LEDTrans = 13;
int timeWaitOn = 1000; //milisec (1 sec)
int timeWaitOff = 1000; // milisec (1 sec)
byte byteRead;

void setup() {
// Turn the Serial Protocol ON
  Serial.begin(9600);

 Serial.print("Insert letter:");
 Serial.println(" ");
}

void loop() {

digitalWrite(LEDTrans,HIGH); //turn the led on
delay(timeWaitOn); //delay in millisec (1 sec)
digitalWrite(LEDTrans,LOW); //turn the led off
delay(timeWaitOff); //wait a sec

   /*  check if data has been sent from the computer: */
  if (Serial.available()) {

     byteRead = Serial.read();
    // will print the binary representation of 'byteRead' as 8 characters of '1's and '0's, MSB first.
for ( uint8_t bitMask = 128; bitMask != 0; bitMask = bitMask >> 1 ) {

      if ( byteRead & bitMask ) {

    Serial.write('1');
  } else {
    Serial.write('0');
  }
}

Serial.write("    ");
Serial.println(byteRead);    //send back the actual ASCII code
}

}

Instead of printing '0' or '1' set the LED pin off or on, like this:

const int LEDTrans = 13;
const int timeWaitOn = 1000;  // millisec (1 sec)
const int timeWaitOff = 1000; // millisec (1 sec)

void setup() {
  // Turn the Serial Protocol ON
  Serial.begin(115200);
  Serial.println("Send letter:");
  pinMode (LEDTrans, OUTPUT);
}

void loop() {
  /*  check if data has been sent from the computer: */
  if (Serial.available()) {
    byte byteRead = Serial.read();
    // will print the binary representation of 'byteRead' as 8 characters of '1's and '0's, MSB first.
    for ( uint8_t bitMask = 128; bitMask != 0; bitMask >>= 1 ) {
      if ( byteRead & bitMask ) {
        digitalWrite(LEDTrans, HIGH); //turn the led on
        delay(timeWaitOn); //delay in millisec (1 sec)
        digitalWrite(LEDTrans, LOW); //turn the led off
      } else {
        delay(timeWaitOff); //wait a sec
      } // end of if
    } // end of for loop
  } // end of if something available
} // end of loop

  how do i count the flashes? is it based on the binary 01000001?

Here's the problem ... according to what your question seems to ask for, you are wanting an LED to flash for a 1 and be off for a zero. So the results (which my code provides) would look like this:

So, you get two flashes, the first one second after it starts, then there is a gap of 5 seconds, and then another flash. That would be 01000001.

However, how do you know when to start counting flashes? It might be:

That would be 00000001.

Or even:

That would be 10000010.

You can see, can't you, that you can't make any meaningful deduction at the receiving end about what the character is?

So what asynchronous serial (normal serial on an Arduino) does is have a Start Bit which signals when to start counting, like this:

Normally the serial port is high (continuous 1s) and then when a 0 arrives that means "start counting". So, you wait 1½ bits of time and then sample at the known baud rate. In your example, where you want 1 second per bit, the baud rate would be 1 (one bit per second). Thus, you sample every one second. Normally baud rates are somewhat faster than that, like 9600 or 115200 samples per second.

Also there is a Stop Bit which is always a 1. This guarantees that there will be at least a single 1 at the end of each byte, so that we can tell when the next start bit arrives.

There are other ways of doing this, for example a short pulse might represent a zero, and a longer pulse represent a one. In that case, any pulse at all could represent the start of a byte, and then you just measure how many short pulses, and how many long pulses, you get (for some definition of "short" and "long").


Variable sets to 32767 - MATLAB Arduino I am running out of ideas of what may be causing this problem, and I would appreciate some help identifying anything I am overlooking.

Quick Problem Summary

A variable gets set to 32767 quite often and I am unsure why. I tried checking if it was a types problem, if there was somewhere in my code it could overflow, any division by 0, initialising all variables in all sections of the code, and have now tried to cast all relevant variables to int. What else could I try?

This is how this variable gets set in a C++ function:

readValue = readAverage(A0);
targetValue = 2000; // Some constant number set beforehand
myVariable = targetValue - static_cast<int>(round(readValue));

// After some operations that only check if myVariable is within a range

// There are several states in which LOG_myVariable can get set in case there is an error where data wants to get logged
LOG_myVariable = myVariable

All of the variables above are public and get initialised to 0. See in the context section to see how the readAverage function works.

This code block above gets repeated thousands of times in a loop and exits when I send an interrupt. LOG_myVariable only gets set in the method above. Sometimes it gives me normal values that I would expect, but it is returning 32767 very often. Is this some C++ syntax or function I am overlooking?

Some context:

An Arduino Due is using the MATLAB 2019 - Arduino Support Package Add-on. The variables described above are stored in memory and are dynamically overwritten during every logging function. I send them back to MATLAB via the C++ commandHandler as:

byte dataOut[2] = {
                  highByte(LOG_myVariable),
                  lowByte(LOG_myVariable)
                  };
sendResponseMsg(commandID, dataOut, 2);

In MATLAB, I convert it within a method after requesting the dataOut via sendCommand:

[dataOut] = sendCommand(arduinoObj, arduinoObj.LibraryName, commandID, dataIn);
            % Converts the two High and Low bytes from [dataOut] into a single integer.
            myVariableMATLAB = 256 * dataOut(1) + dataOut(2);

readAverage works like this:

/*
Reads the raw ADC sampled value of a pin an averagePoints amount of times.
All the values get averaged and the function returns `outputAverage`.
Note
*/
int myClass::readAverage(const uint8_t pin) {
  int i = 1, outputAverage = 0;  // Iteration value, OutputAverage
  double sum = 0, runningAverage = 0;
  // Array Initialization
  int readings[70] = { 0 };

  for (i = 0; i <= 70; i++) {
    if ((runningAverage >= 0) && (runningAverage <= 4096)) {
      // First 10% readings to setup a runningAverage value
      if (i < 70 * 0.1) {
        readings[i] = static_cast<int>(analogRead(pin));
        sum += readings[i];
        runningAverage = static_cast<int>(sum/(i+1));

      } else if (i >= 70 * 0.1) {
        // Normal Operation
        readings[i] = static_cast<int>(analogRead(pin));

        // Filtering Outliers
        // If xReading is within [LOWER_PERCENTAGE, HIGHER_PERCENTAGE] * runningAverage range.
        if ((readings[i] >= LOWER_PERCENTAGE * runningAverage)
        && (readings[i] < HIGHER_PERCENTAGE * runningAverage)) {
          sum += readings[i];
          runningAverage = static_cast<int>(sum/(i+1));
        } else {
          // Enter Error/ Out of Bounds Log Mode, how?
          // Meant to filter out
        }
      }
    } else {
      /* Enter Unknown Error Mode
      Note it defaults to a single measurement, but no signal is sent to mention this.
      */
      runningAverage = static_cast<int>(analogRead(pin));
    }
  }
  outputAverage = static_cast<int>(round(runningAverage));
  return outputAverage;
}

Any tips on improving the code/logic are always appreciated too!

Some findings:

Your for loop iterates over 71 results, but your array has only the length 70.
You may overwrite variables in the memory behind the array.
You can use else instead of else if (i >= 70 * 0.1) because it is just the negation of the if (i < 70 * 0.1). In the else case (i >= 70 * 0.1) is always true.

What is the type of myVariable? If you assign incompatible types (signage or length) an over- or underflow can happen. 32767 = 2^15 - 1 = 0b0011111111111111 (14 bits on) that looks pretty much like an underflow and a conversion of incompatible types.

EDIT:

By a second read of your question I saw another possibility of failure:

You copy the bytes of a two byte signed integer into 2 bytes and send it to matlab.

byte dataOut[2] = {
  highByte( LOG_myVariable ),
  lowByte( LOG_myVariable )
 };

Let's say you have a negative number in LOG_myVariable. In Memory this is represented with a one in the highest bit (MSBit) and the complementary bit string plus one (two's complement: See Wikipedia).

An Example:

16 bit signed int -1 is represented as 0b1111111111111111 you split it in two bytes 0b11111111 and 0b11111111. The you send it to Matlab.

Now it depends on how Matlab interprets the bytes. Are that unsigned int8 or signed int8? you combine the bytes like so:

 myVariableMATLAB = 256 * dataOut(1) + dataOut(2);

If Matlab interprets the bytes as unsigned  you get 256*(-1) + (-1) == -257 but that's not -1. And if it interprets the bytes unsigned it gets 256*255+255 == 65535 which is also not -1. I bet there is a negative number that gives you 32767.


Help avoiding floating point math I'm using a Texas Instruments DRV2605 haptic controller in my project to drive a LRA vibration motor. I would like to calculate the LRA rated voltage during run time using the formula below as provided in the datasheet:

I'm successfully calculating the rated voltage, but the calculation requires floating point calculations and I would like to avoid that because I'm low on available flash space on my ATTiny85 micro controller. Here is how I'm currently calculating the rated voltage value:

uint8_t LRA_closed_loop_rated_voltage( uint16_t voltage ) {
   float RatedVoltage;
   uint16_t SampleTime = 300;
   uint16_t frequency = 175;

   RatedVoltage = ( (float) voltage ) * sqrt( 1 - ( ( 4 * SampleTime + 300 ) * 0.000001 ) * frequency );
   RatedVoltage = ( RatedVoltage * 255 ) / 5300;

   return RatedVoltage;
}

The function above is just a simplified version showing the calculation and the SampleTime and frequency variables are set to their defaults values here. The voltage argument is the actuator's rated voltage in millivolt.

EDIT: Even though SampleTime and frequency have fixed values in the function above, their values will be determined by reading the relevant registers in the final implementation. SampleTime may have one of the following values: 150, 200, 250, 300 and the frequency will depend on the manufacturers specifications for the actuator.

It was easy to overcome the floating point issue on the other calculations by simply scaling up the values by 1000 (fixed point arithmetic):

  ODClamp = ( Vpeak * 255) / 5.6 /* Vpeak in volts */

TO:

  ODClamp = ( Vpeak * 255) / 5600 /* Vpeak in millivolts */

How can I do the calculation in question without having to use floating point?

As I said in my comment, it is all about computing an approximation of
sqrt(1-x). Assuming the typical resonance frequency is between 175
and 235 Hz, then we have

  (4 × 150 µs + 300 µs) 175 Hz ≤ x ≤ (4 × 300 µs + 300 µs) 235 Hz

i.e.

  0.1575 ≤ x ≤ 0.3525

This range is small enough to try a simple polynomial approximation. A
linear approximation is just a bit too crude for 8 bit resolution.
Playing with quadratic polynomials, I found this approximation which is
good to 3.1e-5 in the relevant range:

  √(1−x) ≈ 0.9983795 − x (0.480515 + x 0.1955)

This can be easily implemented in fixed point by scaling everything by a
factor 216 = 65536. One has to take care that any
product of two such fixed point numbers must be computed in
32 bits, and the result subsequently divided by 65536. Which gives
the following implementation:

/*
 * Compute a fixed point approximation of f(x) = sqrt(1-x).
 * Valid for x in [.1575, .3525].
 * Argument and result scaled by 2^16.
 */
uint16_t f(uint16_t x)
{
    return 65430 - x * (31491 + x * 12812UL / 65536) / 65536;
}


How to increase life of EEPROM? I want to store a few (8 as of now) IR codes into my Board's EEPROM.
It would be great if someone could suggest a few tips to maximize the lifetime.

The IR codes in my sketch are saved in array of unsigned longs.

I know that the count of times that I will be writing to EEPROM will << 100,000 times, but still would like to optimize my sketch. + would help in future projects

The other answer mentioned some general ideas; here are a couple of more-specific notes.

• You can direct your writes of single bytes through a routine that reads the EEPROM cell before writing to it, and if its value isn't changing, doesn't write.

• For load-leveling, you can divide the EEPROM address space into k buckets, where k =⌊E/(n+1)⌋, with n = data array size and E = EEPROM size.  Initialize a directory, an array of m bytes all set to k, with m = E-n·k.  When your device starts up, it reads through the directory until it finds current entry, a byte not equal to k. [If all directory entries equal k, initialize the first to 0, and go on from there.]  If the current directory entry contains j, then bucket j contains current data.  When you need to write new data, you store j+1 into the current directory entry; if that makes it equal to k, initialize the next directory entry to 0, and go on from there.  Note that directory bytes get about the same amount of wear as bucket bytes because 2·k > m ≥ k.


Powering Arduino and transistors with one power supply > 12V So say you want to use transistors with your Arduino Nano to power components, which require greater than 12V. If your power supply is more than 12V, is there a way to safely use the same power supply to power the Arduino?

The voltage regulator (on the Vin pin) is supposed to be provided with 12V at max, since it is not cooled (it is a linear regulator, that dissipates the excess voltage as heat). If you have significantly more, you should at best buy a little switching regulator, to directly get a regulated 5V to feed to the 5V pin of the Arduino (that's what I suggest). Be sure to use a regulator, that can provide the needed current (which also depends on what else you provide over the Arduino).

If you really don't want to use an extra regulator and you don't have much more than 12V (maybe like 15V), you might get away by cooling the voltage regulator on the Arduino. The voltage regulator on a genuine Arduino will go into emergency shutdown, if it overheats, but it will not be damaged easily. Here you could try a bit. But be careful to not stress it too much. The clones from china often have different/cheaper regulators, that will mostly be fried if you overheat them. But they are very cheap.


Will this sensor work with arduino? I'm building an electronic gate. I'm needing a photoelectric sensor to detect cars. This one in the link looks decent. it runs on 12v so I will need to power it separately from the arduino. But does this mean it also puts 12v back to the signal wire? Will that work with ardunio without burning the circuit? How many V can i send into an arduino pin?

thanks

photo electric sensor

The sensor you specified states:

Output: SPDT Relay Output

If accurate, it may be inferred that the output is simply 3 contacts where one is normally open and the other is normally closed and the 3rd is the common.  If true then you can treat the output as if it were an ordinary Single Poll Double Throw (SPDT) switch.  Note, with regard to processors, an ordinary switch may need to de-bounced.  This depends on how the state of the switch is used.