Can I measure velocity from an accelerometer? How accurately? I've bought this module

Kootek GY-521 MPU-6050 MPU6050 Module 3 Axis analog gyro sensors+ 3 Axis Accelerometer Module

My project will involve affixing this to a moving object, moving at velocities varying from 0.1 to 1.0 meters per second.

From what I understand, this module will allow me to infer rotation and acceleration, will I be able to derive velocity?

How much accuracy can I expect?

The sensor in itself can't provide you the velocity. I have used it accelerometers in a couple of projects the easiest way to get the velocity is to constantly monitor acceleration changes and calculate velocity instantaneaously.

In order to do so follow these instruction. Pleas note that this is only 1 axis reading in actual case you will have to perform this for all three axis i.e. x,y and z.

I hope you are aware of the equation of motion (V = Vo + at)... The sensor will provide you value of acceleration at any given time. But acceleration can vary quite significantly during a huge time intervals so keep the time intervals 't' small. Lets say t = 10ms (depends on you). So calculate V after every 10ms intervale and this will give you current velocity at any given time. But what about Vo? As you know it is refered to as initial velocity so in the beginning it will be 0. Immediately after first reading when you are about to take second reading the Vo will change to the previous V calculated and hence forth.

This means Vo at any given interval is actually the V calculated in the previous interval.

I tried this method in my project when using accelerometer. hope it helps you as well.


Help! Interfacing LCD with Arduino using 8255A Intel peripherals I'm new to all this stuff and for the past two days, I have been trying to interface a 16x2 LCD to an Arduino Uno using an Intel 8255A component without any luck. The problem is, how can I attach or set the LCD's pins <> to the unknown pins of the 8255A.

Is it even possible?

Thanks for any kind of help.

You will not be able to use 8255 pins as parameters to the the LiquidCrystal library without making substantial changes to either the library or the Arduino core.

The reason is that to configure or change a pin on the 8255, you will need to go through a series of operations manipulating the ATmega pins to which the 8255's microprocessor bus interface is connected.  You can learn about the necessary operations by reading the 8255 data sheet.  Also keep in mind that the 8255 does not have per-pin configuration - rather, the first two ports must each be either entirely inputs or entirely outputs, while there third port can be split in half.

Once you know how to set a pin, you will need to have the liquid crystal functionality trigger these operations.

One approach would be to create a heavily modified version of the library which knows how to work through the 8255.

Another would be to create a modified version of the Arduino core which has additional pin numbers corresponding to the 8255's pins, and generates code which does the necessary intermediate bus operations to access them.  However this will be quite challenging - you have to make sure the intermediate code gets in there in all paths, and figure out how it will handle cases where code tries to set pins that must have the same mode to conflicting modes.

As others have said, you would practically be better off using a different MCU with more I/Os - either an Arduino Mega, or one of the ARM-based boards.


How can I transmit data to/from arduino from up to ~750 ft away? I am working on a design project for school (non-capstone non-electrical engineering project) where we are building a system to remotely control a winch on a boat that will lower an independently operating meter to specified depths using a pressure transducer (controlled from the shore).

My current idea is to have an arduino collecting data from the pressure transducer while being connected to the winch (adjusting it up/down as needed, based on the desired inputted depth). The arduino would then be connected to the a Raspberry Pi B via USB. The Raspberry Pi would then communicate via wifi USB adapter to a router @ 2.5 GHz 802.11n on the shore, which would then communicate with the laptop on the shore. The important thing is that the laptop on the shore will be recording data as well as changing the input depth for the arduino.

Arduino <==> Raspberry Pi <==> Router <==> Laptop on shore

I saw [this information][2] talking about connecting to an arduino via wifi, but I was unable to determine the potential range.

A related project using a boat that uses the Xbee shield.

Once concern is that we will not be able to specifically point any antenna on the boat back to shore, so we are looking for a non-direction-oriented solution.

I was wondering what potential ways I could communicate back to the shore to control the winch depth (output display on shore showing depth, then being able to change the depth from shore). Furthermore, I was wondering if my setup would be feasible and what your suggestions might be.

Thanks!

There are a number of considerations that need to be made when considering any wireless communication solution over long distances and over water.

WiFi is capable of working over long distances especially with higher power cards (1W ones are now readily available) and directional antenna (anything from 3dBi to 30dBi of gain). There are advantages and disadvantages to using WiFi like this for your purposes:

WiFi uses 2.4GHz which is attenuated by the presence of water and water vapour. If you are close to the surface of the water surface, this can cause variable range with weather conditions increasing humidity and spray - even slight choppiness can massively increase the humidity close to the surface.
WiFi is a fairly heavyweight protocol that has several layers that need setting up each time a connection is made. This takes time and means marginal connections will have zero throughput as they will never get setup.
WiFi is intended to have high throughput (>1MBps) and doesn't degrade gracefully below this point. There isn't often a need to shift data this fast on an Arduino project. Speed and range are a trade-off.
Directional antenna on boats can be hard work. The more gain an antenna has, the more directional it is, which in turn means you need to aim it better. Even mild rocking can make this difficult to impossible. It depends if you are on a smooth pond or the sea really.

If you do want to go with WiFi, Ubiquiti make some neat products like the Nanostation that allow long range connections to be set-up over long ranges.

Personally I would stay away from 2.4GHz near water, and go with one of the other ISM bands. Depending on your location, this could mean 315MHz 433MHz, 868MHz, or 915MHz. It depends which region of the world you are in which ones you are allowed to use.

These lower frequencies are suited to longer ranges and penetrating object and water. There are a lot of different solutions in this space, all of which have ups and downs.

The Hope RFM12B is a very popular small RF board that has several easy to use libraries available - I use Jeelib personally. These are just capable of the 750ft range you require. They are available in all most ISM bands, and personally I have found the 868MHz best outdoors, whilst the 434MHz is better indoors.

The newer Hope RFM69W is a similar board but with more functionality and more power. It has 13dBm (20mW) of power vs 0dBm (1mW) of power on the RFM12B. I have been seeing an increase in range of ~50-100% with these boards.

The RFM69HW is a high power version has 20dBm (100mW) of power. I haven't range tested this, but would expect up to 3-4 times the range of an RFM12B.

Ciseco, a UK company, also make a series of boards that use CC1110 chips as transceivers. These are in an XBee like form. One of their boards, the ARF, has a power amplifier. These have 26dBm output power (400mW) and in a brief test in a built up area, I have seen a range of about 2km.

It's important to note that these are transceivers so that they can send and receive, which means you can acknowledge if packets have been received.

There are boards like the nRF2401L which use 2.4GHz, but use a much lighter weight protocol than WiFi so work better on marginal ranges. They are dirt cheap (~£2). They have the same disadvantage of water impacting range.

I don't like Xbee at all. The boards are overpriced and I find the range isn't great even with the higher powered modules.

You could also "roll your own" and use simple 434/868/915MHz on-off-keyed (OOK) transmitter/receivers. Protocol design isn't easy though, and you lose a lot of hidden functionality that the more advanced boards have.


Send button only works when pressed immediately after I am new to Arduino and I am trying to create a Morse code based "chat".
I can submit a message in Morse code using the send button (the one on the right,) and when I press the button on the left and the whole decoded message should appear on the screen. However, this is not happening unless I press the send button immediately after introducing the Morse code. Can anyone help me out? I tried changing the delay period, but nothing seems to make it send how it should.
As I said, I am a beginner, so please go easy on me.
This is my code:
/* String tone = "-... ..- -. .- ";

  Morse code - Receiver

  modified on 14 Apr 2019
  by Saeed Hosseini @ Electropeak
  https://electropeak.com/learn

*/
#include <LiquidCrystal.h>
// Create an LCD object. Parameters: (RS, E, D4, D5, D6, D7):
LiquidCrystal lcd = LiquidCrystal(2, 3, 4, 5, 6, 7);
String code = "";
int len = 0;
char ch;
int ok;
char new_char;
int i1=0;
int i2=1;
const int but_send=8;
const int but = 12;
const int led = 13;
String a="";
unsigned long pres_len = 0, rel_time, pres_time = 0, old_time_len = 0, old_pres = 0, space = 0;
int state = 0;
int unit_delay = 250;
int min_delay = 10;
int buttonState = 0;

char MakeString()
{
  if (pres_len < (unit_delay*3) && pres_len > 50)
  {
    return '.';                        //if button press less than 0.6sec, it is a dot
  }
  else if (pres_len > (unit_delay*3))
  {
    return '-';                        //if button press more than 0.6sec, it is a dash
  }
}

void Morse_decod()
{
  static String morse[] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....",
                             "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-",
                             ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", "!"
                            };
  int i = 0;
  while (morse[i] != "!")
  {
    if (morse[i] == code)
    {
      Serial.print(char('A' + i));
      a=a+char('A' + i);
      //lcd.print(char('A' + i));
      Serial.print(" ");
      if(i2>=2)
      {
        i1++;
        i2=0;
      }
      else
      {i2++;
      }
      break;
    }
    i++;
  }
  if (morse[i] == "!")
  {
    Serial.println("");
    Serial.println("This code is not exist!");
  }

  code = "";
}
void sendText()
{
  Serial.println(digitalRead(but_send));
  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  //if (digitalRead(but_send) == HIGH) {
    // turn LED on:
     //gitalWrite(led, HIGH);
  if(ok==1){
    Serial.println(a);}
  ok=0;

    //}
  //else {
    // turn LED off:
    //Serial.println("NIMIC");
  //}
 delay(200);
}
void setup() {
  Serial.begin(9600);
  pinMode(but, INPUT_PULLUP);
  pinMode(but_send, INPUT_PULLUP);
  pinMode(led, OUTPUT);
  lcd.setCursor(i1, 12);
  lcd.begin(16, 2);

}
void loop() {
label:
  while (digitalRead(but) == HIGH) {}
  old_pres = rel_time;
  pres_time = millis();
  digitalWrite(led, HIGH);
  while (digitalRead(but) == LOW) {}
  rel_time = millis();
  digitalWrite(led, LOW);
  pres_len = rel_time - pres_time;
  space = pres_time - old_pres;
  if (pres_len > min_delay)
  {
    code += MakeString();
  }
  while ((millis() - rel_time) < (unit_delay * 3))
  {

    if (digitalRead(but) == LOW)
    {
      goto label;

    }

  }

  Morse_decod();
    delay(1000);
  if (digitalRead(but_send) == LOW)
  {
    ok=1;
    //Serial.println("A intrat aici");
    sendText();
    //delay(100);

  }

 //Serial.println(digitalRead(but_send));

}

This is what should happen all the time, not only after pressing the send button very fast:

If needed, I can send a link from my tinkercad simulation.

tavis’ answer nailed down your problem: your program is completely
unresponsive when it is blocked in the first while loop of the
loop() function. Here I will try to give you some hints on how to
avoid this situation, but first some general comments:

if (pres_len < (unit_delay*3) && pres_len > 50)

The threshold should be unit_delay*2, maybe with a longer
unit_delay. In Morse, a dot is one unit, and a dash is three units. If
you have to set a threshold, it should be somewhere in the middle.
Otherwise, a perfectly valid dash of 2.99 units would be mistaken
for a dot.
Also, a function returning anything but void should always return a
value. What is this function supposed to return if press_len is
smaller or equal than 50? And if it is exactly equal to
unit_delay*3? The best way to make sure you did not forget any case is
to have an else at the end that returns a default value in case no
condition matches:
else
    return '?';  // we could not understand

In this particular case, it seems to me like you already did the
debounce prior to calling the function, so it could be simplified to
char getSymbol()
{
    if (pres_len < 2 * unit_delay)
        return '.';
    else
        return '-';
}

Note that giving functions meaningful names is an important step in
making the code easy to understand and reason about.

if(i2>=2)
{
  i1++;
  i2=0;
}
else
{i2++;
}

All this serves no useful purpose, as you do not use i1 or i2 after
setup(). Removing useless stuff is also important for the clarity of
the code.

Serial.println("This code is not exist!");

It should say “I cannot understand this code!”, but it may well exist.
Now, to the core of the issue. If you want the program to be responsive,
you should embrace non-blocking programming. This means getting rid of
delay() (see Blink Without Delay) and getting rid of blocking
loops, like the two while loops at the top of loop(). A very useful
approach is to program your system as a finite state machine.
Please, take the time to read and digest these two resources.
Next, as an example, I can point you to a Morse decoder of mine that is
based on the finite state machine concept. You do not have have to look
at my code, which may be too low level for your taste, but look at the
documentation of the program internals. It explains how the state
machines are built and interact with one another. Below is a state
diagram taken from that documentation. It shows the state machine that
takes the debounced “rise” and “fall” events as inputs, and generates
“dot”, “dash”, “end-of-char” and “end-of-word” symbols as outputs:


Arduino protecting analog input with internal voltage reference Usually a common way to protect an analog input consists on reducing voltage and current in the following way:

Current limiting components, as Resistors or inductors and voltage limiting components as diodes, zener, tvs.

In this case for components availability I have used two resistors and a zener diode.

The circuits aims to accept a 0-10V input and read it with the internal reference voltage 1,1V.

The question is the following: Assuming I want to use a 2,2V zener diode as overvoltage protection and 1,1V internal voltage reference, can I consider it safe or the 2,2V of zener will be too much for the 1,1V reference?

simulate this circuit – Schematic created using CircuitLab

NOTES: I am using 2,2V zener diode because is the smallest size I can found.
I could use two normal diodes to reach 1,4V but maybe it will be too much for 1,1V reference and the result could be the same.
I could also add an external reference, but I would like to know if I can have problems with this configuration.

Yes, it is safe.  The reference voltage is only used as a comparison. The ADC is still powered by, and limited by, the chip's supply voltage (5V).

The AREF voltage has no bearing on what limits there are on voltages you can apply to a pin. All that will happen is that voltages above 1.1V will register as 1023. You can go right up to 5V safely.


Print output on 16x2 LCD and Serial Monitor I'm trying to print an int on both an LCD and the Serial Monitor, but its only being displayed on the LCD. The Serial Monitor is printing question marks.

Here is my Arduino code:

#include <LiquidCrystal.h>
LiquidCrystal lcd(1, 2, 4, 5, 6, 7);
int x = 10;

void setup()
{
  lcd.begin(16, 2);
  Serial.begin(9600);
}

void loop()
{
  x++;
  lcd.setCursor(0, 0);
  lcd.print(x);
  Serial.print(x); // print Serial
}

If you are using clasical UNO, then pins 0 and 1 are Serial. Declaring lcd(1,... make LCD use the pin 1 too, so Serial is confused and garbled.

Use other pins for lcd and adjuct the wires acordingly.


while(1) loop blocks program to enter interrupt I want to build a program in C that enables / disables a passive matrix display. But my problem occurs before I can even implement one function of this display.

I have a simple switch connected to Port C pin 24, which is configured as INPUT with a pull-up resistor and debouncing input filter. When I toggle the switch the code enters an interrupt and toggles the "display" on or of depending on the state of the switch.

Everything works fine until I introduce a simple while(1) loop, which should handle everything I want to do. But every time I write the function called run, which only contains one while(1) loop and a single dummy operation __asm__("nop"), the while loop prevents the code from entering the interrupt.

This is my code:

void display_init(void) {
    sysclk_init();
    delay_init(sysclk_get_cpu_hz());
    pmc_set_writeprotect(false);
    pmc_enable_periph_clk(ID_PIOC);
    NVIC_EnableIRQ(PIOC_IRQn);
    REG_PIOC_PER = SWITCH;
    REG_PIOC_ODR = SWITCH;
    REG_PIOC_OWDR = SWITCH;
    REG_PIOC_PUER = SWITCH;
    REG_PIOC_IFER = SWITCH;
    REG_PIOC_DIFSR = SWITCH;
    REG_PIOC_LSR = SWITCH;
    REG_PIOC_REHLSR = SWITCH;

    //Clear input change register to avoid immediate interrupt
    REG_PIOC_ISR;
    REG_PIOC_IER = SWITCH;
    run();
}

void run() {
    while(1) {
        __asm__("nop"); //Dummy operation for debugging
    }
}

void PIOC_Handler(void) {
    REG_PIOC_ISR;
    if(REG_PIOC_PDSR & PIO_PC24) {
        __asm__("nop"); //Breakpoint
    } else {
        __asm__("nop"); //Breakpoint
    }
}

As far as I know, an interrupt stops everything executed at the current time and starts working on the interrupt code. My question is now: Why is the interrupt not stopping the while loop?

Before I recognized this problem, I had a simple condition in the while loop that checks whether 1 or 0 to equals 1 when I set this state to 0, so the condition was 1 == 0 which should equal false. The loop did not stop and continued to run even if the condition for this loop was false... Is it possible that while loops do not like to be used in parallel with interrupts?

EDIT:

void main(void) {
    board_init();
    display_init();
}

I don't have an Arduino setup() function because I'm using Atmel Studio to ensure working at low Level, to avoid unnecessary code and to keep memory usage as low as possible.

The while loop should have no effect on interrupts. Where does run() get called? We'll need to see the code that sets up and calls the code you've shown. But as a sanity check, you could try replacing the entire contents of run() with a ;, that is make it an empty function. Then add in an empty while loop (contains only a ;, no __asm__ code) and try again. Then replace the body of the while loop with __asm("nop")__ and try again. At which of the above steps does your interrupt fail? That should lead you in the right direction.

Update:
What does your main() function do after display_init() returns? Because that won't ever happen when run() runs forever.

The job of main() is to create the C/C++ run-time environment. That may not have been completed (enabling interrupts, for instance) when display_init() and run() get called, but gets completed shortly after they returns - if run() is allowed to end.

Without seeing your main(), we can't know enough to be more specific, but I'd suggest you move all of your code out of main() and down into the Arduino setup() function because, by the time it gets called, the run-time environment will be complete.

Update 2:

  to avoid unnecessary code

If that is your entire main() function, you've left out the run-time environment setup and it's little wonder that your code behaves strangely. You've asked for help and we've made some suggestions: to show your entire code, not just selected pieces of it; and run your code in a standard way and let us know the result. Then you can optimize your code if you feel it's worth it to you. When you've done that test, and you still have questions, ask again. Until then, you're just asking us to guess. We did that. Once.


Motor controller for 24v motor, Arduino Uno I need a motor controller for a 24v motor and I want to control it using än Arduino Uno. Suggestions?

The motor needs to run both directions and is going to draw about 5A

try this Arduino Compatible Mega Motor Shield. Specs:

Low-cost robust H-bridge ''shield'' for Arduino
Provides the ability to control up to 30A of current at up to 28V
Supply voltage: 5V to 28V (24V max battery rating)
Continuous output current: 13A
Have, a look:


Connecting arduino with MATLAB I installed Octave support package for Arduino and it is listed in the packages installed when pkg list command is run.But when the command  "a= arduino('COM8')";
is run,"error: serial: Error opening the interface: No such file or directory" is shown.Please respond.

Using clear command on Octave before executing a=arduino('COM8') will remove this problem.
Use it like this:
clear
a=arduino('COM8')


Is it possible to obtain %0.05 duty cycle at 1hz in arduino?(a 500us square pulse at 1 sec period) I have a system which requires me to obtain different duty cycles at different frequencies. But using the analogWrite() does not allow me to obtain a value lower than 1/255 duty cycle. I need to obtain lower duty cycle values for 1Hz

Expanding from my comment. This is an attempt to generate that signal with Timer 1. No time to test it now... Edit: tested, works as advertised.

/*
 * Configure Timer 1 to generate a slow, low duty cycle PWM signal.
 * Output pin = digital 9 = PB1 = OC1A.
 */

const float PWM_PERIOD  = 1.0;     // 1 s
const float PULSE_WIDTH = 500e-6;  // 500 us

/*
 * With a 16 MHz clock and this prescaler, the resolution is 16 us and
 * the maximum period is 1.048576 s.
 */
const uint16_t TIMER_PRESCALER = 256;
const float F_TIMER = F_CPU / TIMER_PRESCALER;

void setup()
{
    // Configure Timer 1.
    DDRB  |= _BV(PB1);    // set PB1 = OC1A as output
    ICR1   = round(PWM_PERIOD * F_TIMER) - 1;
    OCR1A  = round(PULSE_WIDTH * F_TIMER) - 1;
    TCCR1A = _BV(COM1A1)  // non-inverting PWM on OC1A
           | _BV(WGM11);  // fast PWM mode, TOP = ICR1
    TCCR1B = _BV(WGM12)   // ditto
           | _BV(WGM13)   // ditto
           | _BV(CS12);   // clock at F_CPU/256 = 62.5 kHz
}

void loop() {}


Can I do something like this to simplify the code for arduino? Can I simplify the code in arduino where it doesn't promote any error.
Example:

Int led =13;
Blink = digitalWrite(led, HiGH);
             delay(1000);
             digitalWrite(led, LOW);
             delay(1000);

void setup(){
pinMode(led, OUTPUT);
}

void loop(){
Blink
}

There are indeed some errors.

First, you cannot assign a function body to a variable.

So you have to rewrite the Blink function:

void blink()
{
    digitalWrite(led, HIGH);
    delay(1000);
    digitalWrite(led, LOW);
    delay(1000);
}

Also for calling a function, even without parameters, you should use ( and ):

void loop()
{
    blink();
}

Also you need to use the correct capitals or not:

int led = 13;

You can make it constant since it does not change:

static const int led = 13;

So all together you get:

static const int led = 13;

void setup()
{
    pinMode(led, OUTPUT);
}

void loop()
{
    blink();
}

void blink()
{
    digitalWrite(led, HIGH);
    delay(1000);
    digitalWrite(led, LOW);
    delay(1000);
}

I suggest you read a book about C or C++ to get used to the syntax.

Also, note that int is written as int, not Int. Case matters.


ESP8266 Firmware Upgrade Can I upgrade my ESP8266 firmware by connecting the pins in Arduino Uno, or do I still need a USB UART to Serial?

Looking at the schematic of arduino UNO here you can see that Pin 0 and Pin 1 are connected to the same line of RX TX of the ATMEGA8U2. So in theory (and assuming the ATMEGA8U2 behaves like any usb to uart IC) if you remove or disable the ATMEGA328P, your arduino should behave like any cheap usb to serial. The way you can "disable" ATMEGA328P is by setting it in constant reset mode as explained here

By manually reseting and setting the esp into flashing mode, you should be able to upload the new firmware to it from arduino IDE for example by selecting the ESP device.

Two notes on this

1 - The TX line of the ATMEGA8U2 is the marked RX on arduino Uno board and RX line of the ATMEGA8U2 is the marked to TX on arduino Uno board. That means your ESP RX should connect to pin 0 on arduino and TX of ESP should connect to pin 1.

2 - You might need voltage level conversion on pin 0 as ESP is a 3.3V device although in schematic there is 1K resistor in that line


Which arduino should I start on to learn about it? I'm pretty interested in arduino and the things I can learn from it. Being that I'm new into this I wanted to know which model I should get that would be easiest to learn on and why. What does this model come with, how much, and reputable place where one can purchase this.

I would simply say: buy a startkit like this one.At the end it is not important which Arduino board you'll start. They are (almost) the same*. At the very beginning you can start with Uno or Nano and even Leonardo could be very good. Those boards are very similar and you can program them in the same. Even the pins location and designation is not really different.
The most important thing about Arduino is to understand how to work and program and interface such a board with the sensors. In this sense I would choose a Uno board (or even 2009) which is less expensive and very easy to find overall. I don't really know how much experience you have, but it is likely, at the beginning, that you invert polarities of batteries, you drain too much power, or you invert some pins and damage the microcontroller. In that case doesn't make sense to buy the last powerful mega expensive board on the mark. If you get a Uno you can do almost everything and have for the next month a lot to learn.

To change from Uno or Nano to the other board it is not very difficult. Once you understand the basis you can switch to every board you want. If you need more power and memory you can buy a Mega. If you need much more power you can buy a Due/Tre/etc...you need just an upgrade not everything from scratch to learn.

If you are really new to Arduino the best way is to buy such a learn package as I showed you above. That have everything you need to understand basic of programming till to RC-Servo movement and motor drivers.

Happy new year.

*: stay away for the moment from the Arduino Due/Tre/Zero/Yuan/.. series. they are too expansive and require a lot of attention (3.3V, max drain current from the pins, pull up, pull down...etc..). Here is the risk to get your board damaged within few time very high. And you'll spend a lot of time thinking that the board has some problems.


Unable to retrieve heart rate reading and send to JY-MCU Bluetooth Hello Arduino Community,

I am encountering an issue trying to retrieve a heart rate reading from an op-amp and instrumentation amplifier and sending it via Bluetooth.  I used this website as a basis of my design:  http://www.instructables.com/id/Electrocardiograph-Heart-Rate-Monitor/?ALLSTEPS.  I would appreciate it if you could take a look at that.  Here are a couple of pictures of my design.

Here is the code that I used:

    const int  signal = 7;    // Pin connected to the filtered signal from the circuit
    unsigned long time;
    unsigned long frequency;

    // Internal variables
    int period = 2000;
    int starttime = 2000;
    int input = 0;
    int lastinput = 0;
    unsigned long death = 0;

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

     void loop() {
       delay(1000);

       time = millis();
       input = digitalRead(signal);

       if ((input != lastinput)&&(input == HIGH)) {
       // If the pin state has just changed from low to high (edge detector)
       period = time - starttime; // Compute the time between the previous beat and the one that has just been detected
       starttime = time; // Define the new time reference for the next period computing
       death = time;
      }
      lastinput = input; // Save the current pin state for comparison at the next loop iteration

      if (period < 0) {
      frequency = 0;
      }
      else {
      frequency = 60000/period; // Compute the heart rate in beats per minute (bpm) with the period in milliseconds
      }

      if ((time - death) > 2000) { // Detect if there is no beat after more than 2 seconds
      Serial.println("dead");
      }

      else {
      char freq[3];

      if (frequency/100 == 0) {
       freq[0] = 32; // Print a space to the first character if the frequency is below 100 bpm
      }
      else {
       freq[0] = frequency/100+48; // Sort the hundreds character and convert it in ASCII
      }
       freq[1] = (frequency/10)%10+48; // Sort the thents character and convert it in ASCII
       freq[2] = frequency%10+48; // Sort the units character and convert it in ASCII

      Serial.print(freq);
      Serial.print("alive! ");
      }

      }`

But all I'm getting as output is 'dead'.  I am really starting to lose it here since I am a complete amateur with Arduino and circuitry.  For reference, I copied the design from this image from the website (this is just an enlarged version): http://www.instructables.com/file/FVBC6TYHOW0HQ7H/?size=ORIGINAL.  I would appreciate it if anyone could provide some extra guidance.

assuming your circuit works, your code has some serious issues. I rewrote the code for you and also provided a simplified circuit that I have tested and know works.  Instead of getting the pulse from the heartbeat detector circuit, we will simulate it on the Arduino by pulsing pin 2 periodically.

const int  signal = 7;    // Pin connected to the filtered signal from the circuit
unsigned long currentBeatTime;
unsigned long previousBeatTime;

unsigned long frequency;

unsigned long myBeatFreq;
unsigned long myBeat;

// Internal variables
unsigned long period = 0;
int input = 0;
int lastinput = 0;

void setup() {
    pinMode(signal, INPUT);
    pinMode(2, OUTPUT);
    Serial.begin(9600);

    previousBeatTime = millis();
    myBeat = previousBeatTime;
}

void loop() {
    if ( millis()-myBeat > myBeatFreq )
    {
      digitalWrite(2, HIGH);
      myBeat=millis();
    }
    else
    {
      digitalWrite(2, LOW);
    }

    input = digitalRead(signal);

    if ((input != lastinput) && (input == HIGH)) {
        // If the pin state has just changed from low to high (edge detector)
        currentBeatTime = millis();

        period = currentBeatTime - previousBeatTime; // Compute the time between the previous beat and the one that has just been detected
        previousBeatTime = currentBeatTime; // Define the new time reference for the next period computing
    }

    lastinput = input; // Save the current pin state for comparison at the next loop iteration

    // Detect if there is no beat after more than 2 seconds
    if ( (millis() - previousBeatTime) > 2000 )
    {
        Serial.println("dead");
    }
    else
    {
        if (period <= 0)
        {
            frequency = 0;
        }
        else
        {
            frequency = 60000/period; // Compute the heart rate in beats per minute (bpm) with the period in milliseconds
        }

        Serial.print(frequency);
        Serial.println(" : alive! ");
    }
}


Blend Micro uploading sketch I have just got the Blend Micro board.
After following the getting started tutorial I can't manage to upload sketches on the board. Now, in Arduino v. 1.0.6 I see the voices

Blend
Blend Micro 3.3V/8Mhz
Blend Micro 3.3V/16Mhz (Overclock) as in this picture:

While the L Led is switch on if I upload the sketch the TX and RX leds stay off. The modified Arduino IDE says "Done uploading". As port I choose /dev/tty.Bluetooth-Serial-1 and I don't see any other port and I think this is critical.

But if I open the Android BLE application BLE Controller, after tried to upload the BLEControllerSketch (from RBL_nRF8001 libraries) it finds the board but print the error No Response from the BLE Controller sketch. If I try with SimpleChat example and the SimpleChat Android application if finds the board but prints only "Hello World" and nothing else if I send strings from the android app.

Any kind of advice?

EDIT

I am on a Mac 1.8.5. I have tried also with Codebender, but anything change: I can't see the /dev/tty.usb* in the listed ports

Did you follow the setup exactly? In particular, did you modify main.cpp to have this:

#if defined(BLEND_MICRO_8MHZ)
    // As the F_CPU = 8000000UL, the USB core make the PLLCSR = 0x02
    // But the external xtal is 16000000Hz, so correct it here.
    PLLCSR |= 0x10;             // Need 16 MHz xtal
    while (!(PLLCSR & (1<<PLOCK)));     // wait for lock pll
#elif defined(BLEND_MICRO_16MHZ)
    // The CPU clock in bootloader is 8MHz, change to 16MHz for sketches to run (i.e. overclock running at 3.3v).
    CLKPR = 0x80;
    CLKPR = 0;
#endif

If not, what happens is once the sketch starts the USB stops working and you can't see the serial port due to the clock speed being incorrect. This is why you can only see /dev/tty.Bluetooth-Serial-1 in the port list.

Modify main.cpp according to http://redbearlab.com/getting-started-blendmicro
Press the reset button on the Blend Micro, then quickly select Tools -> Serial Port in the Arduino IDE. The Blend Micro serial port should be there because the boot loader is still running. It will be named like /dev/tty.usb????????
Select that serial port. Compile your code. Now press reset at the same time as pressing upload. Your sketch will upload and the serial port should now be present when the sketch is running.

Update: The Timing Tricks

Note: Blend Micro is basically the same as Arduino Leonardo.

This is the timing:

The reset button is pressed.
The ATMega32u4 restarts. It jumps to the bootstrap loader code.
The bootstrap loader starts up the USB as a CDC device (serial port) and waits for firmware upload instructions. (Pulsing L LED)
If no upload instructions are received within a certain time (8 seconds?), it jumps to the application code.
The application code starts up the USB as a CDC device again.However, since the oscillator (clock) on the Blend Micro is different to the Leonardo, it requires the modifications above, otherwise the USB clock will wrong, and the USB won't work.

If the modifications above were not done, Step 3 is the only time when the USB is working and the serial port can be selected in the Arduino software.


Problem Bootloading AVR328P-PU I executed the following steps in order to burn a bootloader into an  AVR328P-PU chip I acquired on ebay.

I have set up AVR328P-PU on a breadboard as described here: http://arduino.cc/en/main/standalone
I have uploaded the ArduinoISP sketch into Arduion Uno.
Connected the wires in a way described here http://arduino.cc/en/Tutorial/ArduinoToBreadboard ( the setup with external clock)
Chose "Tools -> Programmer -> Arduion as ISP" in the IDE.
Chose "Burn Bootloader" from the IDE.
Got and error avrdude: Yikes!  Invalid device signature., noticed that I connected the wires in the wrong order.
Fixed the wired, but still got the error:

avrdude: Version 6.0.1

     System wide configuration file is "C:\Program Files\Arduino/hardware/tools/avr/etc/avrdude.conf"

     Using Port                    : COM3
     Using Programmer              : stk500v1
     Overriding Baud Rate          : 19200
     AVR Part                      : ATmega328P
     Chip Erase delay              : 9000 us
     PAGEL                         : PD7
     BS2                           : PC2
     RESET disposition             : dedicated
     RETRY pulse                   : SCK
     serial program mode           : yes
     parallel program mode         : yes
     Timeout                       : 200
     StabDelay                     : 100
     CmdexeDelay                   : 25
     SyncLoops                     : 32
     ByteDelay                     : 0
     PollIndex                     : 3
     PollValue                     : 0x53
     Memory Detail                 :

                              Block Poll               Page                       Polled
       Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
       ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
       eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
       flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
       lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
       calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
       signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

     Programmer Type : STK500
     Description     : Atmel STK500 Version 1.x firmware
     Hardware Version: 2
     Firmware Version: 1.18
     Topcard         : Unknown
     Vtarget         : 0.0 V
     Varef           : 0.0 V
     Oscillator      : Off
     SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.06s

avrdude: Device signature = 0x000000 (retrying)

Reading | ################################################## | 100% 0.05s

avrdude: Device signature = 0x000000 (retrying)

Error while burning bootloader.
Reading | ################################################## | 100% 0.07s

avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
     Double check connections and try again, or use -F to override
     this check.

avrdude done.  Thank you.

My questions

I understand that this can be caused by poor breadboard quality. How can I test this hypothesis before buying new breadboard?
Could the wrong wiring from step 5 ruin the chip?

Being from eBay, I would assume the seller "bricked" the chip beyond his/her capability to fix.  Fortunately, you know about stack exchange!

My immediate suggestion is to find, borrow or build a high-voltage programmer.  This is a special programmer that can un-brick the chip no matter what's been done to it. The concept is easy, but you need to protect the programmer's pins from the 12v reset signal.

Googling "avr high voltage programmer" gives several useful links.
I'll get the actual links when I get back to a real computer.

Ok, so life got in the way, sorry about that.
This is the one I built which worked perfectly:
MightyOhm

However hooking up the AVR to a "high voltage programmer" is well documented in the data sheets.  These should be very much similar circuits on Google.


ATtiny84 vs ATtiny85 consumption I'm doing a comparative study between ATtiny84 and ATtiny85, and I found from the datasheet that ATtiny84 consumes less current, is that normal even if it is bigger in terms of size and number of pins? Am i wrong?

There are wide differences in power usage in AVR parts. Typically the "P" variants (for "picopower") are more optimized for low power usage, but there are also differences between different revs of the same part (for example the ATMEGA168PB uses slightly more power than the ATMEGA168PA during sleep) presumably becuase of different processes used to make the chips.

If you are looking for the lowest power possible, it will depend on how your application.  Do you spend most time running at full speed? Power down? Do you need a realtime-clock?

Don't forget about the ATXMEGA parts- they have some that have very low power when running a real-time clock from the internal "ultra-low power" oscillator.


Timer2 "Clear OC2B on Compare Match" not working as expected in CTC mode This is a follow up to my previous question.

I have Timer2 in CTC mode, with TOP=OCR2A set to 150 (with a prescaler of 8, giving a 75us timing interval).

The datasheet states that setting COM2B1 to 1 in TCCR2A will "clear OC2B on compare match" (= Arduino pin D3) when you are in CTC mode.

I would like to use this functionality to get a "pwm" signal with a period of 75us, with duty cycle determined by OCR2B. I realize that this is a very convoluted way of achieving this, but eventually I want to be continually be changing OCR2B to get a (rapidly) varying duty cycle.

In the compare channel A interrupt I would like to turn D3 high, relying on the "clear on compare match" feature of channel B to turn it low a small interval later.

I have the following minimal(-ish) example:

#define OCIEA 1
#define CA21 1

void setup() {
  // PD3 as output
  DDRD |= (1 << PD3);

  // Pause the timers so they sync up
  GTCCR = (1<<TSM)|(1<<PSRASY)|(1<<PSRSYNC); // Halt all timers

  // Reset timer
  TCNT2 = 0; // set timer2 to 0 (8-bit timer)

  // Enable CTC mode
  TCCR2A = (1 << WGM21); // Timer 2 in CTC (TOP = OCR2A)

  // Clear output pins on compare match
  TCCR2A |= (1 << COM2B1); // Clear OC2B on match

  // Set prescaler
  TCCR2B = (1 << CA21); // set timer 2 divisor to 8

  // Set output compare
  OCR2A = 150; // Determines TOP for Timer2

  // Determines the pulse width
  OCR2B = 75; // Timer 2 output B (controls OC2B = PD3 = D3)

  // Enable interrupts for timer 2
  TIMSK2 = (1 << OCIEA);

  // Set the timers going again
  GTCCR = 0; // release all timers
}

ISR(TIMER2_COMPA_vect)
{
  TCCR2A &= ~((1 << COM2B1) | (1 << COM2B0)); // Disable clear OC2B on match
  DDRD |= (1 << PD3); // Enable output
  PORTD |= (1 << PD3); // Output high
  TCCR2A |= (1 << COM2B1); // Enable clear OC2B on match
}

void loop() {

}

Ideally the ISR would just consist of PORTD |= (1 << PD3); but this does not give my desired 50% duty cycle, but apparently it's impossible to write to the pin with COM2B1 enabled, so I tried various combinations of disabling it and reconnecting the pin but all I am getting is a very, very short pulse. It looks like as soon as COM2B1 is re-enabled, the pin goes low, even though a compare match on channel B should not have happened yet.

Setting COM2B0 instead of COM2B1 works as expected: the pin toggles state (but this is not what I want).

Why does this not work the way I expect it to, and is there a way to get my desired behavior? Also, if this is not possible, what on earth is the purpose of the clear on compare match feature if you can't turn the pin on at all when using it?

I have discovered I can sort of get the behavior I want by setting COM2B0 instead of COM2B1 (toggle on match rather than clear on match) and forcing a compare match in the interrupt (toggling the pin off) so that later the "real" toggle on match will turn it off. However, this is not ideal (as if the real and forced match overlap, I would lose track of the pin's state), and I'm still wondering what the purpose of the clear on match functionality is if it just forces the pin low.

The PWM modes manage pin at both ends of the cycle.

The point of the CTC modes is that they manage the pin only at one end of the count, but allow you to manage the other end explicitly.

To manage both ends explicitly, you use normal mode.

To set the OC2B bit with FOC2B in the TCCR2B with your interrupt:

ISR(TIMER2_COMPA_vect)
{
  TCCR2A |=  (1 << COM2B0); // Set OC2B on Compare Match
  TCCR2B |=  (1 << FOC2B ); // Force Output Compare B OC2B
  TCCR2A &= ~(1 << COM2B0); // Clear OC2B on Compare Match
}


Arduino SIM900 No SMS received I tried the tutorial in this link

https://lastminuteengineers.com/sim900-gsm-shield-arduino-tutorial/

to send an SMS message using a SIM900 GSM shield

I completed the section to send AT commands successfully but I can't get
the Arduino Uno to send an SMS. Below is the output I get after doing AT command tests

Initializing...
AT

OK
AT+CPIN?

+CPIN: READY

OK
AT+CSQ

+CSQ: 6,0

OK
AT+CCID

8944500105191448516F

OK
AT+CREG?

+CREG: 0,5

OK
AT+COPS?

+COPS: 0,0,"T-Mobile "

OK
AT+COPS=?

+COPS: (2,"T-Mobile ","T-Mobile ","310260"),,(0,1,4),(0,1,2)

OK

and below are the responses from the SMS code

Initializing...
AT

OK
AT+CMGF=1

OK
AT+CMGS="+1mycellphonenumber"

> Last Minute Engineers | lastminuteengineers.com

so no response from the AT+CMGS command and NO SMS received.
Plug is 5V 2A.

Any idea what might be causing the issue?

Below is the code I used for the Setup() function

void setup()
{
  //Begin serial communication with Arduino and Arduino IDE (Serial Monitor)
  Serial.begin(9600);

  //Begin serial communication with Arduino and SIM900
  mySerial.begin(9600);

  Serial.println("Initializing...");
  delay(1000);

  mySerial.println("AT"); //Handshaking with SIM900
  updateSerial();

  mySerial.println("AT+CMGF=1"); // Configuring TEXT mode
  updateSerial();
  mySerial.println("AT+CMGS=\"+ZZxxxxxxxxxx\"");//change ZZ with country code and xxxxxxxxxxx with phone number to sms
  updateSerial();
  mySerial.print("Last Minute Engineers | lastminuteengineers.com"); //text content
  updateSerial();
  mySerial.write(26);
}

Changed my SIM card to Ting from Hologram and it worked just fine!


How to read data from a rotary encoder with ATmega328 I'm using a home made "bare bones" Arduino, made with the ATmega328, and I need to read angle data from a geared DC drill motor, turning at speeds between 0 and 450 RPM. This is so I can use it as feedback for an angle control system implemented on the Arduino.

I've not yet bought the encoder. I'm waiting until I find a suitable one which works easily with Arduino.

I have already written the control algorithm. I'm using state variable feedback, and the algorithm depends on a getAngle() function that I have not written yet. This function is inside an if statement that executes every 0.2 seconds. It needs to return the angle of the DC motor in degrees.

My questions:

How can I implement this getAngle() function using a rotary encoder?
What is an example of a rotary encoder that is suitable for this application?
Will it be better to use the interrupt pins of the Atmega328, or use some other method?

I have seen a few library's on Arduino Playground that claim to make reading angle data easier, but how do I use them? I need something that is fast (it, and the control algorithm operations, both needs to finish before the 0.2 seconds sample time), and more importantly it needs to be easy to implement. I'm coming up to the project deadline so I don't want to have to spend a whole day figuring out how to implement this getAngle() function.

Thank you!

You will have to use interrupts or otherwise the encoder might be rotating but your Arduino is doing something else than reading the encoder. By using interrupts, the encoder counter is always updated when the encoder moves. This also means that the interrupt function has to be very short so that it only takes a few cycles to complete and thus leaves the majority of the Arduinos computing time for your sketch.

Here is a code that I've used in many applications from CNC handwheels to servos and for reading extremely accurate angle sensors. It is dead simple, uses two interrupts to read the quadrature signal (A & B channel) and also makes use of Arduinos built in pull-up resistors to keep the channels held high for reliable readings.

Assuming that your encoder is an open-collector output and works with 5V, you only need to connect 5V and GND to it and then the A channel to the first interrupt pin #2 and channel B to #3. That's it for the hardware.

This code goes at the start of your sketch, right before setup() function:

const signed byte encoderDirections[] = {0, -1, 1, 0, 1, 0, 0, -1, -1, 0, 0, 1, 0, 1, -1, 0};
volatile long encCount = 0;

It defines a constant array that is used for finding the direction that the encoder has turned based on the previous value and the current value. It is defined as constant as it is never changed. Also a global variable calle encCount is defined as a long type variable so that the encoder can count in both directions. It is absolutelu imperative to declare it as volatile so that the compiler and the microprocessor never try to do any "shortcuts" when you use this variable, but instead always loads it from its respective memory address. This is done so because the interrupt can fire at any time and change the variables value without any other function knowing it.

Next, in your setup() function you will want to include these lines to make the Arduino pins as inputs with the internal pull-up resistors connected. The latter two lines attach the interrupts 0 & 1 (hardware pins pins 2 & 3) so that whenever the pin state changes (low to high or vice versa), it halts the microprocessors operation and jumps to the encoder_interrupt function immediately.

pinMode(2, INPUT_PULLUP);
pinMode(3, INPUT_PULLUP);
attachInterrupt(0, encoder_interrupt, CHANGE);
attachInterrupt(1, encoder_interrupt, CHANGE);

Last you will need the actual interrupt function that reads the encoder and updates the counter value.

void encoder_interrupt() {
  static unsigned int oldEncoderState = 0;
  oldEncoderState <<= 2;
  oldEncoderState |= ((PIND >> 2) & 0x03);
  encCount += encoderDirections[(oldEncoderState & 0x0F)];
}

First this defines a variable that holds the previous encoder value that was read from the pins 2 & 3. This is declared as static, so the value is stored in memory even when this function exits so that it can be used the next time the interrupt routine is run.

The second line moves the previous interrupt channel values two bits to the left (multiply by 4) to make room for the new values.

The third line is an interesting one. It reads the PIND, meaning all the pins at D register, which holds many Arduino pin states, including the pins 2 & 3 that we are interested in. Next it shifts this value 2 bits to the right (divide by 4) to "drop" the pin 2 & 3 states to the lowest bits of this byte. Then it AND's this byte with 0x03 to zero everything else but the lowest two bits that now contain the interrupt channel states. Lastly these two bytes are OR'd with the previous encoder state values to obtain a 4 bit number.

On the forth line this 4 bit number is AND'd with a 0x0F to make sure the highest 4 bits are zero to make sure this number is truly a 4 bit number that stays between 0..15, as it is used as an index for the constant array we defined at the start of the program to get the encoders direction of rotation and this is then added to the counter variable.

And now you have an accurate and extremely fast way of reading a two channel encoder to keep track of its position.

If you want to calculate an angle from the encoders current position, you could do a function like this, but you have to know the line count of your encoder and multiply it by 4 so you know the encoder pulse count per revolution. For example, a 100 line rotary encoder gives out 400 pulses per revolution. I assume that there is a constant defined as follows at the start of program:

const int LINE_COUNT = 400;

Also, this function assumes that the encoder could have turned more than one revolution and you just want the angle from some reference spot in degrees. Do take in to account that the long type variable will overflow after +-2 147 483 648 pulses as it is a 32 bit signed variable.

float getAngle() {
  long curCount = encCount;  // Store the current count.
  while(curCount < 0) {
    curCount += LINE_COUNT;
  }
  while(curCount >= LINE_COUNT) {
    curCount -= LINE_COUNT;
  }
  return (curCount / LINE_COUNT * 360.0);
}

First the encoder count is copied to a one use variable. then two while statements make sure the values is positive from 0 to LINE_COUNT-1, so it basically reduces the count to what it would be with just under one revolution. Then it returns the number of degrees by calculating the current position as a fraction of a one revolution count and multiplies this with 360 to get the degrees.


I am making a rubber band gun but i cant seem to get the button to work with my code to turn the servo? #include <Servo.h>
const int buttonPin = 3;
int buttonState = 0;

Servo myservo;
void setup() {
    myservo.attach(2);
    pinMode(buttonPin, INPUT);
}

void loop() {
    buttonState = digitalRead(buttonPin);
    if (buttonState == HIGH){ myservo.write(90); }
    else { myservo.write(155); }
    delay(1000);
}

Just put your button between pin3 and GND, and use the internal pullup resistor like this:

#include <Servo.h>
const int buttonPin = 3;
int buttonState = 0;

Servo myservo;
void setup()
{
    myservo.attach(2);
    pinMode(buttonPin, INPUT_PULLUP);
}

void loop()
{
    buttonState = digitalRead(buttonPin);
    if(buttonState == LOW)
    {
      myservo.write(90);
    }
    else
    {
      myservo.write(155);
    }
    delay(1000);
}


How to scale a bitmap (uint8_t array) in Arduino? So I have a project where I send text to an Arduino, which is then printed out as a QR code on a thermal printer that can take a bitmap image with a given width and height.

Is there a way I can "scale up" the "image," making it so one pixel is scaled up to 4 or 8 pixels?

Additionally, would it be possible to add a "quiet zone" of sorts on the left side of the image, as I am not able to offset/justify it to the middle.

QR Code lib: https://github.com/ricmoo/QRCode

Thermal printer lib: https://github.com/adafruit/Adafruit-Thermal-Printer-Library

You didn't tell use the size of your QRCode, nor the type of Arduino you
are using. So I am just going to guess that your problem is that you may
have enough RAM to store the raw QRCode, but not enough to store a
scaled bitmap version.

The Adafruit tutorial for their thermal printer library suggests
printing bitmaps with the method:

printBitmap(width, height, tablename)

where tablename is an array holding the bitmap data. This will
obviously not work if you don't have enough RAM to store the array.
Fortunately, there is an overloaded method:

void Adafruit_Thermal::printBitmap(int w, int h, Stream *fromStream)

that allows you to stream the image data instead of preparing it in RAM.
You can create a stream that delivers arbitrary data by writing a class
that derives from Stream. Here is a tentative, untested
implementation, that delivers a scaled-up QRCode one pixel at a time:

// Stream a scaled QRCode one pixel at a time.
class QRCodeStream : public Stream
{
public:
    QRCodeStream(const QRCode &code, uint8_t scale = 1)
    : qrcode(code), scale(scale) {}

    // Output: writing to this stream is a no-op.
    size_t write(uint8_t) {}
    void flush() {}

    // Input delivers the QRCode pixels.
    int available();
    int peek();
    int read();
private:
    QRCode &qrcode;
    uint8_t scale;
    bool done = false;
    uint8_t code_x = 0;  // coordinates of the QRCode module
    uint8_t code_y = 0;
    uint8_t pix_x = 0;  // pixel coordinates within the module
    uint8_t pix_y = 0;
};

int QRCodeStream::available()
{
    // For simplicity, pretend the bytes come one at a time.
    if (done) return 0;
    else return 1;
}

int QRCodeStream::peek()
{
    if (done) return -1;
    if (qrcode_getModule(&qrcode, code_x, code_y)) {
        return 0;  // black
    } else {
        return 255;  // white
    }
}

int QRCodeStream::read()
{
    if (done) return -1;
    int data = peek();

    // Move to the next pixel.
    if (++pix_x >= scale) {
        pix_x = 0;
        if (++code_x >= qrcode.size) {
            code_x = 0;
            if (++pix_y >= scale) {
                pix_y = 0;
                if (++code_y >= qrcode.size) {
                    done = true;
                }
            }
        }
    }

    return data;
}

This would be used as

printer.printBitmap(width, height, QRCodeStream(qrcode, scale));

Note that QRCodeStream delivers the image data as 8-bit gray scale,
where each pixel is returned as one byte, either 0 (for black) or 255
(for white). This is likely not the format expected by the thermal
printer library, which seems to expect 1-bit black and white data, with
8 pixels packed in each byte. You will have to adapt the code for
the right format, which will likely be tedious, but not overly complex.
I leave that “as an exercise to the reader”.


Leonardo-based tachometer? I'm new here. I'm not a native speaker, so pardon my English.

I just received my Arduino Leonardo today. I tried some basic calculations and stuff like blinking and LCD interfacing. Its interesting.

I am now trying to make a tachometer with the Leonardo. I'm following this tutorial.

I guess the board they've used differs from the Arduino Leonardo (ie pin 3 is interrupt0 in the Leonardo but it is pin 2 in the Arduino Uno board used in the tutorial). I tried changing the pins on the program and reconnecting the circuit but it doesn't work.

This is the code from the tutorial:

/* Optical Tachometer
 *
 * Uses an IR LED and IR phototransistor to implement an optical tachometer.
 * The IR LED is connected to pin 13 and ran continually.
 * Pin 3 (interrupt 0) is connected across the IR detector.
 *
 * Code based on: www.instructables.com/id/Arduino-Based-Optical-Tachometer/
 * Coded by: arduinoprojects101.com
 */

int ledPin = 13; // IR LED connected to digital pin 13
volatile byte rpmcount;
unsigned int rpm;
unsigned long timeold;
// include the library code:
#include <LiquidCrystal.h>
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);

void rpm_fun() {
  //Each rotation, this interrupt function is run twice,
  //so take that into consideration for calculating RPM
  //Update count
  rpmcount++;
}

void setup() {
  lcd.begin(16, 2); // intialise the LCD
  //Interrupt 0 is digital pin 2, so that is where the IR detector is connected
  //Triggers on FALLING (change from HIGH to LOW)
  attachInterrupt(0, rpm_fun, FALLING);
  //Turn on IR LED
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, HIGH);
  rpmcount = 0;
  rpm = 0;
  timeold = 0;
}

void loop() {
  //Update RPM every second
  delay(1000);
  //Don't process interrupts during calculations
  detachInterrupt(0);
  //Note that this would be 60*1000/(millis() - timeold)*rpmcount if the interrupt
  //happened once per revolution instead of twice. Other multiples could be used
  //for multi-bladed propellers or fans
  rpm = 30*1000/(millis() - timeold)*rpmcount;
  timeold = millis();
  rpmcount = 0;
  //Print out result to LCD
  lcd.clear();
  lcd.print("RPM=");
  lcd.print(rpm);
  //Restart the interrupt processing
  attachInterrupt(0, rpm_fun, FALLING);
}

Can anyone help me to fix the project? Has anyone here tried this project before?

Thank you!

First, make sure that your LCD routines and wiring are working, by trying to display something on it.
Second, the code isn't correct - it will have some fluctuations from one measurement to another.
One way to do it is to start timing only after the first pulse has arrived, and stop timing only after the last pulse has passed.
Something like this:

Wait until a falling edge.
Time0 is millis().
Wait for N pulses to pass.
Time0 is millis() minus time0.

Now with time0 and N you can calculate your rpm.
Edit:
Here is the above code at work, running Arduino on a PIC24.

The input signal is 10Hz, 1 pulse per revolution, aka 600 rpm.
As you can see the rpm read-out is precisely 600rpm. I'm running the code at 8x oversampling.
As I indicated earlier, your code will introduce uncertainty, as much as one period for the pulses. So in a single pulse measurement, the rpm can be anywhere from 0.5x of the true value to 1.0x of the true value.


Can't get call / message from A7 gsm+gprs+gps module I am making a project using arduino uno & A7 gsm+gps+gprs module.my circuit connection is like this:

A7 UTXD -> arduino RX
A7 RTXD -> arduino TX
A7 GND -> arduino GND
A7 pwr_key -> A7 VCC5.0

When i make call from my mobile to A7,it's ok.But i cannot get call/msg from A7.
Here is my code for making call:

char phone_no[]="phone_no";

void setup()
{
Serial.begin(9600);
delay(200);
Serial.println("AT");
delay(1000);
Serial.print("ATD");
Serial.println(phone_no);
//Serial.println(";");
delay(10000);
Serial.println("ATH");
}

void loop()
{
}

What can i do now??? Please help me to fix it.I apologize for my poor english.

Increase your second delay to 2000 (ie. 2 seconds).

delay(2000);


How to read code from Arduino Uno to Arduino IDE? we can upload a code into Arduino UNO from our computers, but how about reading code? Can we read and get C codes from compiled codes from Arduino hardwares? My second question is that will we read these compiled codes on Arduino ZERO's debug port, which will be a new product for us as developers?

Can we read and get C codes from compiled codes from Arduino hardwares?

While it is possible, even trivial, to disassemble machine code, it is very difficult to convert the assembly code into a higher-level language, and essentially impossible to turn it back into an exact copy of the source code it came from. There simply isn't enough information in the machine code to do so.

  My second question is that will we read these compiled codes on Arduino ZERO's debug port, which will be a new product for us as developers?

The debug port will work in tandem with appropriate software that will already have access to the source code, so this is not a method for conversion either.


Convert string to array I have a project and i need to convert string (contain numbers and letters) to array
String name = "s111, s222, bbbb,cccc ";

and i want
array[0] = s111;
array[1] = s222;
array[2] = bbbb;
array[3] = cccc;

here is the code :
 String name = "s111, s222, bbbb,cccc ";
 int array[50];
 int r=0,t=0;

 for(int i=0;i<name.length();i++){
      if(name.charAt(i) == ','){
          array[t] = name.substring(r,i);
          r = (i+1);
          t++;
         }
 for(int k=0 ;k<=t ;k++){
   Serial.println(array[k]);
  }

When I compile I get just zeros like :
array[0] = 0;
array[1] = 0;
array[2] = 0;
array[3] = 0;

When you declare int array[50]; you declare an array of numbers so only numbers can be stored inside it. If you really want an array of strings then declare an array of strings like String array[50]; There was also a a problem that sometime you split the name by comma, sometime by space, and sometime by comma+space. Also your code was missing closing bracket.
The algorithm has to split both by comma and my space and then take only values that have length more than one to avoid inserting empty strings.
String name = "s111, s222, bbbb,cccc ";
String array[50];
int r=0,t=0;

for(int i=0;i<name.length();i++)
{
  if(name[i] == ' ' || name[i] == ',')
  {
    if (i-r > 1)
    {
      array[t] = name.substring(r,i);
      t++;
    }
    r = (i+1);
  }
}

for(int k=0 ;k<=t ;k++)
{
  Serial.println(array[k]);
}


Can't burn Bootloader on Atmega328P Using Arduino Uno I'm trying to create an Arduino Uno following the circuit described in the diagram below which I'd based from here.

I'd tried this circuit on an Atmega328 PDIP version (with the correct connections since the PDIP has different pinouts from this TQFP) and I was successful in creating and using my own Arduino.

However, when I've used the TQFP version and had this circuit layout and printed on a pcb, I can't burn the bootloader using an Arduino UNO.

I've double checked the pinouts from the Atmega328P datasheet and they are correct. Using a tester, I've also verified that the connections are there.

By the way, I've used the following connections.

Arduino Digital Pin 13 to SCLK
Arduino Digital Pin 12 to MISO
Arduino Digital Pin 11 to MOSI
Arduino Digital Pin 10 to RESET
Arduino 5V to VCC
Arduino GND to GND

I've also burned the ArduinoISP program on th Arduino UNO, selected Arduino as ISP and chosen Arduino UNO as board.

When I press 'Burn Bootloader', I'm getting this error message.

avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
     Double check connections and try again, or use -F to override
     this check.

I've looked at different forums and they are only saying to check the connections which I'd already checked that there is.

I have had this problem in the past and it has always been one of two solutions

The wires were misconfigured, and I only saw it after the Nth time
Wrong chip, I was trying to program a 328 when it expected a 328p

And the secret third option:

Some chip/wire/etc. was busted/burned/bad.

Unfortunately These were the only outcomes to ever come for me when I encountered that particular error.


Connecting Arduino Mega + SIM800L to a car battery I need to make a car tracker powered from a car battery. The problem is the SIM800L needs to be powered with 3.8v to 4.2v, and at 2A preferably. I want to connect the car battery to my Mega first then the Mega powers the SIM800L.

So:

Car battery > Mega > SIM800L

What do I need to achieve this?

This is the SIM800L model:

With this setup you are overstressing the onboard regulator, while wasting a lot of power (not suggested on a battery setup, even if the battery is quite big).

First of all, the power. You have a MEGA, which runs at 5V/few mA, and a SIM800L, which runs at 4V/2A. I suggest you to have two power supplies. On ebay you can find cheap XL4015 converters rated at 5A. You connect IN+ to the +12V, IN- to the ground, then set the first one to output 5V, while the other to 4V. If you want to have the most correct powering scheme connect the 5V to the USB port, otherwise connect it to the +5V pins (note that you will exclude the fuse).

Then there is another problem: the UART levels. As a first approximation you can hope that the arduino reads the correct levels, so you'll just have to lower the TX voltage from 5V to 3.3V. You can do this by using a voltage divider with a 4.7k resistor between arduino TX and SIM RX and a 10k resistor between SIM RX and ground (see, for instance, how they did it in this image).


How to fix 12V RGB LED Strip connection to NodeMCU? I am trying to hook 12V RGB Led Strip (LTROP SMD 5050 RGB LED Light Strip) to a NodeMCU unit. I know there are many different tutorials on this and I am very new to wiring and electric circuits.

I used BUZ91A n-MOSFETs and 150 Ohm resistors for each of the RGB channels, and the board is using it's own power supply via usb.

I use very simple code to check if the setup works:

#define REDPIN D3
#define GREENPIN D1
#define BLUEPIN D2

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

void setup() {
  pinMode(REDPIN, OUTPUT);
  pinMode(GREENPIN, OUTPUT);
  pinMode(BLUEPIN, OUTPUT);
  Serial.begin(115200);
  Serial.println("Finished setup");
}

void loop() {
    analogWrite(REDPIN, 800);
    analogWrite(BLUEPIN, 1020);
    analogWrite(GREENPIN, 400);
    delay(100);

  Serial.println("Finished loop");
}

I suspect nothing works because NodeMCU and the LED are using different power sources and the fact they have common ground doesn't seem to be everything required.

So now we finally know the reason is MOSFET's threshold voltage is too high. The solution is to drive the gate with NPN transistor (you can use BC547 or 2N5551 or similar). You have to connect it's collector to 5 V and it's emitter to GND. Put 10k or 100k resistor between 5 V and the collector, connect the collector to MOSFET's gate and GPIO to the base of NPN transistor. Put some resistor between GPIO and the base of the transistor, maybe 4k7 or similar.

Note:
HIGH from GPIO will switch off the LED strip and LOW will switch it on.

Another solution is to use MOSFET with lower threshold voltage.

EDIT:
If you want to avoid adding NPN transistor you can use NTD5867NL MOSFET which has max threshold voltage 2.5 V so it will for sure work with 3.3 V at the gate but is rather expensive (about $4). Much better solution is adding cheap NPN transistor.

EDIT:
Here is the schematic:

simulate this circuit – Schematic created using CircuitLab

EDIT:
Here is the correct wiring:


How to interface OV5640 to Arduino Mega using Embedded C? I am trying to interface a OV5640 camera module to Arduino Mega 2560 in Eclipse IDE using C language . However I am not able to figure out the registers that need to be initialised , for the camera to start capturing pictures .

There are Arduino libraries to deal with setup and image transfer , however I do not wish to use them . I would like to code in C , without using any library . I just need to know which registers need to be accessed and modified to get the camera working .

For reference - I am trying to create a CCTV based system that will record picture based on intruder presence . The entire project is written in C language without any libraries .

Data sheet for OV5640 -https://cdn.sparkfun.com/datasheets/Sensors/LightImaging/OV5640_datasheet.pdf

Take a look in this link to get an idea about the kind of program it'll be.
How to get 38 Khz clock from Timer 0/2 in Arduino Mega 2560?

Arducam gives you all the info you need on the necessary register settings. The register values for each color space and resolution are defined in this header while the initialization sequence, image format selection and image capture process among other stuff, are implemented here and documented if you look closely at the variable names and compiler directives.

EDIT: More details

Lines 327 - 372 contain the relevant initialization sequence for this specific camera. For instance, assuming you want JPG images, line 335 marks the start of the needed settings:

delay(100);
wrSensorReg16_8(0x3103, 0x11);
wrSensorReg16_8(0x3008, 0x82); delay(100);
wrSensorRegs16_8(OV5640YUV_Sensor_Dvp_Init); delay(500);
wrSensorRegs16_8(OV5640_JPEG_QSXGA);
wrSensorRegs16_8(OV5640_QSXGA2QVGA);
wrSensorReg16_8(0x4407, 0x0C);  # assuming you arent using the Arducam shield or OV5640 5MP Plus

What wrSensorReg16_8 does is pretty obvious: write the 8-bit 2nd argument into the register specified in the 16-bit 1st argument. wrSensorRegs16_8 merely does the same thing for multiple register-value pairs passed into it. OV5640YUV_Sensor_Dvp_Init, OV5640_JPEG_QSXGA and OV5640_QSXGA2QVGA are all structs defined in the header I mentioned earlier; they contain the rest of the register-value pairs you need to know about. Ultimately, these settings should give you 320x240 JPEG, I think.

You can't use the start_capture method since you don't have the ArduCAM FIFO so you'll have to start grabbing frames yourself (and buffering them somewhere very quickly; transmitting the bytes as you read them is out of the question) by paying attention to VSYNC, HREF and PCLK. Look at the timing diagrams in the datasheet. I assume you'll only be taking frames occasionally since a Mega won't do for video. If you're very lucky, you'll get a nice image on your first try but on the whole, be ready to spend serious time studying the datasheet, ArduCAM code and other 0V5640-related code on the web or just go with the OV7670 which has more examples/tutorials.


Regarding the USB port, what is the difference between Uno/Mega and the older boards? I would like to know what the exact difference is between the Uno and Mega boards and the older boards (Duemilanove, Diecimila, etc.).  Why do I need to install a FTDI driver for the older boards, and not for the Uno/Mega boards?  I was in a class the other day, using the Nano, and the lecturer recommended the FTDI drivers. The Nano is a newer type board, so why does that require a driver? I've just discovered that the Nano is old tech from 2008, after reading Are there any reasons to pick Nano over Micro?

What is it about the Uno and Mega boards that don't require the FTDI to be separately installed?

I see that the Getting Started w/ Arduino on Mac OS X page states that the older boards use the FTDI chip. Does that imply that the Uno/Mega boards do not? If they do not, then what do they use?

I have a vague notion that some USB sticks, keyboards, mouse and other various USB devices may contain a driver within the circuitry/firmware(?) of the device, which when connected to a PC for the first time, can be used to install the driver without the PC needing to access the web for the driver. Is this what the difference is between the UNO/Mega and the older devices? If so, is it possible to modify, or flash the firmware of the older boards so that they can connect without the need for an FTDI driver?

The older Arduino boards used an FTDI FT232R chip to handle the USB port. This chip is a special purpose, USB to serial UART interface.

In the current Arduino boards, the USB to serial conversion is handled by dedicated Atmel Atmega8u2 processor. This is a processor that is similar to the main ATmega328p processor, but the added benefit of having built-in USB capabilities.

So, why the change? Well, first, it's cheaper than the FTDI chip, and second, it can do much more. Being that it's an actual microprocessor, you can actually reprogram this chip to behave like different USB devices. For example, you can reprogram it to make your Arduino look like a keyboard, a joystick, a thumb drive, a MIDI instrument - anything that you can do via USB. The FTDI chip does not have this capability, and so it can only ever look like a serial COM port to your PC.

Why have 2 microprocessors on the Arduino? By having a dedicated processor to handle the USB communication, it keeps the main processor free to run your sketches. Plus, the Arduino team felt that this design keeps the Arduino more "hackable".

Wouldn't it be cheaper to make a board using just the one processor that has built-in USB? Yes! That is exactly what the Arduino Leonardo is. It uses the Atmega32U2, the big brother to the Atmega8U2.


How to create an array from serial.read? I'm working on a audio-reactive lightinstallation with 16 LED lights.
In Max MSP I analyse my audio and split the frequencies in 16 'parts'.
I store these parts in a message of 16 ints, either 1 or 0 (on of off).
Every time a new frequency is detected the message updates and puts out a new int from 16 numbers (for exampe 1000100100110101).

I receive this number in my serial monitor of my Arduino Uno.
I want to put this 'incomingValues' in an array so I can check if a number/frequency is 0 or 1. When it's 1 I can turn on my relay/ light.
The 'incomingValues' is changing quite quickly but that shouldn't be a problem right?

I tried multiple things to create an array and update this every time a new serial message is coming in but I'm not used to work with Arduino so I could need some help.

Thanks! :)

Here is my code:

int counter;
int incomingValues = 0;
int lights[16];

void setup() {
  Serial.begin(9600);
  counter = 0;
  pinMode(13, OUTPUT);
}

void loop() {

  boolean newValue = false;

  while (Serial.available() > 0) {

    incomingValues = Serial.read();
    Serial.print(incomingValues);
    counter = counter + 1;

    newValue = true;
  }

  if (newValue) {
//    delay(50);
//    lights[counter] = incomingValues;
//
//
//    Serial.print(lights[0]);
//
//    for (int i = 0 ; i < 16 ; i ++) {
//      Serial.print(lights[i]);
//    }
//    Serial.println("");
//    newValue = false;
  }

  if (counter > 15) {
    counter = 0;
    Serial.print("\n");
  }

  if (incomingValues == 1) {
    digitalWrite(13, HIGH);
  } else if (incomingValues == 0) {
    digitalWrite(13, LOW);
  }
}

If you are able to send the message as 16 chars, followed by a newline, then here is a test sketch that might work for you. Use the Serial Monitor to send the 1000100100110101 data. Please ensure you have the Serial Monitor set to send a Newline Only.

// Valid input data from serial is 16 chars followed by a newline.
// 1000100100110101
const byte bufferSize = 17;
char inputBuffer[bufferSize + 1];

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

void loop(){

  if(Serial.available() > 0){
    byte bytesRead = Serial.readBytesUntil('\n', inputBuffer, bufferSize);
    if(bytesRead == 16){
      for(byte i = 0; i < 16; i++){
        if(inputBuffer[i] == '1'){
          Serial.print("on ");
        }
        else{
          Serial.print("off ");
        }
      }
      Serial.println();
    }
    else{
      Serial.println("Invalid data length.");
    }
  }
}


Can someone recommend a complete guide for learning Arduino? Am trying to learn Arduino so that I can teach my children.
Understand the basics of the coding and can do some simple projects like the ultrasonic reading etc. But I need a more complete, structure guide.

Any recommendations for books, video lessons, and projects would be appreciated.

Arduino Cookbook (I have 2nd edition) is worth its price in paperback. PDF/etc formats are available. Children like to dig in without deep theoretical preparations. IIRC it covers classes briefly, as well as bitmath. A nice book.

Boxall’s book is better still. A link: https://m.barnesandnoble.com/w/arduino-workshop-john-boxall/1114672111?ean=9781593274481

You don’t really need to do much except give the kids a laptop with no games on it, and a few arduino clones. Just lock the door to their room with a default-closed solenoid connected to an H-bridge. They’ll learn quickly.


How to get Arduino to talk to two seperate motors wirelessly? I have an Arduino Uno and I also have two Servo Motors. Say I have a room that is 15 feet wide, and I want to be able to place the Arduino in the center of the room and control two servo motors placed at each end of the room using a button on the Arduino. Is it possible to wirelessly communicate with these two servo motors using just one Arduino and bluetooth transmitters/receivers? Or will I have to use three Arduinos, one for the center with the button and one for each servo. If so, will I be able to substitute the two servo Arduinos with an ATtiny chip?

You'll probably need 3 "controllers", of which the one in the middle of the room might need to be a full-featured Arduino. Depending on the the needed libraries of your bluetooth receivers at the remote servos, it seems likely that you could use ATTinys in place of more feature-filled Arduino, but you would still have to think of the ATTinys as Arduinos or at least the glue controller to translate commands from Bluetooth to servo signals (PWM).

You could provide us with more details, such what particular bluetooth modules or transceivers you plan to use; some might provide an asynchronous serial interface, others might present an I2C or SPI interface, and given the small flash and RAM size in the ATTiny line, you would need to evaluate the code and associated libraries needed to operate it on such a processor.

The answer to your question is, "Maybe", given the small amount of detail you have provided.


Arduino Not Responding During Program I got an Arduino Uno to play around with, and started to actually dive in. During a program that I am writing for a friend, it suddenly stopped outputting to the serial monitor. When I comment out the part I added (the for loop for changing the names), it still doesn't respond.

#include <TrueRandom.h>
#include <EEPROM.h>
#define numPokemon 151
String nameArray[] = {"MISSINGNO","Bulbasaur","Ivysaur","Venusaur","Charmander","Charmeleon","Charizard","Squirtle",
"Wartortle","Blastoise","Caterpie","Metapod","Butterfree","Weedle","Kakuna","Beedrill","Pidgey","Pidgeotto",
"Pidgeot","Rattata","Raticate","Spearow","Fearow","Ekans","Arbok","Pikachu","Raichu","Sandshrew","Sandslash",
"Nidoran♀","Nidorina","Nidoqueen","Nidoran♂","Nidorino","Nidoking","Clefairy","Clefable","Vulpix","Ninetales","Jigglypuff",
"Wigglytuff","Zubat","Golbat","Oddish","Gloom","Vileplume","Paras","Parasect","Venonat","Venomoth","Diglett","Dugtrio","Meowth",
"Persian","Psyduck","Golduck","Mankey","Primeape","Growlithe","Arcanine","Poliwag","Poliwhirl","Poliwrath","Abra","Kadabra","Alakazam",
"Machop","Machoke","Machamp","Bellsprout","Weepinbell","Victreebel","Tentacool","Tentacruel","Geodude","Graveler","Golem","Ponyta","Rapidash",
"Slowpoke","Slowbro","Magnemite","Magneton","Farfetch`d","Doduo","Dodrio","Seel","Dewgong","Grimer","Muk","Shellder","Cloyster","Gastly","Haunter",
"Gengar","Onix","Drowzee","Hypno","Krabby","Kingler","Voltorb","Electrode","Exeggcute","Exeggutor","Cubone","Marowak","Hitmonlee","Hitmonchan","Lickitung",
"Koffing","Weezing","Rhyhorn","Rhydon","Chansey","Tangela","Kangaskhan","Horsea","Seadra","Goldeen","Seaking","Staryu","Starmie","Mr. Mime","Scyther","Jynx",
"Electabuzz","Magmar","Pinsir","Tauros","Magikarp","Gyarados","Lapras","Ditto","Eevee","Vaporeon","Jolteon","Flareon","Porygon","Omanyte","Omastar","Kabuto","Kabutops",
"Aerodactyl","Snorlax","Articuno","Zapdos","Moltres","Dratini","Dragonair","Dragonite","Mewtwo","Mew",
};
int a = 0;
int b = 0;
int value;
String pokemonName;
int currentID = TrueRandom.random(1,numPokemon+1);
// a = CurrentID
void setup(){
  Serial.begin(9600);
  if (EEPROM.read(a)!=0){
    currentID = EEPROM.read(a);
    Serial.print("The Stored ID is ");
    Serial.println(EEPROM.read(a));
    Serial.println("Stored = true");
  }else{
    value = EEPROM.read(a);
    Serial.println(value);
    EEPROM.write(a,currentID);
    value = EEPROM.read(a);
    Serial.println(value);
    Serial.println("Stored = false");
  }
  for (int i = 0 ; i < 152 ; i++){
      if (currentID = i){
        pokemonName = nameArray[i];
        Serial.print(pokemonName);
        break;
      }
   }
  //nameChange(currentID);
  //Serial.println(pokemonName);
}
void loop(){

}
void nameChange(int currentID){
   for (int i = 0 ; i < 152 ; i++){
      if (currentID = i){
        pokemonName = nameArray[i];
        break;
      }
   }
}

What is the problem with this code?

The primary reason that this isn't working is that you are using more RAM than the ATmega328 has (2Kbytes).

The array nameArray is huge. Each one of those characters is 1 byte, it's ~1.1k in itself. Add in Serial, TrueRandom and String, and you are over the limit. It could be you are right on the bounds and calling a single function pushes the stack over it's limit.

To save size, you can place the strings in flash. There is functionality to do this in Arduino, namely PROGMEM directive from underlying AVR-GCC and F() from Arduino. Making arrays of string is quite painful though, and using the Flash library helps here.

Personally I would avoid String for anything like this. The insides of String use dynamic memory allocation and when you are near the limits of RAM, it really isn't helpful. You lose a lot of ease of use by moving to arrays of char though.

You are also using assignment instead of comparison in your code:

if (currentID = i){
   pokemonName = nameArray[i];
   Serial.print(pokemonName);
   break;
}

This needs to be currentID == i.

I'm not confident what you are doing here though. If you want to get the i th element from the array, then just do

pokemonName = nameArray[currentID]

You also have an odd conditional at the beginning where you check for an EEPROM value being non zero, and then the else reads out the EEPROM value which by definition must be zero.

Also, you have a define for numPokemon but you aren't using it for the bounds on your for loops.


Testing Conditions on Port Bytes - ignoring certain bits? Being new to testing byte and bit conditions, I feel like there has to be a better way to test for conditions/values on a byte (read from a port).

For example, I'm reading 8 bits from PORTK. I need to test for a pattern of high bits. (Say, byte value of 207 - bits 7, 6, 3, 2, 1, 0 all high.) Bits 4 and 5 I don't care about. They CAN be high, or can be low. (Using datasheet terminology, they're "X - Don't Care".)

I could do an if, and test if the value equals 207, 223, 239, or 255, but that seems messy and like there would be an easier (and cleaner to read) way.

Edit to add: I've looked at Bit Operators, and .. something is telling me I should/could be using one of those. But I'm having a difficult time walking through which one would help me.

Thanks!
-Mike

You need to use boolean arithmetic.  Use the AND operator (&) to combine the incoming value AND the "mask" value (the value of the bits you do care about) and see if it equals the mask bit:

byte wanted = 0b11001110; // 207
byte incoming = 223; // for example 11011111

if ((wanted & incoming) == wanted) {
    // whatever
}

The AND operator compares each bit of the bytes in turn.  If they are BOTH 1 then the result is 1. Otherwise the result is 0.  So the above gives:

wanted:    11001110
incoming:  11011111
AND:       11001110

And the result matches "wanted". If you had some other value for incoming it could look like this:

wanted:    11001110
incoming:  01011011
AND:       01001010

And you can see that the result doesn't match.


How to send information from Arduino? I plan to make an air quality monitoring system that uses Arduino uno, but I can't decide how I will be able to distribute the air condition and harmful gas concentration info and have it available to other people.

Aside from using a GSM module to text individual persons and making a new website to chart the data from the Arduino, what else can I use to receive information that my Arduino sensed to people's smartphones/computers wirelessly?

what else can I use to receive information that my Arduino sensed to people's smartphones/computers wirelessly?

take a different route. get the information to a pc (or to a server through a pc) and you have much more flexibility.

there are many ways to get that information to a pc, like serial, spi, i2c, acquisition cards, wired / wireless, ....


Minimizing Digital input code I am making a device which can multiply the analog input signal with respect to the selected gain from the digital inputs. Here I have used two digital inputs(from which I can have four selections) but I am planing to add two inputs more(then I can have 16 selections). I made the code with if else statements is there any shorter way to do that? or else the code is getting huge.

here is the code:

#define sensor A0
#define resetPin 3
#define measurePin 2
#define k1 3
#define k2 4

float A = 0;
float J = 0;
int resetstatus = 0;
int measurestatus = 0;

void setup() {
  Serial.begin(9600);
  pinMode(sensor,INPUT);
  pinMode(resetPin,INPUT_PULLUP);
  pinMode(measurePin,INPUT_PULLUP);
  pinMode(k1,INPUT_PULLUP);
  pinMode(k2,INPUT_PULLUP);
  Serial.println("INITIALAIZING");
  delay(3000);
  Serial.println("Ready to begin");
  delay(200);
  }

void loop()
{
  resetstatus = digitalRead(resetPin);
  measurestatus = digitalRead(measurePin);
  if(resetstatus == LOW)
  {
    reset();
    delay(200);
  }
  if(measurestatus == LOW)
  {
    if(digitalRead(k1 == LOW) && digitalRead(k2 == LOW))
    {
    J = 1.0;
    measure();
    delay(50);
    }
    else if(digitalRead(k1 == LOW) && digitalRead(k2 == HIGH))
    {
    J = 2.0;
    measure();
    delay(50);
    }
    else if(digitalRead(k1 == HIGH) && digitalRead(k2 == LOW))
    {
    J = 3.0;
    measure();
    delay(50);
    }
    if(digitalRead(k1 == HIGH) && digitalRead(k2 == HIGH))
    {
    J = 4.0;
    measure();
    delay(50);
    }
  }
}
void measure()
{
  A = analogRead(sensor);
  float sumA = A * J;
  Serial.println(sumA);
}
void reset()
{
  Serial.println("reset");
}

I am having a problem with the output from this code
(I am using a potentiometer to feed the arduino an analog value)

I dont know why the output is showing 993 and 3972 at each cycle. can someone explain?

This is wrong:

if(digitalRead(k1 == LOW)

You mean:

if(digitalRead(k1) == LOW

Ditto for a lot of other places in your code.


How to use voltage divider between ESP8266 (3.3v) and IR proximity sensor (5V)? I am a software developer and I don't know much about circuits so I need help.

I have an ESP8266 (esp-12) 3.3V and I'm planning to use it with an IR proximity sensor (runs between 4.5-5V). I have 2 AA batteries (3V total) and 4 AA (6V total) power supplies. Also, I have a bunch of 10K Ohm and 330 Ohm resistors.

How can I use a voltage divider to supply sufficient voltage to these components, based on what I have? If it would help, I have a 100uF capacitor and I use a CP2102 to TTL Serial Converter to program. Any help will be appreciated. Thank you in advance.

My experience with esp8266 tells me that if you power esp8266 with a 3.3V supply and you provide 5V/0V signal to its pins (either Tx/Rx or pin0,1) nothing's gonna happen. It will work fine.

Based on this experience, i would like to suggest you to

power your esp8266 with 3.3V pin of your TTL converter
power your IR sensor using 5V output pin of your TTL converter
connect signal pin of IR sensor to your esp8266 digital pin. (just
in case esp8266 heats up, disconnect circuit and try using voltage
divided only for this particular connection.

If using those external power supplies don't forget to common GND (or -ive terminal) of those power supplies.


Adafruit_NeoPixel define pin for different setups I am looking for a way of defining multiple pins for my RGB strips. Currently the defined variable is set with the pin within it. This works just fine if I only had one RGB strip connected to the Arduino but I have 4 so I will need to define.

I currently run this code here:

#include <Adafruit_NeoPixel.h>
#include <avr/power.h>

int rgb1 = 18;
int rgb2 = 17;
int LEDs = 11;
int ledFadeTime = 5;

Adafruit_NeoPixel strip1 = Adafruit_NeoPixel(LEDs, rgb1, NEO_GRB + NEO_KHZ800);
Adafruit_NeoPixel strip2 = Adafruit_NeoPixel(LEDs, rgb2, NEO_GRB + NEO_KHZ800);

void setup() {
  strip1.begin();
  strip1.show(); // Initialize all pixels to 'off'
  strip2.begin();
  strip2.show(); // Initialize all pixels to 'off'
}

void loop() {
  rgbFadeInAndOutStrip1(0, 0, 255, ledFadeTime); // Blue
  rgbFadeInAndOutStrip2(255, 0, 0, ledFadeTime); // red
}

void rgbFadeInAndOutStrip1(uint8_t red, uint8_t green, uint8_t blue, uint8_t wait) {
  for(uint8_t b = 0; b <255; b++) {
     for(uint8_t i=0; i < strip1.numPixels(); i++) {
        strip1.setPixelColor(i, red * b/255, green * b/255, blue * b/255);
     }

     strip1.show();
     delay(wait);
  };

  for(uint8_t b=255; b > 0; b--) {
     for(uint8_t i = 0; i < strip1.numPixels(); i++) {
        strip1.setPixelColor(i, red * b/255, green * b/255, blue * b/255);
     }
     strip1.show();
     delay(wait);
  };
};

void rgbFadeInAndOutStrip2(uint8_t red, uint8_t green, uint8_t blue, uint8_t wait) {
  for(uint8_t b = 0; b <255; b++) {
     for(uint8_t i=0; i < strip2.numPixels(); i++) {
        strip2.setPixelColor(i, red * b/255, green * b/255, blue * b/255);
     }

     strip2.show();
     delay(wait);
  };

  for(uint8_t b=255; b > 0; b--) {
     for(uint8_t i = 0; i < strip2.numPixels(); i++) {
        strip2.setPixelColor(i, red * b/255, green * b/255, blue * b/255);
     }
     strip2.show();
     delay(wait);
  };
};

Which works when trying out just one out of the 2. But when the LEDs fade out it has a pause (i still see a hint of blue on the strip). If i comment all the code out for the second strip2 and run that, it pulses just fine without the hint of blue or the delay to start bright again.

What could I be doing incorrectly?

The “hint of blue on the strip” is a consequence of your second loop in rgbFadeInAndOutStrip1() ending with the test b > 0.  Because of that, the last strip1.setPixelColor() call sets the color to (0,0,1), a faint blue, instead of (0,0,0), off.  Here is some revised code that works ok:

#include <Adafruit_NeoPixel.h>
#include <avr/power.h>
enum { rgbPin1=8, rgbPin2=7, LEDcount=11, ledFadeTime=5};

Adafruit_NeoPixel strip1 = Adafruit_NeoPixel(LEDcount, rgbPin1);
Adafruit_NeoPixel strip2 = Adafruit_NeoPixel(LEDcount, rgbPin2);

void setup() {
  strip1.begin();
  strip1.show(); // Initialize all pixels to 'off'
  strip2.begin();
  strip2.show(); // Initialize all pixels to 'off'
}

void loop() {
  rgbFadeInAndOutStrip1(0, 0, 255, ledFadeTime); // Blue
  rgbFadeInAndOutStrip2(255, 0, 0, ledFadeTime); // red
}

void fadeStrip(Adafruit_NeoPixel *strip, int bval, int bdir, uint8_t red, uint8_t green, uint8_t blue, uint8_t wait) {
  for(uint8_t b=0; b<255; ++b) {
    bval += bdir;
    for(uint8_t i=0; i<strip->numPixels(); ++i) {
      strip->setPixelColor(i, red * bval/255, green * bval/255, blue * bval/255);
    }
    strip->show();
    delay(wait);
  }
}

void rgbFadeInAndOutStrip1(uint8_t red, uint8_t green, uint8_t blue, uint8_t wait) {
  fadeStrip(&strip1, -1, 1,   red, green, blue, wait);
  fadeStrip(&strip1, 255, -1, red, green, blue, wait);
}

void rgbFadeInAndOutStrip2(uint8_t red, uint8_t green, uint8_t blue, uint8_t wait) {
  fadeStrip(&strip2, -1, 1,   red, green, blue, wait);
  fadeStrip(&strip2, 255, -1, red, green, blue, wait);
}

Note, since I ran tests on an Uno rather than a Leonardo, I attached pixel strings to pins 7 and 8 rather than 17 and 18.  I used enum to define constants, rather than declaring constants as variables, and factored some common code into functions rather than reduplicating it.

Following is another program (which I call neocycle6) you can use to test two strips.  Note, it only counts colors down to 1 rather than 0 because I like the effect of leftover pixels glowing faintly.  Also note: the round boards I used have only 7 LEDs each, so I set PixelCount to 7, not 11; this uses pins 7 and 8, not 17 and 18; I don't drive the brightness beyond 77 since the LEDs are so bright anyway; and it doesn't have an
#include <avr/power.h> statement, which you can add if needed.

// Drive 2 sets of 7 ea. WS2812 NeoPixels through sets of colors.
// jw 11 September 2015
#include <Adafruit_NeoPixel.h>

// Select pin# connected to NeoPixels strand, and number of NeoPixels.
enum { PixelPinA=7, PixelPinB=8, PixelCount=7 };
// Create a NeoPixels device structure
Adafruit_NeoPixel pixelA = Adafruit_NeoPixel(PixelCount, PixelPinA);
Adafruit_NeoPixel pixelB = Adafruit_NeoPixel(PixelCount, PixelPinB);

void setup() {
  byte i, j=0;
  pixelA.begin();               // Init. NeoPixel data structure
  pixelB.begin();               // Init. NeoPixel data structure
}

uint8_t c=1, d=1, p=0, v=1;
void loop() {
  c += d;
  if (c>76)
    d = -1;                     // Go down when done going up
  else {
    if (c<2) {                  // Set up for next pixel
      d = 1; p = (p+1)%PixelCount;
      if (!p) ++v;              // Rotate the weights to next color
    }
  }

  pixelA.setPixelColor(p, c*(v&1), c*((v&2)/2), c*((v&4)/4));
  pixelB.setPixelColor(p, c*((v&2)/2), c*(v&1), c*((v&4)/4));
  pixelA.show();               // Show updated colors
  pixelB.show();               // Show updated colors
  delay(9 + 300/c);            // Ramp small numbers more slowly
}