How can I make YX5300 MP3 player play song in a loop? I am doing a Christmas project and I have an ultrasonic sensor that detects if a person is In front of it. I want that if someone is in front of it, it lights up LEDs, which it does, and it also has to play a Christmas song, which it doesn't. I tried to make it play the Christmas song but nothing happens. Also the LEDs are only blinking when you put ur hand in front of the ultrasonic sensor. I want it to light up the lEDs for the same amount of time the song is, 28 seconds, and than the lEDS should stop and the ultrasonic sensor should wait for another person and it repeats. I am new to this so please be specific in your reccomendations.
Here is my code:

#define trigPin 10
#define echoPin 13
#include <SoftwareSerial.h>
#define ARDUINO_RX 7//should connect to TX of the Serial MP3 Player module
#define ARDUINO_TX 6//connect to RX of the module
SoftwareSerial mySerial(ARDUINO_RX, ARDUINO_TX);
static int8_t Send_buf[8] = {0} ;
#define CMD_SEL_DEV 0X09
#define DEV_TF 0X02
#define CMD_PLAY_W_VOL 0X22
#define CMD_PLAY 0X0D
#define CMD_PAUSE 0X0E
#define CMD_PREVIOUS 0X02
#define CMD_NEXT 0X01

int red1 = 5;
int red2 = 4;
int green1 = 3;
int green2 = 2;

long lCnt = 0;
unsigned long lStart;

void setup(){
  Serial.begin (9600);
  mySerial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(red1,OUTPUT);
  pinMode(red2,OUTPUT);
  pinMode(green1,OUTPUT);
  pinMode(green2,OUTPUT);
  delay(500);//Wait chip initialization is complete
  sendCommand(CMD_SEL_DEV, DEV_TF);//select the TF card
  delay(200);//wait for 200ms

}

void loop(){
  float duration, distance;
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH);
  distance = (duration / 2) * 0.0344;

  if(distance > 0 && distance <=60){

    digitalWrite(red1,HIGH);
    delay(50);
    digitalWrite(red2,HIGH);
    digitalWrite(green1,HIGH);
    delay(50);
    digitalWrite(red1,LOW);
    delay(50);
    digitalWrite(red2,LOW);
    digitalWrite(green2,HIGH);
    delay(50);
    digitalWrite(green1,LOW);
    digitalWrite(green2,LOW);
    delay(50);
    sendCommand(CMD_PLAY_W_VOL, 0X1E01);
  }

}

void sendCommand(int8_t command, int16_t dat)
{
  delay(20);
  Send_buf[0] = 0x7e; //starting byte
  Send_buf[1] = 0xff; //version
  Send_buf[2] = 0x06; //the number of bytes of the command without starting byte and ending byte
  Send_buf[3] = command; //
  Send_buf[4] = 0x00;//0x00 = no feedback, 0x01 = feedback
  Send_buf[5] = (int8_t)(dat >> 8);//datah
  Send_buf[6] = (int8_t)(dat); //datal
  Send_buf[7] = 0xef; //ending byte
  for(uint8_t i=0; i<8; i++)//
  {
    mySerial.write(Send_buf[i]) ;
  }
}

Thanks

I think you want to use the command [Single cycle play] which is 7E FF 06 08 00 00 01 EF (the 00 01 towards the end is the song number to play).

All the commands are detailed in the manual.


Does Adafruit PowerBoost 1000 Charger support data transfer? As the title says - Does Adafruit PowerBoost 1000 Charger support data transfer?
I mean that if I connect USB on one side to PC and Arduino on other side - can I still program it and get serial monitor communication?
Are the data lines connected??

No it doesn't.

As you can see from the schematic the incoming data lines aren't connected, and the outgoing are wired through appropriate resistors to set the current availability.


External power supply? I have a project where I'm looking to power 120 RGB LEDs in a strip (WS2812B).

Obviously an Arduino Micro cannot supply this amount of current so I'm looking to use an external 5V/4A switching power supply (wall-wart) to power the LED's as well as the Arduino.

My question is, can I just split the power from the wall-wart providing 5v_reg directly to the 5V pin on the Arduino Micro and 5v_reg to the LEDs Vss?

It it necessary to use extra bypass capacitors in this case?

My question is, can I just split the power from the wall-wart providing 5v_reg directly to the 5V pin on the Arduino Micro and 5v_reg to the LEDs Vss?

Yes. As long as it is a clean regulated 5V supply.

  It it necessary to use extra bypass capacitors in this case?

No.


memory usage "dos and don'ts" Though I've written C/C++ code for a long time, the unseen limitations on how memory was consumed on various MCU and SOC programming platforms have often tripped me up. As I'm about to build up code for my first large project for my NANO boards, which will likely use a fair amount of its resources, I'd like to be better prepared for any surprising and unexpected "gotchas" to look out for.

For example, on another SOC I recently worked on extensively (The Pololu.com wixel) I was very surprised to learn that function/method arguments and auto variables, which I'd normally expect to be stack allocated and recovered when a function returns were in fact permanently allocated for the life of the program! Wow! so on that platform, where I'd normally hate to "overwork" variables or reuse variables after their names no longer make sense, I had to adjust my coding to what I'd normally consider BAD for readability. Not to mention realizing that simple loop variables were better off allocated globally. Yecch!

Can those of you who have run into such unexpected coding issues in the Arduino environment share some "special" guidelines about things like this?

As you have noticed yourself, this can be somewhat platform-dependent.
Since you are working on a Nano, my answer will be for the AVR
architecture, when compiled with gcc, the avr-libc, and the Arduino core
library.

First, let me reassure you: this weird behavior you saw of the Wixel
doesn't happen on this platform. Local variables get allocated mostly in
CPU registers, then on the stack.

Now, the first general rule may sound obvious: think twice about what
your program really needs to remember. Also, use each time the
smallest possible data type. The C99 types int8_t, uint16_t and co.
are useful for this.

Another rule you will often hear on this platform: avoid dynamic
allocation, i.e. malloc() and new, as quite often you cannot afford
heap fragmentation. Avoid also the String class, as it relies on
dynamic allocation. Prefer when possible static allocation, or stack
allocation for small things.

Don't forget to use const for constants: with this qualifier the
compiler can often optimize the constants out as immediate operands. For
arrays of constants, use PROGMEM. Yes, it's not comfortable
to use, but it can save you lots of RAM. The F() macro for printing
constant messages is a special case of PROGMEM.

Lastly, be very careful with recursion.


Bitwise write to analog PIN I am just starting to learn bitwise operands and here is my question. To do this:
pinMode (13, OUTPUT);
digitalWrite (13, HIGH);

bitwise I can do like this:
DDRB |= B00100000;   //set PIN13 as OUTPUT
PORTB |= B00100000;  //set PIN13 HIGH

but how I can do this:
analogWrite(9, 200);

I know how to convert DEC numbers to BIN, but how to send this number to PWM PIN? I cannot find any good example in web..
Thank you!

Note, you haven't specified, which Arduino you are using. I'm assuming a Atmega328p based Arduino (Uno, Nano, Mini) here, though the principle works with every AVR microcontroller, that has this hardware).
With analogWrite() are are not sending data bitwise out of a pin. It configures the hardware Timer for setting that pin at a specific frequency and with a specific duty cycle. So analogWrite() actives a totally different piece of hardware inside the microcontroller.
To do this without the Arduino function analogWrite(), you first need to decide, which way to go:

You can generate an interrupt through the hardware Timer and then set the wanted pin by software inside the ISR (which gives you free choice of the pin, but also introduces some jitter in the signal)
or you can let the hardware Timer itself toggle the pin, which does not involve any software for running (that means you can only use one of the 2 pins, that are associated with the corresponding Timer, but you will get a much more stable signal)

There are lots of tutorials on the web on how to do that. A search for "arduino timer register pwm" gave me some promising results, for example this one, where they explain, how to get PWM with the Timer1 registers and a free to choose frequency. (That is a 3 part series, one part for each Timer. Part 1 for Timer 0 is here, though you might want to keep Timer 0 as it is, so that functions like delay() and millis() still work as normal). There are also many such questions on this site, for example this one.
Another very important source for anything hardware related is the datasheet of the corresponding microcontroller. For the Uno, Nano or Mini that is the Atmega328p, which datasheet can be found on the microchip site here (or when googling for the microcontroller name)


How to connect ESP8266 12e directly to Arduino Uno (without shields) I have an ESP8266 12E module and I'm trying to connect it to arduino, without any shields or whatsoever. I've looked everywhere but all I can find is about ESP-01 or with a NodeMCU. I'd like to do the bridge manually, but I don't know which pins I should ground and which pins I should power.

This is my current setup:

And the following sketch:

#include <SoftwareSerial.h>

//RX pin 2, TX pin 3
SoftwareSerial esp8266(2, 3);

#define DEBUG true

void setup() {
  Serial.begin(9600);
  esp8266.begin(115200);
  sendData("AT\r\n", 2000, DEBUG);
  delay(1000);
  Serial.println("Firmware version:");
  delay(3000);
  sendData("AT+GMR\r\n", 2000, DEBUG);
  Serial.println("** End **");
}

void loop() {}

String sendData(String command, const int timeout, boolean debug) {
  String response = "";
  esp8266.print(command);
  long int time = millis();
  while ( (time + timeout) > millis())
  {
    while (esp8266.available())
    {
      // The esp has data so display its output to the serial window
      char c = esp8266.read(); // read the next character.
      response += c;
    }
  }
  if (debug)
  {
    Serial.print(response);
  }
  return response;
}

When run, I get the following output:

Firmware version:
** End **

On the module, the led flashes when I power it up, but after that it remains off. I've already tested the voltage regulator with ReadAnalogVoltage, and the output was 3.33v, so it is working.

Make sure to specify as SoftwareSerial's Rx pin, the pin# connected to the ESP's Tx pin. They have to be crossed. (I just fumbled that myself, a couple of hours ago ):

It is the ESP's Rx pin that needs the voltage divider.

Also pullup the ESP's reset pin.

Update:

ESP-01 and ESP-12 modules use the same ESP8266 chip. The differences are in the number of pins brought out from the chip and made available on the board. Other differences include the firmware interpreters installed on them before shipment: "NodeMCU" is one. ESP-01 is usually shipped with the AT+ command interpreter unless it specified otherwise; I would expect the same for the others. Bottom line is they are connected pretty much alike. Interacting with them serially from an Arduino (or other device) then depends on the installed firmware, including whether you've installed your own. So far, I've used all of mine as WiFi modules using the AT+ interpreter they came with.

  How can I pullup the reset pin? Also do I need to pullup it just for
  initial setup (changing baud rate and such) or should it be pulled up
  at all times?

I use a 10K-Ohm resistor to +3.3v as a pullup. You need it pulled up anytime you are not trying to force a hardware reset; grounding it resets the chip. I have never used a reset button on my ESPs. I just leave them pulled up. If you want one, it should short the reset pin to ground.

Update 2 (wiring):

You've powered the ESP with 3v but your pullups are taken to the Arduino's 3.3v supply. Most chips have a slim tolerance for signal levels above their supply voltage. I'd suggest driving the entire ESP from your 3v battery - power & both pullups.

I don't know the ESP-12E's pinouts to check them; I'm sure you have, and you might want to label the diagram so someone else can look over it too.

Then there's whatever "chicken dance" is needed on the reset and the GPIO line that needs to get toggled to start an upload. I don't know that sequence, but I think you need a grounding buttons on on each one to be able to sequence them.


Android as sensor hub Generally an Android phone has all the basic sensors like accelerometer, light, proximity, magneto, gyro, sometimes pressure etc. So is there a way to use Android's built-in sensors with an Arduino board (Uno) instead of buying the different sensor shields.

There's such a solution, called 1Sheeld. It's pretty expensive though.


Controlling Relay Using Serial Monitor I tried to make a program that can control a 4 channel relay (with LEDs as indicators) with a serial monitor. First time I tried to program it using a char command to make it turn on only, it worked. Then I tried to make it off only, it also worked, but when I tried to combine them, to control it to On or Off in the same program, it didn't work.

this is my code

#define CH1 2
 #define CH2 3
 #define CH3 4
 #define CH4 5
  void setup(){
 Serial.begin(9600);

pinMode(CH1, OUTPUT);
pinMode(CH2, OUTPUT);
pinMode(CH3, OUTPUT);
pinMode(CH4, OUTPUT);
digitalWrite(CH1,HIGH);
digitalWrite(CH2,HIGH);
digitalWrite(CH3,HIGH);
digitalWrite(CH4,HIGH);
 }

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

char ser = Serial.read();

 switch(ser){
 case 'on1':

 onPin1();

 break;

 case 'on2':

 onPin2();

 break;

 case'on3':

 onPin3();

 break;

 case 'on4':

 onPin4();

 break;

 case 'off1':

 offPin1();

 break;

 case 'off2':

 offPin2();

 break;

  case'off3':

 offPin3();

 break;

  case 'off4':

 offPin4();

 break;

   }

 }
 }

 void onPin1(){
    digitalWrite(CH1, LOW);
 }
  void onPin2(){
   digitalWrite(CH2, LOW);
 }
   void onPin3(){
   digitalWrite(CH3, LOW);
 }
  void onPin4(){
   digitalWrite(CH4, LOW);
 }

  void offPin1(){
   digitalWrite(CH1, HIGH);
 }
   void offPin2(){
   digitalWrite(CH2, HIGH);
 }
   void offPin3(){
   digitalWrite(CH3, HIGH);
 }
   void offPin4(){
   digitalWrite(CH4, HIGH);
 }

with that code, I got "duplicate value", maybe because the pin is double-called. But when I tried to make it in separate swicth case condition, no error but couldn't respond to the command char

This is C++, so the single quotes are used for character literals. If you want string literal, you have to use double quotes. However, string literals can't be used in switch.

And you can't definitely use it like that if you are reading only one character.

However you can use single characters for this:

#define CH1 2
#define CH2 3
#define CH3 4
#define CH4 5

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

  pinMode(CH1, OUTPUT);
  pinMode(CH2, OUTPUT);
  pinMode(CH3, OUTPUT);
  pinMode(CH4, OUTPUT);
  digitalWrite(CH1,HIGH);
  digitalWrite(CH2,HIGH);
  digitalWrite(CH3,HIGH);
  digitalWrite(CH4,HIGH);
}

void loop (){
  if (Serial.available()) {
    char ser = Serial.read();
    switch(ser){
      case '1':  onPin(CH1); break;
      case '2':  onPin(CH2); break;
      case '3':  onPin(CH3); break;
      case '4':  onPin(CH4); break;
      case '5': offPin(CH1); break;
      case '6': offPin(CH2); break;
      case '7': offPin(CH3); break;
      case '8': offPin(CH4); break;
    }
  }
}

void onPin(int8_t pin) {
  digitalWrite(pin, LOW);
}

void offPin(int8_t pin) {
  digitalWrite(pin, HIGH);
}

Or you can toggle the relay states.

Test strings as commands are little bit harder to use as you have to read whole command (or use state machine). Following example is little bit unnecessary hard but it's working...

constexpr uint8_t     channels = 4;
constexpr uint8_t ch[channels] = { 2, 3, 4, 5};

template <uint8_t pin, uint8_t val> void setChan() {
  digitalWrite(pin,val);

  Serial.print("setChan: "); Serial.print(pin);  Serial.print(' ');  Serial.println(val);
}

using action_t = void(*)(void);

action_t  on_actions[channels] = {
  &setChan<ch[0],LOW>,
  &setChan<ch[1],LOW>,
  &setChan<ch[2],LOW>,
  &setChan<ch[3],LOW>
};

action_t off_actions[channels] = {
  &setChan<ch[0],HIGH>,
  &setChan<ch[1],HIGH>,
  &setChan<ch[2],HIGH>,
  &setChan<ch[3],HIGH>
};

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

  for (auto pin : ch) {
    pinMode(pin, OUTPUT);
  }
}

String command = "";
action_t action = nullptr;

void loop() {
  if (action != nullptr) {
    action();
    action = nullptr;
  }
}

void serialEvent() {
  if (Serial.available() > 0) {
    char inChar = (char)Serial.read();
    if ((inChar == '\r' || inChar == '\n')) {
      if (command.length() > 0) {
        Serial.print(command);
        if (command.startsWith("on")) {
          uint8_t channel = command.substring(2).toInt()-1;
          if (channel < channels) {
            action = on_actions[channel];
          }
          Serial.print(" On="); Serial.print(channel+1);
        } else if (command.startsWith("off")) {
          uint8_t channel = command.substring(3).toInt()-1;
          if (channel < channels) {
            action = off_actions[channel];
          }
          Serial.print(" Off="); Serial.print(channel+1);
        }
        Serial.println();
        command = "";
      }
    } else {
      command += inChar;
    }
  }
}


Arduino unstable analog reading when using power supply As soon as I unplug my Arduino from USB and only use the VIN pin with my 9 V power supply, the analog readings from my Arduino start to get unstable, which means the value fluctuates much more than with USB connected. When I reconnect USB again, the readings are stable again.

I'm trying to build a load scale using a load cell, an INA125P and the Arduino, using this setup here: Instrument Amplifier Calibration.

Therefore I need stable readings. For example, I wrote some code to convert the analogRead() value to grams. While USB and VIN (9 V) connected, I get a stable reading of about 8.3 to 8.7 grams when I put a weight of 8.5 grams on the scale. As soon as I unplug USB, the LCD shows values from 7.8 grams up to 9 grams.

Unfortunately, I don't have any other power supply which I could use to test. I've already tried to use a 9 V battery with the same results. Do I maybe need some additional de-coupling capacitors?

I solved a similar issue by adding a pin from supply to AREF and it's now stable. This fixed a frustrating pH meter issue on my Mega that every time I plugged USB in it would be right, but as soon as I dropped the USB cable it changed the readings.


Stopping the program after 1 second I am a Beginner in Arduino Programming.
I am working on a project where I control A DC motor with IR sensor and arduino.

Until here it is fine. But I want the Motor to stop after one second even though the IR sensor detects the Obstacle

Here's My Program

Pin 2- IR Sensor
Pin 4,5,6- Motor

enter code here
//Included Libraries
#include <motor.h>

//MACROS are defined here
Motor Motor1(4, 5, 6);

void setup() {
    //put your setup code here, to run once:

    pinMode(2, INPUT);

}

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

    if(digitalRead(2)) {
        Motor1.moveMotor(2.55*0);
    }
    else {
        Motor1.moveMotor(2.55*100);
    }
}

Can anyone help out in this Program. I Just want the Motor to stop after one second.
Thank you in advance!

You need to use read the time (millis()) when you start the motor and read it frequently while the motor is running to know when to stop it. You also need to keep track of the sensor, and don't start the motor again until after you've seen the sensor turn off (detect no obstacle). Here is an outline of the logic in psuedo-code; turn this into a detailed loop() function in C++:

if the motor is ON {
  if (millis() - motorStartMillis) > 1000 {
  stop the motor;
}
else if sensor is ON {
  if the sensor was OFF {
    start the motor;
    motorStartMillis = millis();
    sensorWasOn = true;
  }
}
else {      // sensor must be off
  sensorWasOn = false;
}


Arduino Power project question? I saw a project on the Internet (the one in the photo), and I wonder, would it be a problem for me to connect the Vin and GND of the Arduino to the same place where the Servo Motors are being powered? (to power the Arduino together without having to connect it to another source or USB)

And if instead of the batteries I use one of those Breadboard Power Module (photo two) and connect a 12V / 1A power supply in it, would it have problem ? (connect the 4 Servo + the Arduino in it)

Please provide more information about the power module, or at least a link to it.

But you could supply 12v directly to the Arduino's DC-In barrel-jack. It's not ideal; the Arduino's regulator is likely to get warm, but it would work. This module looks like it regulates its input down to 5v or 3.3v (jumper-selectable). If that is so, then its 5v output would be just right for the Arduino's 5v-In pin. Just make sure your the motors and the Arduino are each directly connected to whatever supply(s) you use. What you need to avoid is trying to power the motors through the Arduino. Your first photo has it right.

Update:

After reading about the supply (using your link), I see that its output is limited to 700ma. Some of that will have to go to power the Arduino (you can use the power supply's USB port for that), leaving a little less for the motors. That will be marginal for one motor and insufficient if the motor is stalled or moving more than a trivial load. It won't be sufficient for more than one motor at a time without scheduling them to prevent simultaneous starts.

You haven't described your motors, so I looked up the Tower-Pro SG-90 hobby servos, one of the simplest and least expensive of the hobby servos. I found a very similar looking one (maybe a clone?) described as being similar to the Tower-Pro, the only one for which I could find current specs. At 5 volts, it draws 100mA with no load and 700ma when stalled. With a stalled motor, the output voltage would likely drop, possibly stopping and resetting the Arduino.

So bottom line is, this supply is marginal, even for one hobby servo in a mechanism that won't stall it. With a larger motor or a heavier load, I don't think it will do the job.


What pins should I use when blinking AtTiny13 with arduino IDE? I'm trying to program AtTiny13 using Arduino IDE. I have connected the atTiny to my PC using USBasp programer.

I want to write a simple blink application to test whether it works or not. Which pins should I blink?

You'll need an Arduino library that supports that chip, to make it appear in the Tools > Board list.  The library docs will tell you which pins then correspond to which Arduino digital I/Os. From that you can decide which pin to attach an LED to (with resistor) and how to edit the blink sketch.

Example: http://www.instructables.com/id/Pimp-Your-Chocolates-with-Arduino-IDE-and-ATtiny13/step2/Program-the-ATtiny13/


How much current and voltage has my resistor + LED I have a very simple circuit: 5v -> LED (5mm, forward voltage of 2 V and max. current of 20mA) -> 1k ohm resistor -> GND.

I want to know how much current is flowing in my circuit. I am using this formula:

U = R x I

Since U = 5, and R = 1000 the current is (according to the formula): 5/1000 = 0.005A.

So far so good. The problem is when I try to check the voltage drop over the resistor and the LED. For calculating the voltage drop in the resistor I would use the same formula where I is my current (0.005A) and R is the resistor 1k ohm. The result is: 5 V.

Something very weird is happening here cause the voltage drop around my resistor should not be 5 V cause I know there must be another voltage drop around the LED. If 5V is in the resistor it would mean that 0v is around the LED (and it should not light up but it does).

Thank you helping me with this basic calculus.

The problem is that if you're trying to measure the current directly, you're going to get the wrong answer. Whether it's due to burden voltage or the (in)accuracy of the meter, it's a hopeless situation. The 0.005A your meter is showing is actually closer to 3mA in reality, but your meter can't distinguish between the two well enough.

If you need to measure current this small then the only way to do so accurately is to use a very low-value shunt resistor and an amplifier. This is the method the µCurrent uses, and it's essentially the defacto gold standard for measuring current in small circuits.


error: 'CLASS' does not name a type only when creating object inside another object I'm trying to use Adafruit's LED Backpack library within a custom class. When I use the Adafruit library directly within a sketch, it compiles fine. When I use an example sketch provided with the library, it compiles fine. However when I create an instance of my custom class with the Adafruit object within it, I get the following error:

  In file included from sketch_feb18a.ino:6:
  /Users/lawnmowerlatte/Documents/Arduino/libraries/Bargraph/bargraph.h:18: error: 'Adafruit_24bargraph' does not name a type

All the reasons I've seen for this error stem from the library being missing or otherwise incorrectly installed. However, since I can use it directly, I think something else must be wrong.

Working

#include <Adafruit_LEDBackpack.h>
#include <Adafruit_GFX.h>
Adafruit_24bargraph bar = Adafruit_24bargraph();

void setup() { }
void loop() { }

Not Working

#include <bargraph.h>
Bargraph bargraph = Bargraph("Test", "api", 0);

void setup() { }
void loop() { }

bargraph.h

#ifndef Bargraph_h
#define Bargraph_h

#include <Adafruit_GFX.h>
#include <Adafruit_LEDBackpack.h>

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

class Bargraph {
  public :
    String name;
    String api;
    Adafruit_24bargraph bar;

    Bargraph(String _name, String _api, int _device,
        String _type="Default");

    void set(String _value);
    void setMax(String _max);
    void update();
    void print();

  private :
    int display[24];

    long max;
    long value;
    int device;
    int size;
    String type;

    void format();
    void write();
};

#endif

bargraph.cpp

#define OFF 0
#define RED 1
#define YELLOW 2
#define GREEN 3

#include <bargraph.h>

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

Bargraph::Bargraph(String _name, String _api, int _device, String _type) : bar() {
    name        = _name;
    api         = _api;
    max         = _max.toLong();
    device      = _device;
    type        = _type;
    value       = 0;

    for (int i=0; i<24; i++) {
        display[i] = OFF;
    }

    bar.begin(0x70+device);
}

**Methods Omitted for Brevity**

Can anyone explain what's going on here? I'm pretty certain my class syntax is correct as I have other object-in-object relationships working. I can post code to GitHub if anyone would like to see more context.

I think these lines still need to be in your main sketch file (in addition to being in your custom class file):

#include <Adafruit_LEDBackpack.h>
#include <Adafruit_GFX.h>

If I remember the Arduino IDE quirks correctly, it uses the #include directives in the main sketch file to determine which libraries to actually link. It's one of those annoying features that was intended to be beginner-friendly but sometimes just makes things more confusing.


Unable to upload sketches after little oopsie (reversed input polarity) So playing around with an arduino uno, I was powering it with a 12volt battery (putting power between Vin and Gnd) and I fat fingered the battery terminals, putting them in reverse (oops)

I see smoke coming out of the 5 volt regulator (the little 3 pin IC). I immediately pull out the battery thinking I've just bricked this thing.

After a minute or two I plug the battery in again (taking care to plug it in straight this time) and to my surprise it works, works pretty well. The last sketch I uploaded works perfectly fine.

I've been using the same thing for an hour or so. But now I wanted to upload another sketch and it doesn't upload. The voltages seem to be fine, I'm putting in 11.8 volts on Vin, there is 5.12 volts on 5v and 3.34 volts on 3v3

I thought there may be some problem with the voltage regulator, so I tried connecting it directly to the USB (powering it from USB) but still the same thing.

I find it intriguing that it works perfectly for everything except uploading new sketches, especially after such an explosive oopsie. Can any of you chaps deduce what the problem might be? I have a USBasp module so I can reburn the bootloader, but I doubt that's the problem.

The atmega328 that runs the sketch is fine, but the communication is broken somehow.  See the steps in https://arduino.stackexchange.com/a/13293/6628


esp8266 deep sleep timer slightly inaccurate? I'm making a door open timer using a hall sensor and have a wemos d1 mini that uses a deep sleep to sleep for 1 minute after checking the hall sensor state and printing the value on the serial port. I'm using the Arduino IDE to monitor the serial output and have the Show timestamp option enabled so that I could time how long the device is running after it resets.  However, I'm getting output like this:

08:03:26.286 -> ^H⸮ȸ$RKx⸮⸮x⸮I⸮⸮696
08:04:25.454 -> HEA⸮⸮⸮d⸮⸮⸮⸮⸮⸮⸮696
08:05:24.681 -> ⸮⸮NI⸮ hlE⸮0⸮/⸮696
08:06:23.915 -> ⸮DP⸮V⸮l⸮X⸮X⸮H⸮⸮694
08:07:23.178 -> ⸮A⸮K`E⸮M⸮⸮xxE⸮696
08:08:22.406 -> ⸮HlX⸮K⸮I|⸮⸮xE⸮693
08:09:21.703 -> ⸮⸮NI⸮ hlE⸮0⸮⸮E⸮694
08:10:20.978 -> 8H⸮JcD⸮M⸮⸮xxE⸮695
08:11:20.306 -> ⸮⸮NI⸮AhlE⸮ Op⸮⸮696
08:12:19.573 -> ⸮⸮NI⸮ hlE⸮0⸮/⸮539
08:13:18.897 -> ⸮⸮OI⸮AhlE⸮⸮O⸮⸮538
08:14:18.196 -> HEA⸮⸮⸮d⸮⸮⸮⸮I⸮⸮539
08:15:17.561 -> ⸮dG⸮⸮⸮hLJ⸮@h⸮⸮(⸮539

The garbage output isn't what I'm asking about, it's the timestamps being created by the arduino ide. Since I sleep for 60,000,000 microseconds, I would assume that the second value of the minute would be slightly more each time. But as shown above, it becomes slightly less every time, as if it takes less than a minute. So what I'm wondering is if the sleep timer on these devices is not accurate enough to count on this or something else I should be considering like an inaccuracy in the IDE?  I only wanted to measure the uptime so that I could consider it for battery drain considerations, I don't really need a millisecond accurate timer for the functionality of the device.

This (now 3 year old) github / esp8266 thread suggests using an external RTC if time tracking is of importance.  It also points at a dead NodeMCU document link.  That document appears to have move here.  This document describes the lengths taken to provide a better account for time passage during sleep.  Which, apparently, includes guessing at the sleeping chip's temperature:

  Time keeping on the ESP8266 is technically quite challenging. Despite
  being named RTC, the RTC is not really a Real Time Clock in the normal
  sense of the word. While it does keep a counter ticking while the
  module is sleeping, the accuracy with which it does so is highly
  dependent on the temperature of the chip. Said temperature changes
  significantly between when the chip is running and when it is
  sleeping, meaning that any calibration performed while the chip is
  active becomes useless mere moments after the chip has gone to sleep.
  As such, calibration values need to be deduced across sleep cycles in
  order to enable accurate time keeping. This is one of the things this
  module does.


Neopixel Painter - Need to change few lines. Not sure where to start My name is Maria and I'm learning programing in high school.
I'm working on a birthday present for my mom, want to make a mood light. Using light painter, a neopixel strip, and an arduino.

https://github.com/adafruit/NeoPixel_Painter

I found the part, which reads the bmp line by line a very innovative way to make custom animations.

But some tweaks are needed. (I've tried to make them, believe me, oh I've tried.) So, i was wondering if i can ask someone a favor and teach me how to modify the code (like, comment on parts that been changed.)

Basically, what I want to be changed is, to loop the current bmp until 'next' button is pressed, rather than hold the trigger. Also, I'm not sure if the code try to save power, but it can be disabled since it will run from a power supply.

Here is the part that makes you hold the trigger button (i think)

  for(;;) {
    while(!(TIFR1 & _BV(TOV1)));               // Wait for Timer1 overflow
    TIFR1 |= _BV(TOV1);                        // Clear overflow bit

    show();                                    // Display current line
    if(stopFlag) break;                        // Break when done

    if(++block >= nBlocks) {                   // Past last block?
      if(digitalRead(TRIGGER) == HIGH) {       // Trigger released?
        memset(sdBuf, 0, N_LEDS * 3);          // LEDs off on next pass
        stopFlag = true;                       // Stop playback on next pass
        continue;
      }                                        // Else trigger still held
      block = 0;                               // Loop back to start
    }
    card.readBlock(block + firstBlock, sdBuf); // Load next pixel row
  }

And the complete code: https://github.com/adafruit/NeoPixel_Painter/blob/master/NeoPixel_Painter.ino

Anyway, Since I'm talking to an experts right now, I have this idea to remote control the code! from  another arduino!

My, probably retarded idea is, to run an IR remote code on a second arduion, than when it receives a signal, send a simulated button press to the first ardu playing the bmp! Is that even possible? Just wondering.

Cheers
Maria

I think you need something like this.

  for(;;) {
    while(!(TIFR1 & _BV(TOV1)));               // Wait for Timer1 overflow
    TIFR1 |= _BV(TOV1);                        // Clear overflow bit

    show();                                    // Display current line

    if(++block >= nBlocks) {                   // Past last block?
      block = 0;                               // Loop back to start
    }

    if(digitalRead(NEXT_PIN_OR_SOMETHING) == LOW) {       // Next button pressed
      break; // Break out of for-loop
    }

    card.readBlock(block + firstBlock, sdBuf); // Load next pixel row
  }


How to use output from Arduino in C++ code? I am a complete novice in Arduino and moderately experienced with the language C++. What if I want to use the output from the serial monitor in C++ code in real time?

Also how can I write to the serial monitor. Which libraries are available for this? Also please give me links to sites where I can learn more about this topic. I am using Arduino Uno.

Unfortunately, C++ doesn't have native support for serial I/O.

You could use the Windows API directly if you're feeling adventurous. It can be a little complicated to get to grips with, but not insurmountable. You can get basic information about it here. There's an example of using it with Arduino here.

As an alternative, you could use a 3rd party library. This one looks good, although I haven't actually used it myself.


basic_insert with WAMP server doesn't connect with MySQL database I'm trying to establish a connection with a MySQL database on a local server wirelessly using the following script:

The wireless connection with my router is successful but then connection with database results in

I'm using a WeMos D1 mini ESP8266, Windows 10, WAMP64, MySQL 5.7.14.

I get ping responses from MySQL at 127.0.0.1, and my host computer and also the ESP8266.  I've disabled my Windows Firewall to test it temporarily.  After the wifi connects with the ESP8266 and confirms the correct WiFi.localIP, 'Connection failed' error with additional text below.

I can manually enter data into the test_arduino table so I think it's a connection issue with the database server. Maybe something to do with my router's handling of of Port 80.

I am able to send sensor data to remote sites such as ThingSpeak.

Any help would be appreciated.

// Created by: Dr. Charles A. Bell

#include "ESP8266WiFi.h"
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>

IPAddress server_addr(192,168,0,10);  // IP of the MySQL *server* here
char user[] = "root";              // MySQL user login username
char password[] = "PASSWORD";        // MySQL user login password

const char* SSID = "MYSSID";         // Your network SSID
const char* PASS = "MYPASSWORD";

// Sample query
char INSERT_SQL[] = "INSERT INTO test_arduino.hello_arduino (message) VALUES ('Hello, Arduino!')";

WiFiClient client;
MySQL_Connection conn((Client *)&client);

void setup() {
  Serial.begin(115200);
  while (!Serial); // wait for serial port to connect

  Serial.print("Connecting to "+*SSID);
  WiFi.begin(SSID, PASS);
  Serial.println("going into wl connect");

  while (WiFi.status() != WL_CONNECTED) //not connected,  ...waiting to connect
    {
      delay(1000);
      Serial.print(".");
    }

  Serial.println("wl connected");
  Serial.println("");
  Serial.println("Credentials accepted! Connected to wifi\n ");
  Serial.println(WiFi.localIP());
  Serial.println("");

  if (conn.connect(server_addr, 3306, user, password)) {
    delay(1000);
  }
  else
    Serial.println("Connection failed.");
}

void loop() {
  delay(2000);

  Serial.println("Recording data.");

  // Initiate the query class instance
  MySQL_Cursor *cur_mem = new MySQL_Cursor(&conn);
  // Execute the query
  cur_mem->execute(INSERT_SQL);
  // Note: since there are no results, we do not need to read any data
  // Deleting the cursor also frees up memory used
  delete cur_mem;
}

The following is the Serial COM4 readout:

Connected to wifi
 going into wl connect
.......wl connected

Credentials accepted! Connected to wifi

192.168.1.XX (intentionally deleted)

Connection failed.
Recording data.

Exception (3):
epc1=0x402050ea epc2=0x00000000 epc3=0x00000000 excvaddr=0x402315cc depc=0x00000000

ctx: cont
sp: 3ffef5a0 end: 3ffef7d0 offset: 01a0

>>>stack>>>
3ffef740:  0a00a8c0 00000001 3ffe8785 402050f4
3ffef750:  3ffee524 0000000e 3ffe850e 3ffee79c
3ffef760:  3fffdad0 00000000 3ffee770 402048fd
3ffef770:  402315cc 00000000 3ffee770 3ffee79c
3ffef780:  3fffdad0 00000000 3ffee770 40204945
3ffef790:  402010ae 00000000 3fff061c 4020292e
3ffef7a0:  3ffe8780 00000000 3fff061c 40201d3e
3ffef7b0:  3fffdad0 00000000 3ffee794 40204c34
3ffef7c0:  feefeffe feefeffe 3ffee7b0 40100718
<<<stack<<<

 ets Jan  8 2013,rst cause:2, boot mode:(3,7)

load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v09f0c112
~ld

I figured it out.  I needed to set up a User (IP  server) in the database.
In phpMyAdmin I created a new user (esp) and set the Host name to the IP address of the ESP8266.  In the sketch I changed the user from "root" to "esp".


Arduino and C++ Serial communication I am using this header: http://playground.arduino.cc/Interfacing/CPPWindows

My main:

#include <iostream>
#include <stdio.h>
#include <tchar.h>
#include "SerialClass.h"
#include <string>

int main(int argc, _TCHAR* argv[])
{
    Serial* SP = new Serial("\\\\.\\COM4");

    if (SP->IsConnected())
        printf("We're connected\n");

    std::string tryStr;
    int value;
    DWORD bytesSend;

    /* Loop */
    while(SP->IsConnected())
    {
         /* Take a value from user */
         printf("Value: "); scanf("%d",&value);

         /* Send Arduino */
         BOOL retVal = WriteFile(SP->hSerial, &value, sizeof(value), &bytesSend, NULL);

        /* I have no idea what is this for? (SP->status.cbInQue) */
        ClearCommError(SP->hSerial, &SP->errors, &SP->status);

        /* Read string from arduino */
        DWORD bytesRead;
        tryStr.assign("");
        bool check = true;
        char tempCharacter;
        while (check==true){

            ReadFile(SP->hSerial, &tempCharacter, sizeof(char), &bytesRead, NULL);
            tryStr += tempCharacter;

            if(tempCharacter == '$'){
                check = false;
            }
        }

        /* Print the string */
        std::cout << tryStr  << std::endl << std::endl ;
    }
    return 0;
}

My Arduino Code:

int LedPin= 10;
int value;
String  incomingData = "hello$";

void setup (){
  Serial.begin(9600);
  pinMode(LedPin, OUTPUT);
}

void loop (){

  while(!(Serial.available() > 0)){
    /*Wait until take data */
  }

  value=Serial.read();

  if (value == 20)
  {
      digitalWrite (LedPin, HIGH);
      incomingData.setCharAt(0,'o');
      incomingData.setCharAt(1,'p');
      incomingData.setCharAt(2,'e');
      incomingData.setCharAt(3,'n');
      incomingData.setCharAt(4,'n');

      Serial.print(incomingData);
  }
  else if (value == 15)
  {
      digitalWrite (LedPin, LOW);
      incomingData.setCharAt(0,'c');
      incomingData.setCharAt(1,'l');
      incomingData.setCharAt(2,'o');
      incomingData.setCharAt(3,'s');
      incomingData.setCharAt(4,'e');

      Serial.print(incomingData);
  }

}

This code works perfectly. Output:

  We're connected  Value: 20  openn$

  Value: 15  close$

  Value: 20  openn$

  Value: 20  openn$

  Value: 15  close$

  Value: 15  close$

  Value: 20  openn$

But now I want to add another condition in my Arduino code:

int LedPin= 10;
int value;
String  incomingData = "hello$";

void setup (){
  Serial.begin(9600);
  pinMode(LedPin, OUTPUT);
}

void loop (){

  while(!(Serial.available() > 0)){
    /*Wait until take data */
  }

  value=Serial.read();

  if (value == 20)
  {
      digitalWrite (LedPin, HIGH);
      incomingData.setCharAt(0,'o');
      incomingData.setCharAt(1,'p');
      incomingData.setCharAt(2,'e');
      incomingData.setCharAt(3,'n');
      incomingData.setCharAt(4,'n');

      Serial.print(incomingData);
  }
  else if (value == 15)
  {
      digitalWrite (LedPin, LOW);
      incomingData.setCharAt(0,'c');
      incomingData.setCharAt(1,'l');
      incomingData.setCharAt(2,'o');
      incomingData.setCharAt(3,'s');
      incomingData.setCharAt(4,'e');

      Serial.print(incomingData);
  }
  else{                                      // new line added
                                             // new line added
      incomingData.setCharAt(0,'g');         // new line added
      incomingData.setCharAt(1,'g');         // new line added
      incomingData.setCharAt(2,'g');         // new line added
      incomingData.setCharAt(3,'g');         // new line added
      incomingData.setCharAt(4,'g');         // new line added
                                             // new line added
      Serial.print(incomingData);            // new line added
  }                                          // new line added

}

But it didn't work. ScreenShot:

What went wrong? The led blinked correctly but the output string is wrong.

BOOL retVal = WriteFile(SP->hSerial, &value, sizeof(value), &bytesSend, NULL);

You're writing sizeof(value) bytes to the Arduino. Since value is an int, which is typically 4 bytes in size for PC compilers/processors, when you send 20, what actually gets to the Arduino is 0x00000014. Your processor is apparently little-endian so the order of bytes sent is 0x14, 0x00, 0x00, 0x00.

You're reading a single byte in every loop() iteration. Your first sketch worked because you didn't provide any else clause for unrecognized bytes. The Arduino merely ignored those leading zeros. However, your second sketch handled unknown bytes (such as 0x00) by printing gggg. So what you get for every value you send to the Arduino is exactly what you'd expect and what you see in your shell -- the result you want (openn == 0x14), followed by 3 gibberish results (because of the leading zero bytes).

You can fix it by either declaring value as a uint8_t in your CPP code (after including stdint.h) or only reading chunks of 4 bytes on the Arduino and then parsing what you get. The former solution seems more reasonable/reliable.


How to implement setSyncProvider and verify it is working with PC I'm trying to retrieve / synchronize time from PC using this Time lib function:

setSyncProvider( requestSync);  //set function to call when sync required

It sends ASCII BEL (07) character to PC, but I'm getting no response using Serial.available. What am I missing?

Do I have to run a specific app on the PC to get a response? The docs do not specify that.

Yes, you'll need something running on the PC which is monitoring the serial port, and which will provide a response in the appropriate format.

The download on this page contains a Processing sketch which will do this for you. After you've unzipped it, look in Time/Examples/Processing/SyncArduinoClock. Open the sketch in Processing, run it, and then start your Arduino.

If you're not familiar with it, Processing is a free programming language / environment based on Java. It's aimed largely at beginners and non-programmers, and is quite commonly used for communicating with Arduino projects via Serial. You can download it here:

http://www.processing.org


Merge two 8 bit arrays to one 16 bit array I am an absolute newbie to Arduino and C++ and try to go through some tutorials to gain a minimal insight. However I stuck already at some tiny Points. What I want to do? Merge two 8 bit integer Arrays in to one 16 bit Array:

int summand_one[8] = {0,0,0,1,1,0,0,0};
int summand_two[8] = {1,0,0,0,0,0,0,1};

int * summand = new int[16];
std::copy(summand_one, summand_one+8, summand);
std::copy(summand_two, summand_two+8, summand+8);

The result should be

{0,0,0,1,1,0,0,0,1,0,0,0,0,0,0,1}

However it's not working at all. Constructor/destructor/type errors…

Any helpful idea how to do this?

It's better to avoid dynamic memory allocation on an Arduino, with only 2 KB of SRAM memory.

Note that your arrays cost 2 (bytes/int) * (8 + 8 + 16) = 64 bytes.
And it seems you are only storing booleans, which could be stored in one bit. So consider another alternative (I will not work that out, since maybe memory consumption is not a problem).

However, an easy solution is to use uint8_t.

Also, I would use a simple memcpy. Very naively it would look like:

uint8_t summand_one[8];
uint8_t summand_two[8];
uint8_t summand[16];

void setup()
{
}

void loop()
{
  memcpy(summand, summand_one, 8);
  memcpy(summand + 8, summand_two, 8);
}

Using some constants for the sizes, you get more flexible/readable and maintainable code:

static const uint8_t SummandOneSize = 8;
static const uint8_t SummandTwoSize = 8;

uint8_t summand_one   [SummandOneSize];
uint8_t summand_two   [SummandTwoSize];
uint8_t summand_merged[SummandOneSize + SummandTwoSize];

void setup()
{
}

void loop()
{
  memcpy(summand_merged                 , summand_one, SummandOneSize);
  memcpy(summand_merged + SummandOneSize, summand_two, SummandTwoSize);
}


How to latch a 200mS LOW pulse? Trying to latch a 200 mS, LOW event to log the event.  LOW only occurs when external Watchdog timer sends reset pulse to the Arduino.

Is a D Latch suitable for this application?  It has been years since my digital class; help most appreciated.

How would you proceed?

I understand your question to be :  you want to latch (and indicate) whenever an external watchdog timer has reset your Arduino.

D type flip flop (latch) can be used.  You would use the clock input as the trigger. However, most D types clock on a rising edge. You could use an inverter on the input to the clock to get the D type to clock on a falling edge. You would also connect the D (Data) input high (logic 1). Then when your input (event) goes low, the Q output will latch high.  The 200 mS is irrelevant because the latch ocurrs at the change from high to low (low to high on clock input).

You would also need a means of resetting the latch, which many D types have a reset input or a clear input.

You could also use a more simple SR latch (set reset latch) using 2 Nand gates.  SR latch changes state when the “set” input goes low (providing that R input was high).  Make the R input go low to reset the latch.

POSSIBLE ALTERNATIVE :  If you have some means of operator intervention (or even a switch).  You could have your program light an LED at startup.  Operator (person) could reset LED.  Then afterwards,  any reset (restart of program) would light the LED.


Does data coming in on Arduino serial port store for some time? I am using Arduino Uno and my question is when data is coming on Rx pin and at that time our program is not checking Serial.available()

Then after some time the program will check Serial.available().
Can we read data? Does it get stored in memory?

If stored how to remove that?

Is the answer the same for Software.Serial()?

Yes.  The serial port uses a ring buffer (also known as a circular buffer) for storing the incoming data until you want it.  That buffer is 16 bytes in size on the smaller Arduinos and 64 bytes in size on the larger one.  A similar ring buffer is used to store transmitted data until the port is ready to transmit it in the background.


MAX471 giving too high current readings I want to measure current using the MAX471 sensor that outputs voltage proportional to the current (1V/A according to the datasheet). To test the module, I connected a 330 ohm resistor to the sensor and powered it from 3.3V arduino. Using ohms law, I was expecting an output voltage of around 10 mV (for ~ 10 mA) in my circuit. However, I am getting an output of around 2.17 volts which seems wrong.
Does anyone see any mistake in my circuit or how I am trying to measure the current?
Here is my circuit:

My Code:
#include <Arduino.h>

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

void loop()
{
  int adc_val = analogRead(A5);
  float vol = 3.2 / 4095 * adc_val; // using a 12 bit adc

  Serial.println(vol);
  delay(3000);
}

Do you have the same operating circuit that is shown on page 1 of the datasheet? do you have the 2K resistor they specifically from OUT to ground? Also, it may be worth adding the 1 uF capacitor they recommend from OUT to ground too
The other thing to consider is the actual voltage over the resistor. Check an see if the voltage over the resistor is 3.3 and that there isn't a voltage drop from the chip
If the voltage is fine, there may be a problem with the chip or the arduino


How do I choose proper diodes for a 74HC595 shift register with a wired OR connection? I want to use a wired OR connection to connect some pins of the 74HC595 shift register to an Arduino Digital Input Pin. How do I choose proper diodes for this situation?

Maximum rated forward current has to be higher than whatever current a single pin of the 74HC595 produces.
The V_F forward voltage drop has to be as low as possible to make sure that a HIGH from the shift register has still a voltage high enough to result in a HIGH at the Arduino pin after passing through the diode.
Switching time has to be low enough to match the shift register's frequency.

So far, so good? What did I miss?

By the way, I haven't decided on the voltage for VCC, yet. Most likely, either 5 V or 3.3 V.

For this, almost any diode will work.  Searching, it turns out that the 1N4148 is a popular ubiquitous choice.  But don't go out of your way to obtain this particular diode.

  Maximum rated forward current has to be higher than whatever current a
  single pin of the 74HC595 produces.

You should turn your thinking around.  Consider the nominal high voltage of the 74HC595, subtract the forward bias diode voltage drop (usually  0.7V for a silicon diode) and divide that by the resistor you pick.  That will be the current passing out of the 74HC595, through the diode and resistor.  Only a small amount of current will pass into the Arduino.  It should be negligible for most applications.  You should pick a resistor high enough to only allow milliamps of current to pass through this circuit.

  The V_F forward voltage drop has to be as low as possible to make sure
  that a HIGH from the shift register has still a voltage high enough to
  result in a HIGH at the Arduino pin after passing through the diode.

Check the voltage margin allow for a logical high input to the Arduino (Atmel processor).  I think 3V - 0.7V = 2.3V is still considered a logical high.  However, if you think this is too close, then switch to the 5 volt Arduino where the 0.7 volt drop will make less difference.

  Switching time has to be low enough to match the shift register's
  frequency.

I doubt this will be a problem.  That is, I doubt the CMOS logic will surpass the speed at which the diode can turn on / off.


What wrong with that code? Hi i have made this code
its so simple its should receive data from the computer and send it back via the serial but the problem is he do not what it is suppose to do
when its run its keep sending -1 to the computer
and if i send something to the arduini  like  55   i receive and answer 53
i have no idea were is the problem in this code

long number = 0;

void setup() {
  Serial.begin(9600);
}
   void loop() {
   number = Serial.read();
   delay(1000);
   Serial.println(number);
}

You need to include DEC as the second argument to the Serial.println() call to get the correct numbers out.  Read up on this here: Arduino Serial Print.

In other words, make change below:

Serial.println(number, DEC); // DEC is needed to get the correct values


Arduino SD count files and open last, How to? I am trying to count files. I have one hidden file from Windows10 so i am doing "-1" but I want to open the last file and can't work out how, any help? Please, Thanks

#include <SD.h>
int entryCount = 0;
File root;
int total = 0;
int Lfile = 0;
void setup()
{
  Serial.begin(9600);
  pinMode(10, OUTPUT);
  SD.begin(4);
  root = SD.open("/");
  printDirectory(root, 0);
  root.close();
  Serial.println();
  Serial.print(total-1);
  Lfile = total-1;

  File dataFile = SD.open(Lfile);
  // if the file is available, write to it:
  if (dataFile) {
    while (dataFile.available()) {
      Serial.write(dataFile.read());
    }
    dataFile.close();
  }
  // if the file isn't open, pop up an error:
  else {
    Serial.println();
    Serial.println("error opening last file");
  }
}

void loop()
{
  // nothing happens after setup finishes.
}

void printDirectory(File dir, int numTabs)
{
  while (true)
  {
    File entry = dir.openNextFile();
    if (! entry)
    {
      if (numTabs == 0)
      return;
    }
    for (uint8_t i = 0; i < numTabs; i++)
      Serial.print('\t');
    Serial.println(entry.name());
    total = entryCount;

    Serial.print(entryCount++);

    Serial.print('\t');

    entry.close();

  }
}

Consider using the exist() method found in the SD.h library you already are including in your program.  Assuming you will create no more than 99 files and the last file created will have the highest 2 digit value as part of its name, test for the existence of the file log99.txt.  If not found, decrement the 2 digit number and test for the existence of file log98.txt.  Repeat this process until you find the newest file created.


Turn off the second builtin Nodemcu 0.9 led I'm making a low energy consumption device so I'd like to turn off all the led when I'm idle.

Unfortunately the nodemcu turn on a blue led while I'm idle (during delay(ms))

Here is my code:

#define LED    16

void setup() {
  initialSetup();
  //Turn off the built-in led
  digitalWrite(LED, HIGH);
}

void loop() {
  //Here I do everything
  doStuff();
  //GO TO SLEEP
  delay(3600000);
}

The led that turn on during delay is the one near to D0 pin.

The led that I can control and so turn off (pin #16 -> D0) is near the 5v pin.

It's possible to completely turn off all led to consume less?

See this link which shows your second LED exactly (the image is for v1.0, I have v0.9 and the code below works just the same in this situation):

'Onboard LEDs? NodeMCU's got two!':

https://lowvoltage.github.io/2017/07/09/Onboard-LEDs-NodeMCU-Got-Two

Quote:

  ESP-12 LED Blink:

 void setup() {
        pinMode(2, OUTPUT);     //Initialize GPIO2 pin as an output
 }

 void loop() {
   digitalWrite(2, LOW);   // Turn the LED on by making the voltage LOW
   delay(1000);            // Wait for a second
   digitalWrite(2, HIGH);  // Turn the LED off by making the voltage HIGH
   delay(2000);            // Wait for two seconds
 }

Or write it like this (ie. using 'D4' rather than '2'):

  ESP-12 LED Blink:

 void setup() {
        pinMode(**D4**, OUTPUT);     //Initialize GPIO2 pin as an output
 }

 void loop() {
   digitalWrite(**D4**, LOW);   // Turn the LED on by making the voltage LOW
   delay(1000);            // Wait for a second
   digitalWrite(**D4**, HIGH);  // Turn the LED off by making the voltage HIGH
   delay(2000);            // Wait for two seconds
 }

Regards, Geoff


How does this code move the bird sprite in this sketch? I'm teaching this sketch in my class. I understand most of the sketch and can see the class that makes the bird move, but I still don't quite understand how the code makes the sprite "move." I can also see what generates the Pipes but I don't how the code creates them or randomizes them.

Here is the code for both:

Bird

class Chym {

private:
  int frameCount;
  int x;
  int y;
  int deltaIde;
  int delayFrame;

  int jumpCount;
  int maxJumpCount;
  int moveSpeed;

  bool _isDead;
public:
  void respawn() {
    x = 24;
    y = 20;
    deltaIde = -1;
    moveSpeed = 1;
    jumpCount = 0;
    _isDead = false;
  }

  Chym() {
    frameCount = 0;
    delayFrame = 0;
    maxJumpCount = 20;
    respawn();
  }

  void render() {
    if (frameCount < ANIM_FRAME / 2) {
      display.drawBitmap(x, y, flappybird_frame_1, 16, 12, 1);
    }
    else {
      display.drawBitmap(x, y, flappybird_frame_2, 16, 12, 1);
    }
  }

  void update() {
    delayFrame++;
    if (delayFrame == DELAY_FRAME) {
      y += deltaIde * moveSpeed;
      delayFrame = 0;
    }

    if (y > 35) {
      _isDead = true;
    }

    frameCount++;
    if (frameCount >= ANIM_FRAME) frameCount = 0;
  }

  bool isDead() {
    return _isDead;
  }

  void die() {
    _isDead = true;
  }

  void cancelJump() {
    jumpCount = 0;
    flyDown();
  }

  void flyUp() {
    if (jumpCount < maxJumpCount) {
      deltaIde = -1;
      moveSpeed = 3;
      jumpCount++;
    }
    else {
      flyDown();
    }
  }

  void flyDown() {
    deltaIde = 1;
    moveSpeed = 1;
  }

  int getX() {
    return x;
  }

  int getY() {
    return y;
  }

};

Pipe

class Bar {

private:
  int x;
  int y;
  int delayFrame;
  int moveSpeed;
public:
  Bar() {
    delayFrame = 0;
    x = 0; y = 24;
    moveSpeed = 2;
  }

  void setPos(int sx, int sy) {
    x = sx; y = sy;
  }

  void render() {
    display.drawBitmap(x, y - 30, bar_top, 8, 20, 1);
    display.drawBitmap(x, y + 10, bar_bottom, 8, 20, 1);
  }

  void update() {
    delayFrame++;
    if (delayFrame == DELAY_FRAME) {

      x -= moveSpeed;
      if (x < -10) x = 95;

      delayFrame = 0;
    }
  }

  int hitTest(int tx, int ty) {
    int hitX = ((tx >= x - 16) && (tx <= x))?1:0;
    int hitY = ((ty <= (y - 10)) || (ty + 12 >= y + 10))?1:0;
    if (hitX != 0) {
      return hitY;
    }
    return 0;
  }

};

https://www.youtube.com/watch?v=04cY78Y2d3g

This part of your code is what changes the sprite's y-value.

y += deltaIde * moveSpeed;

When you click the "jump" button or when the bird falls the y-value is changed to reflect either an upward movement or a downward movement. When your render() method is called the bird will either be drawn higher up on the y-axis (it's flying) or lower on the y-axis (it's falling).

As for the bars, if you watch closely in the video you can see that they aren't actually randomized.

Compound Assignment Operators

+= is the "plus assign" operator. It adds whatever is on the right side to the variable on the left side. Here is a table of other compound assignment operators: https://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Compound_assignment_operators

int x = 5;
x += 2; // equals 7; equivalent to x = x + 2;
x = 5;
x = x + 2; // also equals 7; equivalent to x += 2;


printing the analogRead() functions result crashes Arduino I have created a curcuit which reads the analog pin 3 auf the arduino nano and does other things dependant on the returned value. However I have problems regarding the analogRead() function. Whenever I use a piece of wire to short the "Analog_UpDownHorn_Signal" and do it fast paced so that the arduino reads 0V and 5V repeatedly the serial communication stops. Sometimes it resumes. Sometimes it doesn't and when it does the value is always 1023.
I have managed to reduce the problem to the following 2 lines of code, which leads me to believe its my curcuit or a bug in the functions used. Before the arduino gets stuck it sometimes puts out random '?' or other wierd characters on the serial monitor.
void setup()
{
  Serial.begin(9600);
}

void loop()
{
  Serial.println(analogRead(A3));
}

The capacitor you have is rather large on the Analogue input, normally at this position it would be for debounce. Try something in the range of 100nF. Another idea would be to increase R8 to 10k.
https://www.g7smy.co.uk/2015/09/multiple-buttons-on-one-pin-with-an-arduino/


Arduino Uno: Sensor shield powering multiple servos I posted this on the electrical side of stack exchange and they said it was off topic, so I think it will be on topic here and they confused me even more. So if you guys could clear up my confusion, that would help.I know there are sources for this, but I am still lost.  Anyways, here is the run down. I want to control multiple servos (12 of them) using a sensor shield. I need to know what kind of power supply I need. Here is the servo's I am using:

https://www.amazon.com/gp/product/B01NA80LUR/ref=oh_aui_detailpage_o02_s00?ie=UTF8&psc=1

Here is the sensor shield I am using:

https://www.amazon.com/gp/product/B01ACKVPTW/ref=oh_aui_detailpage_o01_s00?ie=UTF8&psc=1

The servos run at 3-7.2V and 750ma-1000ma full load or another person said they ran only 100-150ma. Also, another question is do I plug that power supply, when I get the right one according to what you say, into the dc jack or the external power on the sensor shield board?

Thank you for your time.

two things make servos fairly easy to control:

they take a slow pwm input; generating pwm is fairly easy on a mcu;
they are generally not that sensitive to the duration of the off state: I have tried from 5ms to 40ms (the longest) and they are fine with that.

so if you combine the two attributes together, it is easy to control multiple servos with from one timer interrupts.

I wrote a few pages on this recently:
1. driving multiple servos on AVR Timer2: https://dannyelectronics.wordpress.com/2017/02/08/driving-multiple-servos-with-avr-timer2/

driving multiple servos on PIC: using TIMER0 (https://dannyelectronics.wordpress.com/2017/02/08/driving-multiple-servos-with-pic-timer0/) or TIMER1 (https://dannyelectronics.wordpress.com/2017/02/07/driving-multiple-servos-with-pic-timer1/).

The following is a combination of the two: driving 8 servos independently on PORTB with TIMER1 and another 8 servos independently on PORTD with TIMER2.

the user code is quite simple:

//set up servo controller 1
srvo1_init();                           //reset the servo module
srvo1_setpr(1, 1000);                   //for 1ms
srvo1_setpr(2, 1200);                   //for 1.2ms
srvo1_setpr(3, 1400);                   //for 1.4ms
srvo1_setpr(4, 1500);                   //for 1.5ms
srvo1_setpr(5, 1800);                   //for 1.8ms
srvo1_setpr(6, 2000);                   //for 2ms
srvo1_setpr(7, 2500);                   //for 2.5ms
srvo1_setpr(8, 4000);                   //for 4ms

//set up servo controller 2
srvo2_init();                           //reset the servo module
srvo2_setpr(1, 1000);                   //for 1ms
srvo2_setpr(2, 1100);                   //for 1.1ms
srvo2_setpr(3, 1200);                   //for 1.2ms
srvo2_setpr(4, 1300);                   //for 1.3ms
srvo2_setpr(5, 1400);                   //for 1.4ms
srvo2_setpr(6, 1500);                   //for 1.5ms
srvo2_setpr(7, 2000);                   //for 2ms
srvo2_setpr(8, 4000);                   //for 4ms

Once it is set-up, you can just leave it alone and no addition attention is required. You can change the duration of course, or disable / re-enable output on a given channel.

Total CPU drain is about 150K ticks in a second for 16 channel controller.

works on Arduino as well.

edit: if you port the code to TIMER0 (easily done),  you can control 32 servos independently.

and if you combine this code with making timers out of the output compare functionality, you can shrink them all on one timer.


Unexpected negative values from abs() function inline with analogRead When sampling from A0 with a 0-5V signal on an arduino micro with the code below I get some negative values.

int sensor = 0;
sensor = abs(analogRead(A0) - 512);

Values:

77
25
-74
-58
46
113
-74
102
-91
-51
-126
47
31

When running the (apparently) mathematically equivalent code below I get exclusively positive values.

int sensor = 0;
sensor = analogRead(A0);
sensor = sensor - 512;
sensor = abs(sensor);

I don't think this is an integer overflow as in this post because when I switch to long sensor = 0 I get the same negative results.

What's going on here?

abs() is defined in Arduino.h as a macro:

 #define abs(x) ((x)>0?(x):-(x))

A macro does not evaluate in the same way as a function.

 sensor = abs(analogRead(A0) - 512);

This statement will be expanded at compile-time to:

 sensor = ((analogRead(A0) - 512)>0?(analogRead(A0) - 512):-(analogRead(A0) - 512));

Now the "error" is easy to understand. The analog pin is read twice. The "error" can be avoided by adding the following line first in your sketch:

#undef abs

This will remove the macro abs() and the standard library function will be used instead.

Cheers!


SPI.transfer(buffer, size) does not send data from buffer I am having trouble getting SPI.transfer(buffer, size) to work as expected.

Here is the code:

// inslude the SPI library:
#include <SPI.h>

// set pin 10 as the slave select for the digital pot:
const int slaveSelectPin = 10;

uint16_t SPI_message = 0xABCD;

void setup() {
  // set the slaveSelectPin as an output:
  pinMode(slaveSelectPin, OUTPUT);
  // initialize SPI:
  SPI.begin();

}

void loop() {

  SPI.beginTransaction(SPISettings(14000000, MSBFIRST, SPI_MODE0));
  SPI.transfer(0xEF);
  SPI.transfer(&SPI_message, 2);
  SPI.endTransaction();

  delayMicroseconds(300);

}

Here is the output of logic analyzer:

As can be seen the call for SPI.Transfer(0xEF) works as expected. However SPI.transfer(&SPI_message,2) sends 0x0000 instead of 0xABCD on the bus.

What am I doing wrong?

SPI.transfer(&SPI_message,2) is unfortunately destructive. The buffer is updated with the received values. There is a SPI member function[1] that can be used for 16-bit data; SPI.transfer16(SPI_message).

To correct your sketch either initialize the buffer before each call (as recommended by @domen) or use the 16-bit transfer function.

There are other SPI APIs that included non-destructive transfer function e.g. read/write. Please see [2].

Cheers!

Ref.

https://www.arduino.cc/en/Reference/SPITransfer
https://github.com/mikaelpatel/Arduino-SPI/blob/master/src/SPI.h#L137


LED Strip Effect without delay so a brief introduction about the project which I am working on before I go onto my issue.

I am working on a love-o-meter project (Not similar to the arduino example), whereby 2 people place 1 of their hands on a pad and with their other hand holding each other. Making use of a pulse sensor, I measure the BPM for 10s and then indicate the score on a LED strip.
Apart from indicating the compatibility score, I also plan to use the LED strip (cylon/fire effect) to indicate that the arduino is in the progress of calculating (when it is measuring the BPM for 10s) and also to indicate idling (rainbow cycle effect, when there is no one is using the love-o-meter).

However, here comes my issue: Performing the BPM measurement and displaying the cylon/fire effect function at the same time. I know that I cannot use the delay function and instead use millis(). However, the functions in the NeoPixel library already uses the delay effect and it seems like a tough job to edit the function to it using millis(). Is there another way to do so?

If you can find another way of calculating the BMP during displaying an effect on the strip depends highly on your BMP sensor. If you can do the measurement with interrupts, it should work. In this case you should make sure, that the interrupt cannot be fired during the execution of the Adafruit_NeoPixel.show() function, since it is quite timing sensitive.

But since I recently worked on a project with a NeoPixel LED strip, I have already edited functions from the strandtest example for use with the millis() function. So you will not have to reinvent the wheel again :D I will try to strip away my custom code, so that you can easily use it.

float brightness = 1.0;
uint32_t strip_state=0;

uint32_t Wheel(Adafruit_NeoPixel *strip, byte WheelPos) {
  WheelPos = 255 - WheelPos;
  if(WheelPos < 85) {
    return strip->Color((255 - WheelPos * 3)*brightness, 0, WheelPos * 3*brightness);
  }
  if(WheelPos < 170) {
    WheelPos -= 85;
    return strip->Color(0, WheelPos * 3 * brightness, (255 - WheelPos * 3)*brightness);
  }
  WheelPos -= 170;
  return strip->Color(WheelPos * 3 * brightness, (255 - WheelPos * 3)*brightness, 0);
}

void fill_color(uint32_t color){
  byte r= ((color & 0xFF0000) >> 16) * brightness;
  byte g= ((color & 0xFF00) >> 8) *brightness;
  byte b= (color & 0xFF) * brightness;
  color = strip.Color(r,g,b);
  for(unsigned int i=0; i < strip.numPixels(); i++) {
    strip.setPixelColor(i, color);
  }
  strip.show();
}

void fade_color(){
  for(unsigned int i=0;i<strip.numPixels();i++){
    strip.setPixelColor(i,Wheel(&strip,strip_state));
  }
  strip.show();
  strip_state++;
  if(strip_state>255) strip_state = 0;
}

void moving_rainbow(){
  for(unsigned int i=0; i<strip.numPixels(); i++) {
    strip.setPixelColor(i, Wheel(&strip,((i * 256 / strip.numPixels()) + strip_state) & 255));
  }
  strip.show();
  strip_state++;
}

void colorWipe(uint32_t color) {
  byte r= ((color & 0xFF0000) >> 16) * brightness;
  byte g= ((color & 0xFF00) >> 8) *brightness;
  byte b= (color & 0xFF) * brightness;
  color = strip.Color(r,g,b);

  strip.setPixelColor(strip_state, color);
  strip.show();
  strip_state++;
}

//Theatre-style crawling lights.
void theaterChase(uint32_t c) {
  byte r= ((c & 0xFF0000) >> 16) * brightness;
  byte g= ((c & 0xFF00) >> 8) *brightness;
  byte b= (c & 0xFF) * brightness;
  c = strip.Color(r,g,b);
  for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
    strip.setPixelColor(i + strip_state % 3, c);    //turn every third pixel on
    strip.setPixelColor(i + (strip_state +1) % 3, 0); // turn others off
    strip.setPixelColor(i + (strip_state +2) % 3, 0);
  }
  strip.show();
  strip_state++;
}

//Theatre-style crawling lights with rainbow effect
void theaterChaseRainbow() {
  for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
    strip.setPixelColor(i + strip_state % 3, Wheel(&strip, (i+strip_state) % 255));    //turn every third pixel on
    strip.setPixelColor(i + (strip_state +1) % 3, 0); // turn others off
    strip.setPixelColor(i + (strip_state +2) % 3, 0);
  }
  strip.show();
  strip_state++;
}

The functions use the float variable brigthness to modulate the overall brightness of all LEDs. You can set it to every value between 0.0 and 1.0.

The variable strip_state holds the current state of the effect on the strip. It is incremented everytime one of the functions is executed. Reset it to 0 if you want to restart an effect.

You yourself have to declare the variable strip as from the type Adafruit_NeoPixel.

So now you only have to call these function from the typical millis() code (like from the BlinkWithoutDelay example) in an interval, that you chose.


Read one value from continuous data stream at a lower frequency I am working on a university final project and have run into a problem with programming Arduino, after a 3 year hiatus. I have a pressure transducer that is sending pressure data at 10Hz. I have successfully programmed my Arduino Pro Micro to read the data as it is coming in. I'm using the SoftwareSerial library to set digital pins 8 and 9 to RX and TX, respectively. As the pressure transducer is continuously streaming data values, I read each character, store them in an array, and print them to the Serial Monitor. I'm using a start and end-marker to recognize each incoming character and put them into the array. The raw data output from the transducer is in the form:

*000114.2927
*000114.2926
*000114.2927

And this is the code I am using.

#include <SoftwareSerial.h>
#define paroRX 8
#define paroTX 9

SoftwareSerial paroSerial(paroRX, paroTX);

const byte numChars = 16;
char paroChars[numChars];     //array to store received data
char paroToSend[numChars];      //array to transmit
boolean newParoData = false;

void setup(){
  Serial.begin(9600);     //with transmitter radio
  paroSerial.begin(9600);
}

void loop(){
  paroSerial.listen();
  readParo();      //read from Paro and store values in paroChars
  if(newParoData == true){
    for(int i=0; i<16; i++){
      paroToSend[i] = paroChars[i];
    }
    Serial.print(paroToSend); Serial.print('\n');     //transmit Paro data with a new line for each value
    newParoData = false;
  }
}

void readParo(){
  static boolean receiveInProgress = false;
  static byte index = 0;
  char startMarker = '*';
  char endMarker = '\n';
  char pd;
  while(paroSerial.available() && newParoData == false){
    pd = paroSerial.read();
    if(receiveInProgress == true){
      if(pd != endMarker){
        paroChars[index] = pd;
        index++;
        if(index >= numChars){
          index = numChars - 1;
        }
      }else{
        paroChars[index] = '\0';      //terminate string
        receiveInProgress = false;
        index = 0;
        newParoData = true;
      }
    }else if(pd == startMarker){
      receiveInProgress = true;
    }
  }
}

And this is the output that I get, which is correct. I don't really want that * in front anyways.

000114.2927
000114.2928
000114.2927
000114.2929

But all of this happens at 10Hz, which means I get a constant stream of readings on the Serial Monitor. I want to slow this down to 1Hz, or just one reading per second. The obvious solution that occurred to me was to put a delay in the loop. So I tried to implement this with delay(1000) and using the millis() function as well, but I get strange readings like:

000114.2927
***000114
**2928
***.000114
000114.2928

How can I read at 1Hz from the 10Hz data stream? I want to just store one data value from the stream per second in the form of 000114.2927, then ignore the rest while the Arduino does something else.

Thanks!

You're thinking backwards. You don't want to read slower (which is what delay does), you want to only send every 10th entry.

That is, count the lines as they come in. When you hit 10 you print one and reset your count.

In other words:

static int count = 0;

if(newParoData == true){

  count ++;
  if (count == 10) {
      count = 0;

      // (Why copy the line just to send the copy...?)
      for(int i=0; i<16; i++){
        paroToSend[i] = paroChars[i];
      }
      Serial.print(paroToSend); Serial.print('\n');     //transmit Paro data with a new line for each value
  }
  newParoData = false;
}


Flickering LCD when using > 5v power supply on a Pro Mini I have a Pro Mini wired up to an LCD via an I2C board. At http://www.arduino.cc/en/Main/ArduinoBoardProMini it says the pro mini can accept up to 12v on the RAW pin as it has a voltage regulator on board. When I plug a 12v power supply into the raw pin, the LCD works fine initially, then slowly degrades into flickering more and more. It also does this with a 9v power supply. At 5v it works perfectly. Any ideas what's going on?

If the LCD has a backlight you are absolutely over heating the regulator on that board by running it at 9 or 12V: At 12V with 100mA for the backlight and using 175C/W thermal resistance for the regulator:
Tj = 25C + ((12V - 5V) x 100mA x 175C/W) = 147C
That regulator goes into thermal limit at 125C.


How can I record something using an arduino and use bluetooth to search those terms on google now? I'm trying to build something that can use voice recognition to search something up. I am planning to use this small module for the mic (https://www.sparkfun.com/products/12758), because I want to make it as compact as possible. So I've hooked up a bluetooth module to my arduino uno and I can hook the microphone up, but how would I get the microphone to connect to my phone's Google Voice Search in realtime through bluetooth?

If this is a simple "I can do it!", then it's a good project to work.
If it's just something to use, I'd rather use RPi. It's much much more simple to do it. Even already has proper connectors and everything. Just plug&play for this kinda application.


Serial data to arduino problem I cant understand what is going on here , I was trying to find way to send through Serial a number for example 12 and then extract from it number 1 and 2 and store them in two different variables , but suddenly i was unable to make a simple division !!

Do you want to eventually do 12 / 10 or 1 / 10 and 2 / 10? If the second one, you'll have to read all the serial values into an array and convert those characters to their plain integer values (subtracting 48 from each value). After that, you'll have to add them together with the correct placeholders (A * 100 + B * 10 + C).

Basically, the read() function returns one character in the ASCII format. ACII basically representing characters on your screen with numbers. 48 displays a 0 on your screen, 49 a 1, and so on.

You're also facing a problem where your numbers are getting truncated. This means it cuts off the decimal. For when you send 100, it is 48 / 10 = 4.8, however 4.8 becomes just 4. The same thing happens for 49.

To fix this, you need to use a float data type. This allows decimal values. You also want to make sure that the conversion from float to string works correctly for the Serial.print() so you don't end up with 4 again.

Final code:

while(Serial.available()) {
  float number = (float)(Serial.read() - 48) / 10;
  Serial.println(number, 4);
}


Arduino and 2 MOSFETs I want to turn on 2 bulbs using 2 MOSFETs. The problem is that they both turn on when it should turn up just one light.

Code:

void setup() {
  pinMode(13, OUTPUT);
  pinMode(7, OUTPUT);
}

void loop() {
  digitalWrite(13,1);
  digitalWrite(13,0);
}

See circuit below:

Try adding a delay into your loop. In your code pin 13 will toggle very rapidly, much too fast to see it. For example:

void loop() {
  digitalWrite(13,HIGH);
  delay (1000);
  digitalWrite(13,LOW);
  delay (1000);
}

It doesn't look wired correctly. For an N-channel MOSFET the Source should go to ground, like this:


Why does an `.ino` file have to be in a folder of the same name? I'm trying to organise a very complicated project and I want to put all the actual code in a folder named src (source), but I want to keep the main .ino file as main.ino (it will also be in src). Then when I try to open the code, the IDE says that main.ino has to be in a folder named main.

Why is this?

I fully understand the error message, but why does the file naming in Arduino has to be so. Is there a way to change that?

AFAIK, that is a quirk built into the Arduino IDE. The best workaround I can think of is a file structure something like:

ArduinoWorkspace --- /myproj/ ----+ /src/ --------+ myproj.cpp
                                  + myproj.ino    + sensor.h
                                                  + sensor.cpp
                                                  + (more files)

, where myproj.cpp just #include's main.cpp. This should leave your project files "clean" such that they should work in a more typical environment as well.

Update:

I borrowed the name "main" from your question, but on reflection, "main" is a reserved name, specifically, every C or C++ program has a main.c or main.cpp as its top level code, provided by the system if you don't provide one. So I avoided using that as the folder- and project-name (but feel free to try it) and I've updated the diagram. What you do need is a project folder and a .ino file within it, of the same name. The .ino file could

#include <src/anything-else-you-like>

, e.g., your top level code file, thus pulling everything else. You may need for your .ino to #include each of the files in the src folder, if it the compiler doesn't figure out on its own, that that's where your other files are.

BTW, if you do use the name main.cpp for your top file, it will have to call the setup() and loop() functions (and serial event function, if you use that). It's probably best to leave the name 'main' alone, let the system provide the same main every Arduino program gets by default, and write your project code the typical Arduino way -- starting with setup() and loop().


Sending minimal data between two Arduinos far away from each other Problem: I need to send small integer numbers (single-digit numbers suffices) between two arduinos located approximately 50-60m away from each other.
The connection must be made through cables. I have read that the mentioned distance is too long for using serial communication. I do not care if the method is not fast, delays up to one or two seconds are ok for this. If it helps: the devices (Arduino UNO or similar) will run not  yet written codes for a simple alarm system (with no cameras/images).

Question: What is a good way to this?

My efforts: I thought a couple of alternatives to solve this problem. Both involve the use of PWM signals sent from a device A to another B.

One of them requires some DAC in A  and read the analog input in B. The values read are then mapped to the small integer lists. I found some disadvantages with this approach:

Increment of hardware complexity and cost. Although I have read that the digital to analog conversion can be made with cheap capacitors I would have many problems to acquire them because of the lock-down of my country.
Probably I will need to  do many test to set up the mapping procedure  due to voltage drop.

The second is just read the digital input in B many times during a fixed period (e.g. 0.1 or 1 second) and average the values that were read in that period. My bet is that the devices are not synchronized and then the average (times 1023) in such longs periods would be close to the value sent by analogWrite(somepin, value). Finally, the accepted value would be the closest value in alist of acceptable values.
Example: For passing one of the numbers 0,1,2 or 3 the A device will output 0, 341, 682 or 1023, respectively. Eg. for passing "1" A will do analogWrite(somepinA, 341). B will read int lecture = digitalRead(somepinB) and get the time average of lecture for some time period. After multiplication by 1023 it could return something like "312". Then, it must find the value in [0, 341, 682,1023] closest to 280 (341) and map to 1.

Even if they were synchronized some way, I think that I could send 0 or 1 using random numbers or digitalWrite(somepinA) (Is it possible? Advantages? Disadvantages?)

I'm a novice in this field so I do not known if there is something wrong with my approach. I would also appreciate if a better alternative is proposed.
Thanks in advance.

RS-485 is best (you can buy some modules for this from Adafruit, Amazon, eBay, etc), but you can use the built-in hardware RS-232 serial UARTs from each on pins 0 and 1 so long as the baud rate is really really low. The lower the baud rate, the longer the range can be because lower baud rates reject noise better (and the longer the cable, the worse the noise, since the longer the cable the more it acts like an antenna and an inductor and a capacitor). Here are some rough estimates of how far you can transfer regular-logic-level unbalanced RS-232 signals:

Source:
https://www.tldp.org/HOWTO/Remote-Serial-Console-HOWTO/serial-distance.html
If this trend continues, you should be able to get like 120m at 1200 bps (baud), 240m at 600 bps, 480m at 300 bps, etc. maybe even up to > 1000m at 50 bps. I don't think the trend will continue like that, and we are using 5V TTL logic (signal voltage) levels here instead of RS-232's +/- 12V or so, so our logic levels are much worse and will have less range, so just use 50 baud and give it a shot:
// do on each Arduino
Serial.begin(50); // 50 baud = 10 bytes/sec throughput rate; see below

Note that for 8-N-1 serial communication baud rate, which is the default on Arduino, there are 10 bits per byte sent over the wire. This is because there is "one start bit, the eight data bits, and the one stop bit" for every 8-bit byte sent. That's an effective throughput data rate of 80%. This means a baud rate of 50 bps (bits per second) only can transmit 50/10 = 5 bytes per second. That's it! That's suuuuuper slow, but if it's fast enough for your application, it's fast enough!
I hypothesize 5V TTL twisted quad RS-232 communication between two Arduinos would have a maximum range at 50 baud of about 1000m/(24V span for regular RS-232 / 5V span for 5V TTL logic RS-232) = 208m. Just a crude guestimate. Please report back any findings you get from your experiments. I'd like to hear about it.
Assuming that this all does work, it would also be useful to start increasing the baud rate on each device until the data starts getting corrupted. Back off on the baud rate a little, and that's your maximum baud rate. Take that maximum baud rate and divide by 2 or 3, and that's your maximum "safe" baud rate perhaps. If you need throughput that is as high as possible, then that's what I'd do. Ex: maybe in your case 50 baud works just fine, so you increase it. At 1000 baud you start seeing corrupted data, so you back off to 800. At that point you no longer see corrupted data. So, divide that by 2 or 3 and you get a maximum "safe" baud for your setup of perhaps 800/3 = 267 to 800/2 = 400.
Try using a twisted quad cable (wires are twisted together in groups of 4) to reduce noise and increase range, and set the baud rates on each Arduino to like 50. You will need 3 wires connected between the Arduinos:

GND to GND
Tx to Rx
Rx to Tx

Power them each separately with ungrounded power supplies.
Communicate via Serial.write() and Serial.read() (so long as Serial.available() shows some data is available in the read buffer).
More on balanced vs unbalanced lines, and why I recommend "twisted quad" wire:
Normally, RS-232 is considered to be an unbalanced line transimission system. This means the impedance in the transmission wire is not equal to the impedance in the return wire, which would be a common ground between the sender and receiver, in conjunction with (in parallel with) an Earth ground through the building wiring and/or actually through the Earth...literally, the dirt you walk on. By powering each Arduino with an ungrounded power supply, such as a 2-prong power supply, however, which is common, there is no Earth ground connected to the Arduino. Furthermore, by only having a single transmission line active at any moment between two Arduinos, you have just balanced the transmission between them. Now, the out path is a single Tx signal from one Arduino to the other, and the return path has matching impedance, as it is your single, common GND wire between the two Arduinos. You now have balanced line RS-232 TTL logic level transmission between the two Arduinos. Balanced line transmission can have improved noise rejection and range by using a twisted pair between the two lines. In this case, however, there are 3 lines: Tx --> Rx, Rx --> Tx, and Gnd --> Gnd. So, you should use twisted quad wire, which means 4 wires at once are twisted together. Connect all 3 lines to the same twisted quad bundle. Again, remember, this assumes only one Arduino is transmitting at a time on one single wire in one single direction at a time (so as to not negate your return current through the GND line when transmitting on two lines, one in each direction, or double your return current through the GND line when transmitting on two lines each in the same direction [assuming you had multiple UARTS on each device]), thereby this usage creates a balanced line system since they also aren't truly grounded through a 3-prong grounded power supply. If these 2 requirements are met (1 Arduino transmits at a time, and at least one of them is not grounded to the building wiring), use twisted quad wire, as the system is balanced line communication. If it is not the case, because you are transmitting from each Arduino to the other at exactly the same time, or because both (not one) Arduinos are grounded to the building, thereby offering an alternative return path through the building ground wiring, then twisted quad cable will not benefit you, and you should use regular untwisted wiring.
Having said all that, experimentation is the real boss here. Try it out. if I didn't have twisted quad wire I'd try twisted pair, and if I didn't have twisted pair, I'd try untwisted wire.
Regarding your approach about using PWM to produce an analog output to be read by the receiving end:
Using PWM to produce an analog voltage to be read by the receiving end is an interesting approach. Without filtering, I think what you'd be doing is producing tremendous noise, however, literally producing electromagnetic radiation (think like low frequency radio or TV waves or something), where this huge 60m wire is your broadcasting antenna. If you put a 20k~50k resistor right at the sending end, however, and a 1uF capacitor right at the receiving end, however, to filter this PWM into an analog output immediately at the sending end, I think it would then eliminate your antenna effect where you are broadcasting something, and work much better, but still be highly susceptible to external noise influencing it. Give it a shot, but I suspect a simple set of digital pins to set HIGH or LOW on different pins to match different states would be much much much better than any analog signal at those lengths, with a 50 baud serial signal being the next best for signal-to-noise thereafter.
So, in order of best to worst signal-to-noise ratio (SNR):

differential pair (referenced to each other) digital HIGH/LOW values to represent states, which you update very slowly
RS-485 differential pair serial transmission
Note: for all of the following really low-speed digital signal sending scenarios, you might try it with the low-pass filter shown in the schematic below too, as it may help reject noise.
single-ended (referenced to GND) digital HIGH/LOW values to represent states, which you update very slowly
super low-speed SPI (including bit-banging it); ie: declare any digital pin a CLOCK_PIN, and any other digital pin a DATA_PIN. Set a clock pin LOW, set a data pin HIGH, set the clock pin HIGH. The clock transition tells the receiver (you have to code this up) to read the data pin, so you just read a 1 bit. Set the data pin LOW, set the clock pin LOW. The clock transition tells the receiver to read the data pin, so you just read a 0 bit. Leave the data pin low, set the clock pin HIGH again. You just sent another 0 bit, etc etc. Send data like this really slowly. It will work at great lengths--even better than asynchronous serial since it's synchronous.
asynchronous serial (+/- 12V true RS-232) at 100 baud
asynchronous serial (+/- 12V true RS-232) at 50 baud
asynchronous serial (5V TTL RS-232) at 50 baud
asynchronous serial (3V TTL RS-232) at 50 baud
analog value filtered with resistor and capacitor low-pass RC filter; update: I'd try this filtering layout for sending analog values via PWM (see schematic below, but use the higher resistor value I describe in my bullets underneath the schematic, rather than the lower value I show in the schematic); the filter may also be beneficial to help filter noise when doing low-speed digital communication too, so give it a shot in your 50-baud rate serial setup above too:

Send with analogWrite() (PWM); receive with analogRead().
Report back on this too please. I'm very curious if it would work.

unfiltered PWM---square wave antenna broadcasting who knows what--could result in an interesting broadcasting system for you. Add a transistor and you could really amp up the power and broadcast some interesting signals out! Get some good high power going here (1W~10W+) and maybe even get the government to find out who's jamming GPS and cellular? I don't know: could be interesting!

Schematic of low-pass RC filter to reduce noise between the two Arduinos when sending really low-speed digital signals (better), or slowly-changing analog signals (worse) between the two sides:

simulate this circuit – Schematic created using CircuitLab

For filtering the digital signals (ex: 5V TTL pseudo-RS232 serial at 50 to 100 baud):

Use 470 Ohms for each resistor, as shown above.
This results in a cutoff freq of 847 Hz, so stay below ~169 baud (cutoff_freq/5 = 847Hz/5 = 169 or so) for digital signal sending through this filter.

For filtering analog signals sent via analogWrite():

Since most Arduino pins have a PWM Frequency of 490 Hz, we need a cutoff frequency of ~490Hz/10 = 49Hz or lower to cleanly filter out the PWM frequency and result in a true analog output.
Using the calculator linked-to below, that means you should use R values of at least 10k each, which results in a cutoff freq. of 40 Hz. You can use 20k resistors each too, for a cutoff freq. of about 20 Hz.

To increase cutoff frequency to allow higher baud rates, decrease either R or C or both.
For a cutoff frequency calculator, see: https://electronicbase.net/low-pass-filter-calculator/#rc-low-pass-calculator --> "RC Low Pass Filter Calculator" --> enter, for example, 940 Ohms (470 x 2) as the resistor value and 0.2uF (0.1uF x 2) as the capacitor value to see that the resulting cutoff frequency for this low-pass filter is 846.57 Hz.

I'm no filter expert, but this is what I'd try. If someone sees some glaring errors in this filter or ways to improve it, please comment below the answer.
Extras:
Here's the Bode plot for the above series filter I show except with a 1k resistor and 0.1uF (100nF) capacitor followed by the same thing again. The purple line is the voltage we care about. Source: godfreyl, here.

The cutoff frequency here is 398Hz, which is where the -3db drop occurs, which corresponds to the half power and 70.7% voltage attenuation point. (sqrt(0.50) = 0.707, so 0.707^2 = 0.5)). You can read more about cutoff frequency here.

Additional reading:

https://www.tldp.org/HOWTO/Remote-Serial-Console-HOWTO/serial-distance.html
Google search for "is rs232 balanced?"
https://www.idc-online.com/technical_references/pdfs/data_communications/tutorial_2.pdf
http://www.iec-usa.com/Browse05/DTBALUN.html
https://en.wikipedia.org/wiki/Signal-to-noise_ratio


Power Arduino Nano with OTG cable I have a project that I am putting an Arduino Nano in an enclosed box that will light LEDs in a pattern. I am planning to power it with a 5 V power brick but I would like to build a way a update the code to the Arduino without needing to disassemble the box.

Could I use an OTG cable with power (OTG Y cable)  to accomplish this? or is there a better way to do this?

It is possible to use a OTG Y cable just plug it into your phone, power cable into the power source and use the third connector to connect  to your PC. (Assuming the PC only gets GND, D+ and D- and battery bank GND, 5V)

It is also possible to reprogram an Arduino with an Android device that has OTG support.
Would save you a bit of hassle.

My Android phone (LG D605) with ArduinoDroid can easily upload code to my Nano and Uno.


Extract binary data from text string. Like Perl pack, not just regexp If I have data coming into an Arduino in an ASCII serial format from some external device (or from a PC, or whatever) and I want to extract binary values from that data and log it or put it on a little display or react to it or whatever there are a few ways I can do it. But it seems like there should be a reversed version of sprintf, mashed up with regexp, mashed up with Perls pack/unpack that would make it easy and configurable.

For example, let's say I'm getting hex numbers from a data logger. something like
c,03,1234,5678,9ABC
where c is just a code telling me this line is channel data, there are 3 channels installed, and then there are the 3 sets of data. I can use split or something like that and then extract the values, convert the hex to binary, apply Y=mX+B and display the channel readings. If a channel goes flat, I can sound an alarm, etc... No worries.

But then I have a different data logger plugged in, and this one uses a different format. Like decimal raw ADC counts. It spits out
2342 1313 234236
Now I gotta recode.

But wait, what if I just had a regexp in eeprom and I used that to extract the data? Something like /^c,\X+,(\X+),(\X+),(\X+)$/ for the first logger and /^(\d+) (\d+) (\d+)$/ for the second. That would be really cool because I could pretty much extract data from any serial device for local display. No need to reprogram, just update the regexp. And there is a nice regexp library:
https://github.com/nickgammon/Regexp
although it uses the LUA regexp syntax.

Oh, but that won't work... because although my program in the Arduino gets back 3 values from the regexp, it doesn't know that the first set are hex strings, and the second set are decimal.

Now, if I was doing this in Perl, I'd just apply a pack string to the binary data. But then pack can't reject a bad match, it always returns a result, even if the input wasn't valid.

Doesn't it seem like the regexp should be able to return /binary/ values instead of just the string? It knows those values are hex. And shouldn't pack be able to do matching against the other characters in the string and reject the value if it's not a match?

Seems to me like there is a hole in our standard libraries. Something that does both simple matches, and converts data to binary return values on the fly.

Or is that too much to ask from an engine? Perhaps few people would use it; better to just hardcode for the rare times you need something like this?

Something that does both simple matches, and converts data to binary
  return values on the fly.

You are describing sscanf(). It is way less powerful than
regexps when it comes to pattern matching, but it seems to closely match
your requirements.

Dummy example:

const int FORMAT_COUNT = 2;
const char * formats[FORMAT_COUNT] = {
    "c,%*x,%lx,%lx,%lx",  // first data logger
    "%lu %lu %lu"         // second data logger
};

// Here goes the data.
unsigned long channels[3];

// Try to parse using all the known formats.
void parse(const char *message)
{
    for (int i = 0; i < FORMAT_COUNT; i++) {
        int ret = sscanf(message, formats[i],
                &channels[0], &channels[1], &channels[2]);
        if (ret == 3) {
            Serial.print("Message \"");
            Serial.print(message);
            Serial.print("\" matched with format \"");
            Serial.print(formats[i]);
            Serial.println("\"");
            return;
        }
    }
    Serial.println("Could not parse message.");
}

Sample output:

Message "c,03,1234,5678,9ABC" matched with format "c,%*x,%lx,%lx,%lx"
Message "2342 1313 234236" matched with format "%lu %lu %lu"