How to send 2 data to processing from Arduino I am new to Arduino and processing so sorry for any mistakes.
I have a problem with sending multiple data to processing from Arduino. I can send 1 data easily ut I can't send more than 2 data can somebody help?!??.
This is my Arduino code:

#include <DHT.h>
#define Type DHT11
int dhtpin =2;
float temopValC;
float temopValF;
DHT HT(dhtpin,Type);

#include <Servo.h>
int servopin=9;
int servopos;
Servo servo1;

int trigpin=10;
int ecopin=11;
float distance;
float spedd=343;
float timee;

void setup() {
Serial.begin(9600);
HT.begin();
delay(200);
pinMode(trigpin,OUTPUT);
pinMode(ecopin,INPUT);

servo1.attach(servopin);

}

void loop() {

 temopValC=HT.readTemperature();
 temopValF=HT.readTemperature(true);

spedd =331.3 +(0.6 *temopValC);
//Serial.println(spedd);

 /*Serial.print("Temp C/F "); //temp val
 Serial.print(temopValC);
 Serial.print("   ");
 Serial.println(temopValF);
 delay (1005);*/

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

digitalWrite(trigpin,LOW);
 delayMicroseconds(2000);
digitalWrite(trigpin,HIGH);
 delayMicroseconds(15);
digitalWrite(trigpin,LOW);

timee=pulseIn(ecopin,HIGH);
timee= timee /1000000.;
timee= timee /3600.;

distance= spedd * timee;
distance = distance /2;
distance = distance * 63360;//inch
distance =distance *2.54; //cm
distance= distance *2;

 //Serial.print(distance);
 //Serial.print("  ");
 // delay(200);

  servo1.write(servopos);
  //delay(100);
 // Serial.print(servopos);
  //Serial.println("  ");
   delay(100);
  }
for(servopos=180;servopos >= 1; servopos -=1){

digitalWrite(trigpin,LOW);
 delayMicroseconds(2000);
digitalWrite(trigpin,HIGH);
 delayMicroseconds(15);
digitalWrite(trigpin,LOW);

timee=pulseIn(ecopin,HIGH);
timee= timee /1000000.;
timee= timee /3600.;

distance= spedd * timee;
distance = distance /2;
distance = distance * 63360;//inch
distance =distance *2.54; //cm
distance= distance *2;

// Serial.print(distance);
// Serial.print("  ");
//delay(200);
  servo1.write(servopos);
 //delay(100);
 // Serial.print(servopos);
  //Serial.println("  ");
  // delay(100);
}

/*if(distance < 14.28){
  Serial.println("..............o");
  delay(800);
  }
 if(distance> 14.28){
  Serial.println(" h  ");
  delay(800);
  }

  if(distance== 14.28){
    Serial.println("i   ");
    delay(800);
    }

*/

}

And this is my processing code for one data:

    import processing.serial.*;
Serial mySerial;

String mystring= null;
int nl=10;
float myVal;

void setup(){
size(800, 600);
String myport= Serial.list() [2];
mySerial=new Serial(this,myport,9600);

}

void draw(){

while(mySerial.available() >0){

  mystring =mySerial.readStringUntil(nl);

  if(mystring != null){
  background(0);
  myVal=float(mystring);
  println(myVal);
  }
}
ellipse(250,myVal,10,10);
rect(0,0,20,10);
rect(0,40,20,10);
rect(0,80,20,10);
rect(0,120,20,10);
rect(0,160,20,10);
rect(0,200,20,10);
rect(0,240,20,10);
rect(0,280,20,10);
rect(0,320,20,10);
rect(0,360,20,10);
rect(0,400,20,10);
rect(0,440,20,10);
rect(0,480,20,10);
rect(0,520,20,10);
rect(0,560,20,10);
rect(0,600,20,10);

}

I want to change the x value of the ellipse with the second data fromthe Arduino.

If you mean sending multiple integers, floats, or strings, you can use a CSV format.
CSV Format:
sentData = variables,variables,variable3
You can then decode it with things similar to substring on the Processing side.


Create a device to detect object state Here is what I want to do or get it done (since I am not a embedded guy)...

create a prototype with Arduino to detect open window/door of my room using camera(image processing/object state detection)?
that prototype will take pictures of room door/window at certain interval and than using some algorithm to decide whether they are open or not and will sound an alarm if it is open.
prototype should work in dark as well
No false alarms
Form factor should be small (the final product should not be bigger than smoke detectors that we have it in our room)

My questions are..

Is it possible? :)
What all things I need to create a prototype?
Which camera should I use? Camera should be really small.
Are algorithms available to detect it?

Your answers :-)

yes, it's possible and should not be too complex
for a simple prototype, you do not need an embedded device, just a PC with a webcam
a webcam with few megapixels should be enough
try OpenCV

After your prototype is ready, you can use a small PC-like platform.
Examples: Minnowboard, Edison, BeagleBone, RaspBerry PI 2, Arduino Yun, Galileo 2

A word of warning: depending on the expectations you have, you will have to pick more powerful models. Computer Vision is computationally intensive.
The examples I gave are roughly sorted by performance and, unsurprisingly, cost. OpenCV is available for many architectures, but afaik, it is particularly optimized for x86, since it's mostly sponsored by Intel.

Disclosure: I work for Intel, so I am more informed on Intel products, but by no means I'm trying to do advertisement, this answer is simply given to the best of my knowledge.


Photoresistor is not working, is there something wrong in the code? I am trying to make the photoresistor work in a simple project.

The project is as follows:
The LED light should light up brighter and brighter as the photoresistor reads less light in the room.

The problem:
The reading is fixed on 1023. Therefore the LED never lights up. I cannot understand why.. Sometimes if I cover the sensor the readings go down to 900- 950 but never less even though it is completely dark around the sensor. Is there something wrong in the code? What could have gone wrong?
Please note that the resistor connected to the sensor is 10k Ohm as is the one connected to the LED.

Here is the code

int photoPin = 0;
int pReading; // analog readings

int LED = 11; // red LED connected to pin 11
int LEDbrightness; //

void setup()
{
  //set up the serial connection
  Serial.begin(9600);
}

void loop()
{
  pReading = analogRead(photoPin);
  Serial.print("Photocell reading = ");
  Serial.println(pReading); // Analog reading

  pReading = 1023 - pReading;
  //map 0-1023 to 0-255
  LEDbrightness = map(pReading, 0, 1023, 0, 255);

  analogWrite(LED, LEDbrightness);
  delay(50);
}

Here are the connections

thank you!

The code looks OK. It looks like it's your circuit which is the problem.

The main role of a photoresistor is to restrict the amount of current flowing through it when the light level is reduced. It won't directly affect voltage the way you're expecting (the analog pins respond to voltage).

However, it's pretty easy to make it affect voltage with a slightly different circuit. Try creating a voltage divider circuit, such that the supply voltage (5V) goes through the photoresistor, then through another resistor, and then to ground. The Arduino's analog pin should be connected between the photoresistor and resistor. (See the image below, although the resistor on the output probably isn't necessary in this case.)

This should cause the voltage on the analog pin to decrease when the light level decreases. You may need to experiment a little to find a suitable resistor value on the ground connection, although 2K Ohms is probably a good starting point. It basically affects the sensitivity of the circuit.

Image credit: Morteza Lahijanian (source)


Debug soldered connections of LCD 1602A I am moving my first steps into Arduino and electronics and I have tried to program an LCD 1602A display following this tutorial.

I managed to complete the tutorial up to setting up the contrasts of the display using the potentiometer (on the display I get nice "white" rectangles), but when I tried to upload the code provided I get no text on the display.

I checked and I connected pins the right way but I suspect that my soldering skills might affect the final result: the pins seem wiggly and even just to power up the display I have to adjust the cable connections quite a bit before the LCD turns on.

Which steps should I follow to check that the pins are soldered correctly and that the right current flows through each of them? I figured I could use a multimeter to check the intensity through and voltage applied to each of the pins, but I have no clue what readings I should get. How should I proceed?

EDIT (2016/12/12)>
Here is the picture showing the step I got stuck

And here is a picture showing the soldering I did:

Also I checked with the multimeter and each of the pin passes a continuity measurement.

What else can I try?

As noted in a comment, you can measure connection resistances, which should be near zero.  (Typical DVMs / multimeters will show an ohm or two for a short, because of leads resistances.)

Measuring voltages may give you more definitive results than measuring resistances.  To measure voltages, install a sketch that toggles known pins in a known pattern.  For example, the sketch below toggles PB0...PB5 high, low, high, low, ... every two seconds.

//  jw - Dec 2016 - toggle bits PB0-PB5 every 2 seconds
enum {PinMask = 63};    // Mask for PB0...PB5, or d8 ... d13
void setup() {
  PORTB = DDRB = PinMask;  // Set pins as high outputs
}
void loop() {
  delay(2000);      // Delay 2 seconds
  PINB = PinMask;   // Toggle the pins
}

To use this sketch, attach a meter lead to ground on your Uno.  If you have small enough clips, hook a lead to pin 6 of the 6-pin ISP connector, as in  the diagram.  Then verify that pin 2 of that connector shows a steady +5V, and that each of pins 1, 3, and 4 on it are toggling between +5 V and 0 V every two seconds.  Those pins are connected to PB4, PB5, and PB3, which are Arduino digital pins #12, 13, and 11, respectively.  Note, toggling #13 should turn the on-board LED off or on every two seconds.

Note, pins 1 and 2 are closer to the RX-TX corner of the Uno board than are pins 5 and 6.  The latter are closer to the A4-A5 corner.

After you have the sketch loaded and verified (that is, have seen properly toggling voltages at the ISP connector), with one lead still attached to ISP pin 6 ground, point a probe at each LCD land where a wire connects.  That is, make the probe contact the copper you intended to solder to, rather than contacting the wire.  This is to get closer to end-to-end measurements.  With the sketch shown above, you will touch your probe to the lands of LCD pins 6, 11, 12, 13, 14 (assuming you've followed pin assignments shown in your link).  If you find those points toggling ok, you've got basic connectivity.  If not, resolder, using proper solder and a hot-enough iron.  If basic connectivity is ok but LCD still doesn't work, you may have some lines mixed up, or may have shorts between lines, etc.  You can run a sketch like the one shown below to test individual lines.  Set WhichPin to values 1, 2, 4, 8, or 16 in turn, to test  Arduino digital pins #8, 9, 10, 11, 12, respectively.

//  jw - Dec 2016 - toggle one of PB0-PB5 every 2 seconds
enum {PinMask = 63};    // Mask for PB0...PB5, or d8 ... d13
enum {WhichPin = 1};    // Set this to 1, 2, 4, 8, or 16 for PB0-PB5
void setup() {
  PORTB = DDRB = PinMask;  // Set pins as high outputs
}
void loop() {
  delay(2000);      // Delay 2 seconds
  PINB = WhichPin;  // Toggle the selected pin
}

For testing Arduino digital pin #7, you can add pinMode(7,OUTPUT); digitalWrite(7, HIGH); in setup() and digitalWrite(7, !digitalRead(7)); in loop().

Edit 1: The first sketch shows a brief way of toggling six lines at once, using port-level IO instead of using a half-dozen digitalWrite() calls.  The sketch generates a low-frequency square-wave.  The reason for measuring if LCD pin-voltages toggle up and down when the Uno outputs a square wave is to find out if there are ok connections between pins on the Uno and corresponding pins on the LCD.

One cannot realistically expect the LCD to work unless the connections are solid.  Making solid connections requires finding out which connections are good, and which are bad, and fixing the bad ones.  A quick test for if a connection exists is to output a square wave to an Arduino pin and observe if that square wave arrives at its destination pin on the LCD.

In the sketch, PinMask selects which bits of port B get toggled.  (A 1 OR'd into PinMask selects PB0 or digital pin #8 to be toggled; a 2 OR'd in  selects PB1, #9; a 4 selects PB2, #10; and so forth.)  In the second sketch, WhichPin is a bit mask containing one bit, which is used to select one pin to be toggled instead of toggling all six pins.


Customize FTDI driver for custom PID and VID I have changed PID and VID of my FTDI board for  arduino program because i wanted to rename the com port name.
The ic is  FT232R a USB to serial UART interface IC. I have store new vid and pid to EEPROM.
Now It is showing in unknown devices. I am not able to update driver of it.
I have followed this article http://forum.arduino.cc/index.php?topic=6929.0.

Can anyone tell how to make cutmoize driver for it.
Any suggestions will be very helpful.

On Windows

You can refer to FTDI's documentation here for details on how to create your own custom device driver. The FTDI website has a lot of resources for this, however they seem to be a little outdated. Microsoft details how drivers work in it's Hardware Dev Center.

On Linux

On Linux it may be as easy as registering the device with modprobe. For example, for a device with a VID of 0102 and a PID of 1234, execute the following from the shell:

modprobe ftdi_sio
echo "0102 1234" | sudo tee /sys/module/ftdi_sio/drivers/usb-serial\:ftdi_sio/new_id > /dev/null


Pro micro Wire.endTransmission() does not return I have an Arduino Pro Micro(blue version) and I'm having trouble using the I2C. To test it, I use the code below and the result is an infinite square wave on SCL and SDA lines and I only get the number 1 on the terminal output. I have pullup resistors on both wires, 2k each.
Since the board uses an ATMEGA32U4, I tried the same code on a bare MCU and the code works as expected. The difference between the two is the bootloader type. The bare PCB is flashed over USB, using the factory bootloader(ATMEGA32U4-AU, QFP44).
By debugging the code, I found out that endTransmission does not return.
Does anyone have an idea, why the I2C is not working as expected on the Pro Micro module?
Thanks!
#include <Wire.h>

void setup() {
  Serial.begin (115200);
  // Leonardo: wait for serial port to connect
  while (!Serial)
    {
    }
  Serial.println ();
  Serial.println ("I2C scanner. Scanning ...");
  byte count = 0;
  Wire.begin();
}  // end of setup

void loop() {
  byte count = 0;
  for (byte i = 1; i < 120; i++)
  {
    Serial.println(i);
    Wire.beginTransmission (i);
    Wire.endTransmission ();
    delay(10);
  }
}

Seems like the module has a defect, since the same code on another board produces the expected output on the I2C lines


Generate 1.7 Mhz with PWM in Uno? I have this code:

void setup() {
  pinMode(11, OUTPUT);
  TCCR2B = 0;
  TCNT2 = 0;
  TCCR2A = _BV(WGM21);
  TCCR2A |= _BV(COM2A0);
  OCR2A = 249;
}

void loop() {
  soundBuzzer();
}

void soundBuzzer() {
  TCCR2B |= _BV(CS21);
}

void silenceBuzzer() {
  TCCR2B &= ~_BV(CS21);
  TCNT2 = 0;
}

(Got it from here).

And I have an ultrasonic water atomizer that works in a frequency of 1.7 Mhz.
Writing another number instead of 249 in the line "OCR2A = 249;", the frequency generated changes. With 249 it generates a frequency of 4 Khz. So, my question is: Which number do I have to write to get approximately 1.7 Mhz?

Expanding from my comment... any signal level generated by this kind of
microcontroller can only last for an integer number of CPU cycles. In
order to generate it, you first have to compute the timing
characteristics of the desired signal in terms of CPU cycles:

period = 16 MHz ÷ 1.7 MHz = 9.412 cycles

The closest you can get is 9 cycles, which gives the frequency

frequency = 16 MHz ÷ 9 = 1.778 MHz

Assuming this is acceptably close to your target, you can configure a
timer to do it. The example code you provided uses Timer 2 with the
OC2A output set to toggle mode. This approach can only give periods
which are an even number of cycles, thus I am using the regular
“non-inverting fast PWM” mode instead in the solution below. In this
mode, the pin OC2A cannot be used with a controlled frequency, then I
changed it to OC2B (pin 3 on the Uno). Here is the code:

const uint8_t OUTPUT_PIN = 3;  // = OC2B
const uint8_t PERIOD = 9;      // 9 CPU cycles ~ 1.778 MHz

void setup()
{
    pinMode(OUTPUT_PIN, OUTPUT);
    TCCR2B = 0;           // stop timer
    TCNT2  = 0;           // reset timer
    TCCR2A = _BV(COM2B1)  // non-inverting PWM on OC2B
           | _BV(WGM20)   // fast PWM mode, TOP = OCR2A
           | _BV(WGM21);  // ...ditto
    TCCR2B = _BV(WGM22);  // ...ditto
    OCR2A = PERIOD - 1;
    OCR2B = PERIOD/2 - 1;
}

void soundBuzzer() {
    TCCR2B |= _BV(CS20);  // F_CPU / 1
}

void silenceBuzzer() {
    TCCR2B &= ~_BV(CS20);
    TCNT2 = 0;
}

The generated signal is slightly asymmetric: it stays HIGH during
4 cycles and LOW for 5 cycles. If you want a symmetric signal
(50% duty cycle), you can set PERIOD to 10 (5 cycles HIGH
and 5 cycles LOW), but then the frequency drops to 1.6 MHz.

Edit: You could also replace your Arduino Uno by a cheap ATtiny85
microcontroller, or maybe an Arduino-compatible dev board based on it,
like the Trinket or the Digispark.

This microcontroller has a built-in PLL which allows it to run one of
its timers at 64 MHz, even though the CPU is running much slower.
A 64 MHz timer allows you to hit the target 1.7 MHz frequency
to within 1%:

64 MHz ÷ 38 = 1.684 MHz


Can an L293D motor driver shield do microstepping? I bought a L293D motor driver shield and have used it with a pre-made sketch for driving a pair of stepper motors, but I'm not familiar with its capabilities.

The sketch I've used so far doesn't use microstepping when it's set up for this shield (though it does use it with the Adafruit shield).

I've done some searching, and it's not clear if the L293D chips on the shield can do microstepping, and if so, how.

Are L293D chips (and thus the motor driver shield that uses them) capable of microstepping? If so, how can I add this capability into my sketch?

It would be more accurate to say that it can be used as part of a microstepping system, though it's probably not a good choice for any use today.

The L293D is merely an (effectively obsolete implementation of an) H-bridge, not a stepper motor sequencer, hence it is no more capable of autonomously driving a motor in full or half step mode than it is of microstepping - it can only do any of these when it is controlled by a sequencer, such as an L297 chip, or software running on an Arduino's processor.

Microstepping requires partially actuating the coils to interpolate between the angular positions which would be achieved by activating each in turn fully.  It can be thought of as a proportional extension of how half-stepping uses actuating both coils at the same power to achieve a halfway in between position, only now the coils are actuated at different power levels to achieve finer gradations of position, though achieving accurate interpolation requires care as the relationship is not linear.

Modern power electronics no longer use variable analog drivers, as these convert the unused power to heat.  Instead, the goal is to use switches which come as close as possible to only ever being fully on or fully off.  Reduced driver power is achieved by pulse width modulating the switch, varying the average amount of power delivered to the load over a short period of time.  In a stepper motor setting, this on-off modulation can be done to achieve microstepping and or also to achieve current regulation when a many-times-rated-voltage supply is used to allow overcoming winding inductance at high step rates.

The L293D (and its larger cousin the L298) are quite inefficient bipolar transistor bridges (they aren't very good switches compared to MOSFETs), and should probably not be chosen for new designs today.  They are, however, capable of being used to microstep a motor when actuated by a sequencer which pulse width modulates the phase signals.
Adafruit, who appear to be the original creators of this shield design, have in fact published microstepping driver code for their L293D board on github.

https://github.com/adafruit/Adafruit-Motor-Shield-library

Given that the ebay seller you link to as the source of the board is using Adafruit's own schematic on their product page, it's a bit unclear why your software is differentiating between this board vs an Adafruit one, unless by the the Adafruit board you mean their V2 shield.  The V2 design uses a more efficient TB6612FNG FET bridge, but of more relevance to microstepping offloads the sequencing task from Arduino software to a PCA9685 chip which is apparently capable of microstepping (as well as simpler modes) by itself.  Depending on the computational load and/or your  level of determination, you may be able to get the ATmega microstepping the L293D in the context of your overall project.


How is a long int stored in an 8 bit Arduino register Assume the following code in C:

long int a = 262143;

which in binary will be 111111111111111111 (18 bits).
If an atmega328p register can hold 8 bits, how is the above represented in the register?

Compiled Assembly:

    .file   "a.c"
__SP_H__ = 0x3e
__SP_L__ = 0x3d
__SREG__ = 0x3f
__tmp_reg__ = 0
__zero_reg__ = 1
    .text
.global main
    .type   main, @function
main:
    push r28
    push r29
    rcall .
    rcall .
    in r28,__SP_L__
    in r29,__SP_H__
/* prologue: function */
/* frame size = 4 */
/* stack size = 6 */
.L__stack_usage = 6
    ldi r24,lo8(-1)
    ldi r25,lo8(-1)
    ldi r26,lo8(3)
    ldi r27,0
    std Y+1,r24
    std Y+2,r25
    std Y+3,r26
    std Y+4,r27
    ldi r24,0
    ldi r25,0
/* epilogue start */
    pop __tmp_reg__
    pop __tmp_reg__
    pop __tmp_reg__
    pop __tmp_reg__
    pop r29
    pop r28
    ret
    .size   main, .-main
    .ident  "GCC: (GNU) 8.2.0"

It isn't.  It's split into four 8-bit values, each representing a quarter of the bits.  Each value is stored in a separate register or memory location (depending on what is being done with it).

Software then combines them together to act as a single 32-bit value.


I2C call during Wire.requestFrom Which I2C command happen during Wire.requestFrom(address, quantity)?

Is it correct that Wire put a Start condition, then 7-bit address appended with read bit? How would that be different from Wire.write(address)?

There is no Wire.write(address) in the Wire library. The function write() takes data and puts it into the library internal write buffer. It does nothing on the I2C bus.

For master write operation (sending from master to slave) the following commands are necessary:

Wire.beginTransmission(address);
Wire.write(data);
Wire.endTransmission();

Only the last of these commands does something on the I2C bus. It generates a Start condition, sends the byte consisting of the address (that we set in the beginTransmission() statement) and the direction bit, which is always 0 here, because these commands are meant for master write operation. Then it sends the data and ends the transmission with a stop condition. You cannot control, which value the direction bit has. The parameter of beginTransmission() is only meant to be 7 bit long. If you provide a bigger address, the function will simply cut the highest bit and issuing a write operation anyway.

For master read operation the action on the I2C bus happens inside the requestFrom() function. It sends a Start condition, followed by the address and the direction bit set to 1 (again you cannot control the value of the direction bit here). Then it reads the bytes, that are coming from the slave until all requested bytes were received. Then you can read the bytes from the library internal buffer with the Wire.read() function. Again this function does nothing on the I2C bus. It only interacts with the libraries buffer.


Measure Vcc using 1.1V bandgap For an battery driven application I want to measure the Vcc (using an Atmega 32u4). That is my code:

int readBandGap() {
  ADMUX = (B01 << REFS0)    // VCC
        | (0 << ADLAR)      // right-adjusted result
        | (B011110 << MUX0) // 1.1V
        ;
  // switch off any ADC conversion
  ADCSRA &= ~(1 << ADEN);
  // enable ADC
  ADCSRA |= 1 << ADEN;
  // start ADC
  ADCSRA |= 1 << ADSC;
  // wait until finished
  while (bit_is_set(ADCSRA, ADSC));
  // first read low, then high!
  uint8_t low = ADCL;
  uint8_t high = ADCH;
  // switch off any ADC conversion
  ADCSRA &= ~(1 << ADEN);
  return (high << 8) | low;
}

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

void loop() {
  int value = readBandGap();
  float vcc = 1.1 * 1023 / value;
  Serial.print(value);
  Serial.print("  ");
  Serial.println(vcc);

  delay(1000);
}

My Olimexino 32u4 board has the ability to switch the voltage between 5V and 3.3V. There are two strange things:

the first measurement is always significantly different than the later measurements
with 5V I'm getting 450, followed by ~367; with 3.3V I'm getting 422, followed by ~395. I would have expected a higher Vcc resulting in a lower measured value (bandgap should be measured compared to Vcc).

Any ideas what is wrong with my approach?

The bandgap voltage reference needs some time to stabilize, after you enable it. See http://jeelabs.org/2012/05/12/improved-vcc-measurement/

Doing 3 dummy measurements, gives it enough time to do that.


Use std::list in Arduino programming When trying to compile

#include <list>
std::list<byte> l = { 7, 5, 16, 8 };

in the Arduino IDE (with ATtinyCore for ATtiny4313), I get this message:

  error: list: No such file or directory
    #include <list>

How to use the standard C++ std::list with Arduino/ATtiny?

I back up Michel Keijzers' suggestion to use a plain array, especially
given the tiny amount of RAM in your MCU (only 256 bytes).

Concerning the removal of items from the list, and given that your list
will be 16 bytes at most, you don't need to get fancy: just move back
the items that are past the one you removed. It will not take long.

Here is a barebones implementation of a list that can hold at most
16 bytes and supports removal:

class List {
public:
    byte length;
    byte data[16];
    void append(byte item) {
        if (length < 16) data[length++] = item;
    }
    void remove(byte index) {
        if (index >= length) return;
        memmove(&data[index], &data[index+1], length - index - 1);
        length--;
    }
};

Note that this only takes 17 bytes of RAM (16 items max plus a
length count). There is not vtable, as it has no virtual methods. You
can get fancier if you want, make this a template parametrized by the
data type and the maximum length, add accessors and such... but if you
are just writing a simple sketch (as opposed to a general purpose
library), I would recommend keeping it as simple as possible.

Example usage, based on your pseudo-code:

List l { .length = 3, .data = { 12, 82, 29 } };
l.remove(1);

This will indeed result in the list [12, 29].


LCDs larger than 20x04 and 5" diagonal Are there any i2c LCD screens that are larger than 2004 characters and larger than 4.8 x 2.7 x 1.2 inches in dimensions?

I have the Sainsmart 2004 LCD but it can't display all the information that I need. Maybe a 20x8 character screen? Because the screen will be viewed from a distance of about 50cm, the screen size should be at least 5" in diagonal.

Naked displays... search e.g. Ebay for "40x4 lcd" (maybe enable "worldwide" search)...

...naked... so not i2c ... but Arduino libs for these displays exist (e.g.: liquidcrystal440), so add an Arduino-Pro or such and you can have i2c... basically they are two 40x2 displays on the same spi bus selected by different chip select lines...


How to decrease adc accuracy? I read in this atmega328p datasheet the following on page 308:
From sect. 28.4:

By default, the successive approximation circuitry requires an input
clock frequency between 50kHz and 200kHz to get maximum resolution. If
a lower resolution than 10 bits is needed, the input clock frequency
to the ADC can be higher than 200kHz to get a higher sample rate.
The
ADC module contains a prescaler, which generates an acceptable ADC
clock frequency from any CPU frequency above 100kHz. The prescaling is
selected by the ADC Prescaler Select bits in the ADC Control and
Status Register A (ADCSRA.ADPS). The prescaler starts counting from
the moment the ADC is switched on by writing the ADC Enable bit
ADCSRA.ADEN to '1'. The prescaler keeps running for as long as ADEN=1,
and is continuously reset when ADEN=0.
When initiating a single ended
conversion by writing a '1' to the ADC Start Conversion bit
(ADCSRA.ADSC), the conversion starts at the following rising edge of
the ADC clock cycle.
A normal conversion takes 13 ADC clock cycles.
The first conversion after the ADC is switched on (i.e., ADCSRA.ADEN
is written to '1') takes 25 ADC clock cycles in order to initialize
the analog circuitry.

By required bandwidth is 120 kHz, and 5 bit accuracy will suffice for my purpose. So, I understand that I can achieve this by changing the prescaler to a lower division number, thus increasing the clock frequency fed into the ADC (as per the diagram in the aforementioned document).
However, the document only specifies the min and max times required for ADC conversion for 50 kHz (12 to 280 microseconds at 50kHz bandwidth).
My question: Given my requirement of 120kHz bandwidth, what is the lowest prescaler division value I should use to guarantee ADC completion time to within 1/120kHz seconds (8.3us)?
EDIT: This is another question I have: Why does the accuracy change when using a lower divider value? Surely we are simply changing the clock frequency fed into the ADC converter, not the ADC algorithm itself; so why should the bit accuracy change?

From: http://forum.arduino.cc/index.php?topic=6549.0

The documentation states that 13 cycles are neccesary for ADC conversion. Thus, using the clk/13*8 divisor configuration, and 16 MHz system clock, the upper bound becomes 154KHz

The forum post in the above link continues to say that "ADC clock frequencies above 1MHz are uncharacterised", however this was quoting another document for which the link is dead. I could not find this statement in the most recent documentation.

Edit: Another forum post where a user successfully used an atmega328p to achieve 360000 samples/sec, so it is technically possible:
http://forum.arduino.cc/index.php?topic=8795.0


Is there a non-float alternative to pow()? I've scoured the LANGUAGE REFERENCE in the Arduino web-site, and I can't find a non-Float equivalent to pow()  I've got to be missing something big, but for the life of me, I'm stumped!  I found pow() in the FUNCTIONS column under the Math heading (like I would expect), but it says that both parameters,  [base] and [exponent] are both (float). And there are only six other entries under the Math heading; none of them seem to be seem to be an integer version. All I want to do is generate the powers of 2 using the exponents from 0 to 10. Like 2^0=1 then 2^1=2 then 2^2=4 then 2^3=8 then 2^4=16 then 2^5=32 then 2^6=64 then 2^7=128 then 2^8=256 then 2^9=512 then 2^10 is 1024

Is using floats the only way I can do this? I'm starting to feel like I'm at odds with reality, and have actually counted my medication, but I'm right where I should be. Let me apologize in advance for this egregious oversight that I've wasted your time with, but I've gone through all 9 pages of tags and have done ever search I could think of. I'll admit that I haven't spent all THAT much time, but I was sure this was only going to be like a five minute thing!

For the general case, @dat_ha 's answer is correct, but it is worth noting that you want a very special case... powers of two. Because computers use binary arithmetic, operations involving powers of two often have some shortcuts available.

Multiplying a number by a power of two can be accomplished by the left shift operation (<<), which literally shifts the digits of the binary representation of the number (i.e., bits) leftward.  In base two, shifting bits one place to the left is the same as multiplying by 2, just as in base 10 shifting digits one place to the left is the same as multiplying by 10. For a full explanation of the left shift operator in C++, see this answer on Stack Overflow.

It is important to note that left shifting can lose information; bits shifted off the end are lost. Because you need powers of 2 up to 10, you are safe when working with signed integers, which have a max value of 2^15-1 on Arduino Uno.

Given those caveats, here's a function to calculate powers of two within these constraints.  This is very fast code because the left shift operation is a very low level operation, and no multiplication is actually performed.

int pow2(int p){
    return 1 << p;
}


ESP-01 not responding to serial data while programming with esptool.py I have a Arduino uno board, ESP-01 board and a logic level shifter (bidirectional) and to program the esp module i wired my Arduino and esp like this

Arduino uno(atmega328p removed)  --> level shifter --> ESP-01
5v --> highvolt
3v3 --> lowvolt
TX --> ch1 --> TX
RX --> ch2 --> RX
proper ground connections

but when i click upload the RX pin lights up indicating its receiving data but esp doesn't respond to that when i reset the module while its uploading the compiler throws this
Serial port COM3
Connecting........_____....._____....._____....._____....._____....._____.....____Traceback (most recent call last):
  File "C:\Users\TRAJU\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4/tools/upload.py", line 65, in <module>
    esptool.main(cmdline)
  File "C:/Users/TRAJU/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.7.4/tools/esptool\esptool.py", line 2890, in main
    esp.connect(args.before)
  File "C:/Users/TRAJU/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.7.4/tools/esptool\esptool.py", line 483, in connect
    raise FatalError('Failed to connect to %s: %s' % (self.CHIP_NAME, last_error))
esptool.FatalError: Failed to connect to ESP8266: Timed out waiting for packet header
_
the selected serial port _
 does not exist or your board is not connected

It as working fine yesterday and it stopped today :(
Please help and thanks in advance.

I found my problem.
esptool.py uploads the firmware at 115200 baud rate, which my logic level converter couldn't handle.  I found this out after writing this question. I thought of connecting RX and RX directly to the ESP module's RX and TX and it uploaded the program. Maybe I am wrong.  Please, if any one know why this happened I am curios to know.  Thanks in advance. ;)


How to output a true analog voltage at output pin Regarding my program, it is a program that does some calculations and then outputs a voltage based on the result using analogWrite function. However my problem is that I had done my programming based on a misconception that analogWrite function via PWM does output an analog voltage, where in fact it only "simulates" the analog voltage instead.

Here are the relevant parts of my code :

int pwmOutput = 11;
int pwm = 0;

void compareNewOldVoltageYes(void)
{
  if(pv_Vnew > pv_Vold && pwm != 255)
  {
    ++pwm;           //increasing value
  }
  else if(pwm != 0)
  {
    --pwm;           //decreasing
  }
}

void compareNewOldVoltageNo(void)
{
  if(pv_Vnew > pv_Vold && pwm != 0)
  {
    --pwm;
  }
  else if(pwm != 255)
  {
    ++pwm;
  }
}

void loop()
{
   reading();
   PowerCalculation();

   if(pv_NewP > pv_OldP)
   {
      compareNewOldVoltageYes();
   }
   else
   {
      compareNewOldVoltageNo();
   }

   analogWrite(pwmOutput, pwm);           //analogWrite

   float displayPWMvolt = pwm * 0.0196;

   Serial.print("Output Voltage: ");
   Serial.print(displayPWMvolt);
   Serial.println(" V");

   pv_OldP = pv_NewP;

   Serial.print("Previous Power: ");
   Serial.print(pv_OldP);
   Serial.println(" W");

}

As for the circuitry, output pin 11 is being connected to a 1 ohm resistor and then to GND. (Where I measured the voltage) I am using Arduino Uno board.

UPDATE:

As said in the comments by @DatHa, pwm does not output voltage. Is there a way to output voltage as said, without changing the board?

You basically have three options:

Switch to an Arduino Due which has a built-in DAC which outputs a real voltage.
Add an external DAC chip (such as the MCP4821/2) to create the voltage for you
Use a low-pass filter (R-C network) on a PWM pin.

Of the three options I usually use an MCP4822 since it gives the best results and doesn't cost as much as using a Due.


Editing a particular position in a file stored in SD card I am trying to store some variables in a text file which is saved in a SD card, using the SD library. Every time my program runs, it load the values of those variables from the file. After a few minutes, my program will attempt to change the value of some variables (not all).

This is what I would in a C program. I would locate the position (using position()) where the values to be edited is present, and then using the seek() function I would write at the given position thus overwriting the file.

Each variable is stored in a separate row. But for some reason the program only writes at the end of the file, even if I have moved the file pointer elsewhere. How can I do the above task?

A simple example of the code is as follows:

#include <SD.h> //Load SD library

int chipSelect = 53;
File file;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(chipSelect, OUTPUT); // chip select pin must be set to OUTPUT mode

  Serial.print("Welcome!");
  Serial.println();

  bool initialization_state = SD.begin(chipSelect);
  delay(400); // SD card needs sometime to intialize

  if (!initialization_state) { // Initialize SD card
    Serial.println("Could not initialize SD card."); // if return value is false, something went wrong
  } else {  // if return value is true
    Serial.println("SD card initialized");
  }

  SD.remove("misc.txt");
  file = SD.open("misc.txt",FILE_WRITE);
  file.print("Once you know the central idea and a rough plan for your paragraphs, you need to arrange them in a certain manner to get your story across.");
  file.println();
  file.print("Following are some possible ways of organizing your paragraphs.");
  file.println();
  file.print("Narration: Tell a story. Go chronologically, from start to finish. Description: Provide specific details about what something looks, smells, tastes, sounds, or feels like.");
  file.println();
  file.print("Organize spatially, in order of appearance, or by topic. Process: Explain how something works, step by step. Perhaps follow a sequence—first, second, third.");
  file.close();
  read_file();
  Serial.print("Read?");
  Serial.println();

  update_file();
  read_file();
}

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

void read_file() {
  Serial.println("--- Reading file ---");
  file = SD.open("misc.txt", FILE_READ);

  char character;
  while( (character = file.read()) != -1) {
    Serial.print(character);
  }
  Serial.println();
  file.close();
}

void update_file() {
  file = SD.open("misc.txt", FILE_READ);
  char character;
  while( (character = file.read()) != '\n') {}
  byte pos = file.position();
  file.close();

  file = SD.open("misc.txt", FILE_WRITE);
  file.seek(pos);
  file.print(" Love, love, love.");
  file.close();
}

In this program I am attempting to overwrite the second line. The while loop breaks at the first newline character. I store the location of the first character in the second line in a variable pos. Then I open the file object for writing, I seek the position where I want to write (using file.seek(pos) ) and then I print into the file. But when I read the file, the text "Love, love, love." is written at the end.

I am using the linux Arduino IDE 1.8.9.

The problem is that you are opening the file with FILE_WRITE.  That is a combined macro that is made up of:

#define FILE_WRITE (O_READ | O_WRITE | O_CREAT | O_APPEND)

The key one there is O_APPEND.  In the source code (SdFile.cpp) t says:

  O_APPEND - If set, the file offset shall be set to the end of the file prior to each write.

So the seek does nothing if O_APPEND is set, since it is overridden.

So instead you need to open the file without O_APPEND.  In fact you don't need to close and open the file at all, since if opened correctly you can hop around at will reading and writing.  The flag O_RDWR is a combination of O_READ and O_WRITE.

For example:

void update_file() {
  file = SD.open("misc.txt", O_RDWR);
  char character;
  while( (character = file.read()) != '\n') {}
  file.print(" Love, love, love.");
  file.close();
}

The O_CREAT flag that is part of FILE_WRITE will create a new file if you try and open one that doesn't exist. By omitting that SD.open will fail if the file you are trying to modify doesn't exist.


NodeMCU : Input pullup in A0 I am trying to port a simple project I have working in an Arduino UNO to a NodeMCU but I am stuck as I am using the analog gpio to receive the input from some buttons, I am always getting always low values (between 0 and 5) while in the working arduino sketch I get values from 0 to 1023.

I have tried deactivating the wifi while trying to retrieve the values, but I got no luck trying that, as I have read that sometimes the NodeMCU A0 gpio malfunctions when the wifi is not sleeping.

I am setting up the gpio in the setup method like this:

void setup(void){
    pinMode(sensorPin, INPUT_PULLUP);
    ...

And my sensorPin variable is declared in the beginning of the sketch

int sensorPin = A0;

Any ideas why when I read the value in the NodeMCU I don't get the same behaviour as in an Arduino board?

As stated by Majenko in the comments, I thought that all MCUs analog gpios had a pullup resistor built in, so I have been able to solve the problem using an external pullup, in this case connecting a 10K resistor like in the diagram:

 .

Special thanks to Majenko for his time and patience. Cheers!


Can't connect to serial port I'm trying to make my Arduino's LED blink for the first time, but when I try to upload the code I get the following error in the Serial Monitor:

  Error opening serial port '/dev/ttyACM0'.
  Try consulting the documentation at http://playground.arduino.cc/Linux/All#Permission

BTW, I have serial.debug_rate=9600, so I don't think that's the problem. Can anyone help me with this please?

It seems your serial does not have the right permissions to be opened in user mode. Try adjusting that by typing

sudo chmod a+rw /dev/ttyACM0

on the console (open it by CTRLALTT).


Telit GPRS Module never returning and never timing out for command AT#FTPOPEN Howdie!  I trying to run a GPRS modem on an Arduino. My full stack is Nimbelink's NL-SW-GPRS Modem (containing Telit GE910-QUAD GPRS module) with the Nimbelink Arduino Development Shield on an Arduino UNO R3.

My goal is to connect to an FTP server and upload a file. I am following this guide from Nimbelink and section 3.3 from Telit's user guide.

I am stuck because the AT#FTPOPEN command doesn't seem to ever timeout nor does it return any result (ERROR or OKAY).

Here is the AT commands I am running:

AT
> OK

AT+CGREG?
> +CGREG: 0,1
> OK

AT#SIMDET=1
> OK

AT+CGDCONT=1,"IP","internet.com","0.0.0.0",0,0
> OK

AT#SCFG=1,1,300,90,600,200
> OK

AT#SGACTAUTH=0
> OK

AT#SGACT=1,1
> <My IP Address>
> OK

AT#FTPTO=100
> OK

AT#FTPOPEN="209.86.62.76","anonymous","anonymous",0

Where 209.86.62.76 is the IP address of ftp.earthlink.net which I am just using for testing purposes, but I have tried several others. I have tried with FTP mode 0 (active) and 1 (passive) with no change in behavior.

The AT#FTPOPEN just never returns anything (no ERROR and no OK). I've waited up to 5 minutes. The command does returns "ERROR" if I deliberately mess up the syntax of the command (eg. AT#FTPOPEN="") but for any valid format it just seems to hang.

Is this a known problem or something I can easy work around? Am I doing something crazy with my timeout values? Is there an easy way to test the context that I activated with the SGACT?

This is more of a question for an M2M forum, but I'm on an Arduino and it seems like there are many people using GSM modules on Arduino - so I thought I'd post here because I am a bit desperate. Thanks :)

The issues were:

Pin 9 MSM_nRESET should be explicitly set to HIGH.
Pin 10 (DTR) and pin 11 (RTS) should be explicitly set to LOW.
The Nimbelink device requires 5V external power. With USB power, the modem can intermittently reset during period of high activity. If the modem resets, then the command can appear to run forever when nothing is actually running.
Must use FTPOPEN with connection type 1 (passive).


How to animate a LED Strip via wifi? I'm remotely connecting my phone to an arduino MKR1000 via wifi, and sending data via HTTP GET (so to switch on the debug LED, I just need to navigate to http://192.168.1.1/debug/H, for example). Now, I want to be able to remotely send animations to an RGBW led strip.

Ideally, I would have a simple keyframe based protocol such as:
    http://192.168.1.1/anim/(keytime in ms):R,G,B,W+(keytimeinms) etc...

So for example, to animate from white to red in 500ms, I would navigate to:
    http://192.168.1.1/anim/0:255,255,255,255+500:255,0,0,0

Is this the best way to remotely send animations to my arduino? How should I implement this on the arduino side in the most ressource-efficient way possible? I don't even know where to start :/
For the moment, on the arduino side, I've got a keyframe class and an array of those keyframes representing the animation.

Ignacio's comment, “Start with something. Worry about making it efficient after you've figured out how to make it at all”, is good advice.

Note, to make the transition from one keyframe to another more efficient, use a variant of the Bresenham algorithm.  This allows use of fast integer arithmetic and is intrinsically accurate.  Instead of error accumulating and getting steadily worse (as will happen if you add constant increments), the Bresenham algorithm tracks error and minimizes it.  See, for example, “Simplified Bresenham's line algorithm: What does it exactly do?”.

This edit addresses Paul's question about accumulating error:

  I've added a note to my answer, in which I try to battle the accumulation of error, could you check if my assumption (that the last implementation doesn't accumulate the error) is right?

There can be several sources of error, including accumulation of round-off error; arithmetic overflow errors; time-base errors; and silly errors [it's always easier to poke holes in other people's code!].

To illustrate those error sources and a possible solution, consider the following code snippet:

 0   unsigned long int startTime = millis();
 1.  unsigned int totalTime = 3000, nSteps = 100;
 2.  int msPerStep = round(totalTime/nSteps);
 3.  byte startRed = 100, startGreen = 28, startBlue= 50;
 4.  int deltaRed   = endRed   - startRed;
 5.  int deltaGreen = endGreen - startGreen;
 6.  int deltaBlue  = endBlue  - startBlue;
 7.  byte nowRed=startRed, nowGreen=startGreen, nowBlue=startBlue;
 8.  for(int step= 0; step < nSteps; step++){
 9.     analogWrite(RPin, nowRed   += deltaRed/step);
10.     analogWrite(GPin, nowGreen += deltaGreen/nSteps);
11.     nowBlue = startBlue + (deltaBlue/amountOfSteps)*step;
12.     analogWrite(BPin, nowBlue);
13.     long int elapsed = millis()-startTime;
14.     analogWrite(RPin, startRed + (deltaRed*elapsed)/totalTime);
15.     delay(msPerStep);
16.  }

First, consider currentRed += deltaRed/step expression in line 9.  In the first loop pass it adds an undefined quantity, deltaRed/0, to nowRed; in the next, it adds deltaRed/1 to nowRed; then deltaRed/2; and so forth.

Line 10 corrects the silly error of dividing by step instead of nSteps.  But there can be significant accumulation of round-off error.  For example, if deltaGreen is 199 and nSteps is 100, it repeatedly adds 1 instead of 1.99, and ends up with the Green level 99 counts short of being correct.

Line 11 attempts to compensate for that problem by adding a step-proportional amount of deltaBlue to startBlue at each step.  However, due to the parenthesized order of arithmetic it has exactly the same round-off error problem as line 10 – it adds exactly one unit per step for my example numbers.  To try to avoid this problem, one might write (deltaBlue*step)/amountOfSteps in place of (deltaBlue/amountOfSteps)*step.  This will do accurate arithmetic except can easily overflow an int so should perhaps be written instead as (deltaBlue*(long int)step)/amountOfSteps.

Even if line 11 is rewritten to avoid truncation, round-off, and overflow errors, it still is subject to time-base errors.  Like the color numbers, the delay() parameter msPerStep is subject to accumulation of round-off errors.  During the for loop, several hundred milliseconds of error could accumulate, leading to mismatched or jittery color levels.  To avoid that error, instead measure elapsed time (as in line 13) and make color levels proportional to elapsed time (as in line 14).  In addition, one probably should change the for loop to a do { ... } while (elapsed < totalTime) loop, ie, let the loop run until the right time has passed, rather than some arbitrary number of passes.


Is there a preprocessor constant for memory size I would like my compiles to exclude some code depending upon the flash/program space available. To be used in the demo code of a library I support. Whereas my current solution is to use a #ifdef of processor type. But I would like to be more general and not have to specify all the various chips. Rather it would be nice if there was a pre-processor constant that stated the available size.

Where I am not fluent enough in gcc and or avr-gcc I might expect to find some constants similar those that define the beginning and end of the heap.

On case example. Is that both the UNO and Leo have 32K of Flash. But the Leo's core library uses 4K for USB support, resulting in only 28K available. My Library's demo is near max'ed out on the UNO and I would like to automatically trim out based on available program space.

Find the io__.h file for your microcontroller, on Linux it is located in /usr/lib/avr/include/avr, on Windows it will be in a somewhat similar location.

Scroll down to the part that says /* Constants */. There are couple interesting macros defined there, FLASHEND being the one you should be interested in. You can use it for example as follows:

#if FLASHEND > 0x8000
/* Include some extra code when sufficient flash is available. */

#endif


Arduino weather vane My little weather station is run on a Nano and has the anemometer and the temp/humidity sensor.  A smoke detector is on the way because I live where wildfire is a big concern.

I would like to build a simple weather vane without spending a lot to buy the commercial solutions.  Rotary potentiometers have dead spots and using a bunch of hall effect sensors would use up too many digital inputs to be useful, afaik.

Question:  How can I build a simple direction sensor?

Its a long time since I looked at this and the details are a bit misty, so sorry for the inaccuracies, but I'm sure people will correct them for me :)

I originally brought one of these http://www.maplin.co.uk/p/maplin-replacement-wind-direction-sensor-for-n96fyn96gy-n81nf and then decided to take it to bits, like you do.

The vane spins a magnet around and this triggers 1 of 8 reed switches as it passes around.  The read switch is connected to VCC and a resistor and the resistors feed into a common wire back to the microprocessor.  The 8 resistors all have different values, so the result is a differing output voltage depending on which reed switch has been triggered.

So what you need is:

A magnet
A number of read switches positioned far enough apart so only one is triggered at a time
A number of different resistors

Supply 5V from you Nano and read the result on an analogue pin, then come up with a calibration table to work out the direction.

I hope that makes sense.
(Sorry I can't draw you a circuit diagram)


How to run a timer every 12 hours (exceeding the max size of int) without an RTC? I'm experimenting with a Nano, and trying to trigger an action around twice a day. I'm aware that it's not super accurate, but I don't really mind, as long as it's in the ballpark.

I've tried using the SimpleTimer library but I'm running into an issue because it takes milliseconds as an int, and 12 hours is 43200000 (larger than 32,767 max). Is there another library, or another technique I can use for this?

Set the timer for every hour, which is within the limit. In your action, keep a static int, initialized to zero, which you increment each time. When it ==12, do the thing you want to do and reset your int back to zero.


Object Sensor on conveyor belt (want to record the data in EEPROM for testing) void setup ()
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(LED_Blue_pin, OUTPUT);
pinMode(LED_White_pin, OUTPUT);

Serial.begin(9600);
digitalWrite(LED_Blue_pin, LOW);
digitalWrite(LED_White_pin, LOW);

void loop()
{
    long duration, cm;

    pinMode(trigPin, OUTPUT);
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(5);
    digitalWrite(trigPin, LOW);

    pinMode(echoPin, INPUT);
    duration = pulseIn(echoPin, HIGH);

    cm = microsecondsToCentimeters(duration);
    long distance = 70 - cm ;

    if (distance < 20) {
        Serial.println("NO ITEM");
        digitalWrite(LED_White_pin, HIGH);
    } else {
        digitalWrite(LED_White_pin, LOW);
    }

    if (distance > 20 && distance < 70) {
        digitalWrite(LED_Blue_pin, HIGH);
        Serial.print("Item : ");
        Serial.print(item++);
        Serial.println(" stk");
    } else {
        digitalWrite(LED_Blue_pin, LOW);
    }

    delay(1500);
}

long microsecondsToCentimeters(long microseconds)
{
    return microseconds / 29 / 2;
}

The code above is for the Ultrasonic Sensor HC-SR04. The sensor detects items that passes through and counts them along the way. The Blue Led indicates that the sensor detected an item while the White Led detects none. How can I store the data from HC-SR04 to EEPROM? The reason is, I just want to test it out before I sent the data from EEPROM to a database server. I'm still a novice at this.

You can use the EEPROM.write() function. There is a useful tutorial on the Arduino site.

The sample code from that tutorial is shown below:

/*
 * EEPROM Write
 *
 * Stores values read from analog input 0 into the EEPROM.
 * These values will stay in the EEPROM when the board is
 * turned off and may be retrieved later by another sketch.
 */

#include <EEPROM.h>

/** the current address in the EEPROM (i.e. which byte we're going to write to next) **/
int addr = 0;

void setup() {
  /** Empty setup. **/
}

void loop() {
  /***
    Need to divide by 4 because analog inputs range from
    0 to 1023 and each byte of the EEPROM can only hold a
    value from 0 to 255.
  ***/

  int val = analogRead(0) / 4;

  /***
    Write the value to the appropriate byte of the EEPROM.
    these values will remain there when the board is
    turned off.
  ***/

  EEPROM.write(addr, val);

  /***
    Advance to the next address, when at the end restart at the beginning.

    Larger AVR processors have larger EEPROM sizes, E.g:
    - Arduno Duemilanove: 512b EEPROM storage.
    - Arduino Uno:        1kb EEPROM storage.
    - Arduino Mega:       4kb EEPROM storage.

    Rather than hard-coding the length, you should use the pre-provided length function.
    This will make your code portable to all AVR processors.
  ***/
  addr = addr + 1;
  if (addr == EEPROM.length()) {
    addr = 0;
  }

  /***
    As the EEPROM sizes are powers of two, wrapping (preventing overflow) of an
    EEPROM address is also doable by a bitwise and of the length - 1.

    ++addr &= EEPROM.length() - 1;
  ***/

  delay(100);
}


Where is JP1 on the Arduino Uno? Recently I have been attempting to make my Arduino Uno a PIC16F877A programmer. Looking at the schematic to do this, I see that there is no JP1 pin on the Arduino as specified on the diagram on the top-left.

As I am new to electrical engineering I may just be simply overlooking it yet this is unlikely because I have been puzzled by this for two days.

None of this is on the Arduino. You must construct all of this yourself.


Infrared Low Frequency Transmission I have some basic code that I will soon expand for my project which is a universal remote for air conditioners. I have all of the codes but the problem is 3 of the codes are below 1khz. (500hz). My sketch doesn't allow for anything to go lower and the frequency in the actual code doesn't seem to go that low. 108 is 38khz.
uint16_t fuck[] = {0,108,0,0,347,173,22,22,22,22,22,22,22,65,22,65,22,65,22,22,22,22,22,65,22,65,22,65,22,22,22,22,22,22,22,65,22,65,22,22,22,65,22,22,22,22,22,65,22,22,22,22,22,22,22,65,22,22,22,65,22,65,22,22,22,65,22,65,22,65,22,1527,347,87,22,3692};
static uint16_t sent_array_numbers;
static uint8_t ir_seq_index = 4;
static uint8_t pin_state;

void ir_on()
{
  TCCR1A |= 192;
  pin_state = 1;
}

void ir_off()
{
  TCCR1A &= -193;
  pin_state = 0;
}

void ir_toggle()
{
  if (pin_state)
    ir_off();
  else
    ir_on();
}

void ir_start()
{
  DDRB |= 10;
  ICR1 = 416;
  OCR1A = 104;
  TCCR1A = 2;
  TCCR1B = 24;
  TIMSK1 = 1;
  ir_on();
  TCCR1B |= 1;
}

ISR(TIMER1_OVF_vect) {

  sent_array_numbers++;

  if (sent_array_numbers == fuck[ir_seq_index]) {
    ir_toggle();
    sent_array_numbers = 0;
    ir_seq_index++;

       }
}

void setup() {
  ir_start();
}

void loop() {

}

Your whole question is not very clear, so I will mainly give you explanations, of how the Timer code works (since you don't seem to understand that) and give hints.
Let's look at ir_start(), where you configure Timer1 for the IR operation:
void ir_start()
{
  DDRB |= 10;
  ICR1 = 416;
  OCR1A = 104;
  TCCR1A = 2;
  TCCR1B = 24;
  TIMSK1 = 1;
  ir_on();
  TCCR1B |= 1;
}

First you should better not use the decimal representation of numbers here. Most of them consist of single or few bits, that a bound to a specific configuration option. You can better see, what is going on, when you use hex or better binary. So instead of DDRB |= 10; you would write DDRB |= 0b1010; (0b marking the binary representation, and 1010 being the binary representation of 10). That makes it easier to read by others or by you, when you leave that code for a time and come back to it. Using decimal is good in the cases, where you write registers, that represent a single value (like ICR1).
Now let's go through each line. Here I will only state, what the line does, not if that makes sense or if it is correct.
DDRB |= 10;

is equal to DDRB |= 0b1010 and will set will configure PB1 and PB3 (pin 9 and 11 on the Uno) as output pins.
ICR1 = 416;

sets the input capture register 1, which - when not in input capture mode - sets the TOP value of the Timer, meaning the max value, to which it will count until overflow.
OCR1A = 104;

sets the timer value, where the Timer will toggle the output compare pin A of Timer1 (PB1, aka pin 9) (of course only, if the output compare mode is activated).
TCCR1A = 2;

is equivalent to TCCR1A = 0b00000010. It disables the output compare mode, thus normal port operation. Also bit WGM11 is set to 1 and WGM10 is set to 0 (explanation with the next line).
TCCR1B = 24;

is equal to TCCR1B = 0b00011000. It sets WGM12 and WGM13 to one. Together with the other bits of the last line, this sets the Timer mode to FastPWM, counting to the value in ICR1, resetting there. Also the clock source bits are all set to zero, so disabling the Timer.
TIMSK1 = 1;

This enables the Timer1 overflow interrupt, and is of course equal to TIMSK1 = 0b1.
In ir_on() you use
TCCR1A |= 192;

which is equal to TCCR1A |= 0b11000000. It enables the output compare for OC1A, configured for setting it at the compare match and clearing it on resetting (also called inverted mode).
TCCR1B |= 1;

will set the clock source of the Timer to the main clock without any prescaler. A prescaler would scale the counter values. For example with a prescaler of 8 (setting the clock source bits to 0b010) would mean, that the Timer value would increment by one every 8 clock transitions, instead of on every transition. Here you have no prescaler, so the Timer runs with full speed. You can make it slower by changing the prescaler. The fine tuning can then be done by changing the ICR1 value, which is used as TOP. Setting the clock source will also turn the Timer on.
Then in ir_off() you use
TCCR1A &= -193;

Decimal -193 is a value, that needs 2 bytes as a signed integer (twos-complement). It's binary value is 0b11111111 00111111. You assign to a 1 byte register, so the high byte will be cut off. So you actually use the decimal value 63. It will disable the output compare for OC1A, so disabling the PWM output on the OC1A pin.
So, to sum up the actual function of that code: The Timer is configured to run from 0 to 416 without any prescaler. At the value 104 the OC1A pin is set, on timer reset/overflow it is reset. The frequency of the signal will be 16MHz / 416 = 38,5 kHz, with a duty cycle of (416 - 104) / 416 = 75%.
By changing ICR1 and OCR1A, you can go down to 16MHz / 65535 = 244Hz. So for a frequency of 500Hz, you could use the ICR1 value 32000. For the same duty cycle you then need the OCR1A value of 8000.
If you need an even lower frequency, you could use the prescaler by setting the clock source bits correspondingly.
Note: You use the timer overflow as your smallest time measure (since you are incrementing sent_array_numbers in the ISR). So by changing the Timer frequency, you also change the amount of time, that one increment of sent_array_numbers represents. While this time is 1 / 38.5kHz = 26.3us with 38.5kHz, it will be 1 / 500Hz = 2ms for 500Hz. Just keep that fact in mind, when writing the IR pulse values into the array.
You can read about all this in the datasheet of the Atmega328p, which is used in the Arduino Uno.

Notes besides the Timer configuration:

Make sure, that all variables, that get changed inside of an ISR, are declared as volatile, so that the compiler knows, that the variable can change at any time and that it cannot optimize the access to it.

Make sure, that the index, that you use with the array, is not exceeding the size of the array. Otherwise you will read from whatever was placed behind that array in the memory.

Every variable should have a fitting speaking name, which tells exactly, what it is. Its function might not be that obvious, when you look at your code after a few years.

The first 4 values in the array with the IR codes are not used. From your code I cannot understand, why. (Though you suggested, that this is not the complete code).

I hope, that helps. If not, then you need to be more precise with your question. And provide a complete compilable minimal example code.


Tinkercad but offline? I have some issues with network and would like to work with arduino everywhere. I use Tinkercad which is great, but I would like to installit to my laptop and work without using WiFi. I couldn't find any "offline tinkercad" but maybe there are any similar programs where you can program AND write code inside.

The best replacement (but keep in mind that Tinkercad is prob the best for code AND hardware sim) would be Yenka. They offer a "block style" language but you can go in depth with the hardware more than most programs.

Here is a ref image:


Motor shield not providing enough current to 2 12V DC fans I have 2 fans and they require up to 3A current, but my motor shield (Arduino Motor Shield Rev3) on my Arduino MEGA can only provide 2A per channel (4A max).  Is it ok to run the fans at a lower speed or are there other options to run (H-bridge)? Thanks.

Fans:
https://www.amazon.com/HIGHFINE-4000RPM-Cooling-FFC1212DE-Computer/dp/B01LLYQ2VE/ref=sr_1_1?ie=UTF8&qid=1523596613&sr=8-1&keywords=12V+dc+fan+200+cfm

I kinda doubt that that fan will actually draw 3A. You could probably get away with using your shield--just measure the fan current draw by directly connecting it up to a 12V supply and measuring with a multimeter.

If it actually draws 3A, any of these sounds like a decent idea:

https://www.amazon.com/WGCD-Controller-Module-Stepper-Arduino/dp/B06X9D1PR9/ref=sr_1_4?s=electronics&ie=UTF8&qid=1523692716&sr=1-4&keywords=arduino+h+bridge

https://www.amazon.com/Diymall-Module-Stepper-Modules-Arduino/dp/B00NJOTBOK/ref=sr_1_8?s=electronics&ie=UTF8&qid=1523692716&sr=1-8&keywords=arduino+h+bridge

https://www.amazon.com/SainSmart-Stepper-Controller-Mega2560-Duemilanove/dp/B00AJGM37I/ref=sr_1_11?s=electronics&ie=UTF8&qid=1523692716&sr=1-11&keywords=arduino+h+bridge


Buzzer interfere with thermistor reading This is how i wired the thermistor and buzzer:

simulate this circuit – Schematic created using CircuitLab

And the code:

#define RT0 10000
#define B 3977
#define R 10000
float RT, VR, ln, TX, T0, VRT;

void setup() {
  T0 = 25 + 273.15;
}

void loop() {
  VRT = analogRead(A3);
  VRT = (5.00 / 1023.00) * VRT;
  VR = 3.3 - VRT;
  RT = VRT / (VR / R);
  ln = log(RT / RT0);
  TX = (1 / ((ln / B) + (1 / T0)));
  TX = TX - 273.15;
}

When i connect the buzzer it causes a bit of voltage drop which messes with temperature reading, How can i get a steady temperature reading while having a buzzer in the circuit?

You can use the output of your regulator as the reference voltage for your analog readings. That way, no matter what the voltage you voltage divider for the thermistor uses, the "upper" voltage that the ADC uses is always the same as the thermistor's voltage.

Simply connect the output of the regulator to the AREF pin, and set the ADC to use the external voltage reference:

analogReference(EXTERNAL);

Now you have the range 0-1023 covering 0-3.3V (or whatever the voltage is the regulator is outputting), and because the output of your voltage divider is just a ratio of that voltage, that ratio will always be a ratio of 1023, regardless of what the voltage happens to be.

You have, in effect, removed the voltage from the equation. All you are left with is the value as a fraction of 1023, which is then directly proportional to the resistance of the thermistor.


Flashing NodeMCU with .ino file? I'm brand new to the Arduino world. I recently purchased a NodeMCU in order to have it act as a sort of foothold to get into Arduinos as it's something I've always wanted to do. However, it was only after I had received the NodeMCU that I realised that there was no default option in the Arduino IDE to flash to a NodeMCU and soon found out that this is because the NodeMCU is in fact not an Arduino and therefore has its own proprietary flashing software for .bin files. This initially confused me as an outsider as I assumed all devices of that nature must be Arduinos.

I recently came across a Homebridge plugin by affix called homebridge-mcu-lamp which uses a NodeMCU running an HTTP server to control a relay. Interestingly, the script he has included in the repository which he claims to have running on his NodeMCU is a .ino file which really confused me.

My question is: how would I flash a .ino file to a NodeMCU like the one mentioned above as I have no experience with .bin files and would much more value to treat the NodeMCU as an Arduino instead (i.e. programming in C++)?

I understand this may sound like a very simple/dumb question for most of you on this forum but it is something that has had me stumped for days and would really appreciate some guidance on.

I would also find it useful if someone could explain to me the difference between a NodeMCU and an ESP8266 as I see the two words being used interchangeably when referring to the same looking board.

This is what my NodeMCU looks like:

Last question first: The ESP8266 is the main IC on the NodeMCU board.

This is similar to the idea that an ATMega328 is the IC on Arduino Uno.

A normal 'clean' Arduino IDE install can work with an Uno ('flash with an INO'), but not with an ESP8266 based board. For this, you will need the ESP8266 addon for the Arduino IDE, after which, the NodeMCU board is available as an option.

This page documents the ESP8266 addon:
https://github.com/esp8266/Arduino

Long story short, open preferences (File -> Preferences) , under Additional Board Manager URLs, add http://arduino.esp8266.com/stable/package_esp8266com_index.json

Click on Tools>Board>Board Manager (assuming you have Arduino IDE 1.6.4 or later) and search for ESP8266 and install the option that includes NodeMCU.


What is the output format of PINxn on atmega328p I have written this simple code to run on my Arduino:

#ifndef F_CPU
#define F_CPU 16000000UL // 16 MHz clock speed
#endif

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

int main(void)
{
  Serial.begin(9600);
  DDRD = 0x00;
  PORTD = 0x80; //activate pull-up resistor on first pin on port D

  while (1)
  {
    Serial.print(PIND);
  }
  return 0;
}

I simply set my D port as an input and read the value in a loop. The output of PIND is 253. What is this number representing? is it in decimals? where can I see a list of these? How can I see a binary repression of the PIN output (8 bits of them). I don not want to use bit shifting.

Serial.print(PIND, BIN); will write the value in PIND to the serial port in Base-2 representation.


Arduino /dev/ttyUSB0 permission denied even when user added to group "dialout' on Ubuntu 18.04 I bought Arduino Mega board (CH341 usb) and I am able to connect to /dev/ttyUSB0 (upload to device) only by using sudo.

OS: Ubuntu 18.04

What I've tried:

I have downloaded Arduino IDE and added my user to dialout group. Logged out and logged in. Still nothing.
Installed Arduino by using apt
Installed Arduino by using snap

For all three cases it worked only by running as root (sudo actually). I saw couple of answers for Ubuntu 14.04 but none of answers didn't help.

I guess some other device access permissions are missing but I still didn't find any solution.

After some struggle I figured out that I need to add my user to "tty" group as well.

There's another approach that involves udev rules modification for certain vendor:device and update of device's ownership but this seems more sane approach.

To recap:

Add your standard user to the group "dialout'

sudo usermod -a -G dialout your-username
Add your standard user to the group "tty"

sudo usermod -a -G tty your-username
Logout/Login

Hope this helps


threshold voltage level and blinking problem I am using arduino pro mini 3.3 V,8 Mhz.vcc of the this arduino is coming from AC-DC converter with regulator 3.3 volt.I am listening analog data from voltage divider approximately 250 milivolts.

I want to basically,If analog voltage will reach 250 milivolts then led on.Otherwise led off.I am using avarage 100 ms for voltage data.

But,I have seen led on blinking for threshold voltage.Such as,The voltage level is changing 248-254.led on,led of,led on...I don't want to blink.

What can you do in such situations?Voltage level and slightly variable voltage?

Thanks

What is the sensetive ac voltage stabilization method coming from
  voltage divider and it contains noise filter capacitor and take
  avarage?

Calculating an average by using 3/4 of the current average and 1/4 of the new measurement (exponential average) works well for me in a lot of situations. You can adjust the constants as you see fit, as long as they add to 1.0. I use powers of 2 and shifting for maximum performance:

// Exp. average: 3/4 old avg + 1/4 new data, with rounding
int16_t xpavg(int16_t newdat, int16_t avg){

   // (3 * avg + 1 * newdat) / 4
   return( (((avg<<2) - avg + newdat) + 2) >> 2 );
}


'"/dev/ttyACM0": Permission denied' on Ubuntu 18.04 I'd like to say that I'm a noob at both Arduino & Ubuntu (have some command line experience).

I've set port permissions, joined the relevant groups (tty,uucp,dialout & plugdev). I know that the IDE recognizes the board because ttyACM0 only shows up when the board is plugged in. I've searched the Internet and Stack Exchange and Arduino troubleshooting guide and tried all the suggestions. It's not Genuino but a knock-off that's recognized as an Uno. I've got to be missing something.

Are there any relevant logs or a way to monitor whats going on in realtime?

Verbose upload output:

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

Sketch uses 928 bytes (2%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
/snap/arduino-mhall119/5/hardware/tools/avr/bin/avrdude -C/snap/arduino-mhall119/5/hardware/tools/avr/etc/avrdude.conf -v -patmega328p -carduino -P/dev/ttyACM0 -b115200 -D -Uflash:w:/tmp/arduino_build_241052/Blink500.ino.hex:i

avrdude: Version 6.3, compiled on Jan 17 2017 at 11:00:16
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/snap/arduino-mhall119/5/hardware/tools/avr/etc/avrdude.conf"
         User configuration file is "/home/harry/snap/arduino-mhall119/5/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyACM0
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: ser_open(): can't open device "/dev/ttyACM0": Permission denied

avrdude done.  Thank you.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

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

As stupid as it may sound but "have you tried turning it off and on again?".
Changes to groups only become effective when you have logged out of your account


How can I understand which arduino I need to run some code? I want to build this project (but any other project would give me the same uncertainty):
https://github.com/ltpitt/arduino-n64-controller-library

But I cannot understand which arduino I can buy that will be compatible and also very small / easy to program / cheap.

There are countless possibilities but I cannot understand how can I match available code and compatible hardware.

In this case, the description on Github says specifically that it is compatible with the Uno:

  Based on the work in
  http://www.instructables.com/id/Use-an-Arduino-with-an-N64-controller/
  here comes a comfortable library for usage with e.g. Arduino Uno.

If you know in advance that you intend to write a very large body of code, of which this library is only a part, you can anticipate needing an Arduino with more memory at some point, but an Uno will get you a long way there. And, with all due respect, the fact that you're asking this question also suggests that an Uno will be more than adequate.

Genuine Italian Unos just barely exceed U$D 20 and Uno clones are about 2/3 of that price. Some of the clones may not be quite up to quality of the genuine boards, but reputable board makers' products are usually quite good. The best advice I can offer would be to buy a genuine Uno for your first board, both for the most likely best experience starting out, as well as to support the folks who did the upfront work and released the design as open source. Then maybe branch out to other board-makers' products for price, or especially, for added features (assuming those are useful to you) that some of them have engineered into their versions of the product.

Update:

  My final goal is to put it into a Nintendo 64 so its size is really
  important. Something like this could be ok?
  kiwi-electronics.nl/beetle-arduino-leonardo

The Beetle's processor, AtMega32U4, has a similar memory complement as the Uno's AtMega328. In fact it has a little bit more RAM than the Uno. It should be quite doable to compile it for the Beetle.


Compile-time 'Undefined reference' error for functions defined in a .cpp source file that are called in my main project file I'm currently working with the NodeMCU ESP12E and MPU6050 IMU using the Arduino IDE and wanted to create a project that has a .h file that declares the variables and functions. In the .cpp file, I have various function definitions. The main.ino file just calls some of these functions. Please find some excerpts of code from each file and the errors I encountered. The errors say the three functions called in the .ino file are undefined even though they are defined in the .cpp file

Algo.h file:

extern int activity_state; // activity_state=1 for RUN and activity_state=0 for WALK
extern float * speedarray; // Dynamic array for storing speed
extern int speedindex;
extern float * timearray; // Dynamic array for storing time
extern int timeindex;

extern unsigned int localPort;

Algo.cpp:

static void pedometerInit() // Initialising all pedometer algorithm variables
{
      int i = 0;
  //pedometerAlgo varibles
  pedi_window_high = 2000;
  pedi_window_low = 200;

  pedi_sampling_counter = 0;
  pedi_refresh_frequency = 50;
  validZone = 1;
  jatin_index_1 = 0;
  jatin_mag = 0;
  pedi_max = 0;
.
.

All the functions work on the variables declared in the header file.

Ped_algo.ino:

void setup() {

  Serial.begin(115200);
  WiFi.mode(WIFI_STA);
  WiFi.begin(STASSID, STAPSK); // Setting up WiFi station
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print('.');
    delay(500);
  }

  Udp.begin(localPort); // Setting up UDP connection

  MPU6050_Init(); // Initial configuration of the MPU6050
  pedometerInit();
}

void loop() {

  pedometerAlgo();
}

Error messages:

Ped_Algo.ino.cpp.o:(.text.loop+0x0): undefined reference to pedometerAlgo()'
in functionloop':
 undefined reference to pedometerInit()'
 undefined reference toMPU6050_Init()'
 undefined reference to `pedometerInit()'

Error compiling for board NodeMCU 1.0 (ESP-12E Module).

Firstly, static keeps a function from ever being exported globally:

static void pedometerInit() // Initialising all pedometer algorithm variables

should not be static.

Secondly, extern does not define a variable, it merely tells the compiler that "this variable exists somewhere. Find it at link time." - however you're not actually defining those variables anywhere.  In addition to the extern hints in the .h file you need to have the variables in the .cpp file for the compiler to be able to find them.

int activity_state; // activity_state=1 for RUN and activity_state=0 for WALK
float * speedarray; // Dynamic array for storing speed
int speedindex;
float * timearray; // Dynamic array for storing time
int timeindex;

unsigned int localPort;

void pedometerInit() // Initialising all pedometer algorithm variables
{
 ... your code ...
}


Keyboard.println missing characters when I print long strings The topic is pretty straight forward: When I use Keyboard.println(), it sends short (up to 30-ish) strings just fine, but when I get up around 100 characters there are random characters missing. "Random" - meaning it is not all the time, it's somewhat consistently the same characters missing though.

I've checked and the data is arriving at the Arduino correctly (over web service), but once it shows back up in the notepad, it's missing random stuff.

Any thoughts or suggestions?

Edit: Examples as requested:
I'm sending...

  cheat SpawnDino Blueprint'/Game/PrimalEarth/Dinos/Pelagornis/PelaCharacter_BP.Pela_Character_BP' 10 1 1 10

And what's printing is...

  cheat SpawnDino Blueprint'/Game/PRIMALEarth/Dinos/Pelgornis/PelaCharacter_BP.Pela_Character_bP' 10 1 1 10

I've actually noticed now that it's changing capitalization too, the BP to bP and Primal to PRIMAL.

I'd bet the issue is overflowing the keyboard buffer of the device you're talking to. On Windows, you can change a registry value to make the buffer larger:

http://www.windowsnetworking.com/kbase/WindowsTips/WindowsNT/RegistryTips/Hardware/KeyboardBufferSize.html

(and in fact, the Windows keyboard buffer is 100 characters by default.)

The reason the capitalization is becoming strange is because the device missed the shift-down or shift-up event, so it's using whatever it would use if the shift key wasn't pressed or released.

The best solution is to avoid sending so much: break it down and send a little at a time as Gerben said.


Error using Crypto Library for Arduino: Speck I'm trying to encrypt a string in my Arduino Uno using the following library:

https://github.com/rweather/arduinolibs/tree/master/libraries/Crypto

And I'm getting this error:

  In function 'void setup()':

  TESTING_SPECK_LIB:27: error: request for member 'setKey' in
  '(byte)(& cipher)', which is of non-class type 'byte {aka unsigned
  char}'

  cipher->setKey(*key,keySize);

  exit status 1 request for member 'setKey' in '(byte)(& cipher)',
  which is of non-class type 'byte {aka unsigned char}'

This is the code I'm using:

#include <Crypto.h>
#include <Speck.h>
#include <SpeckSmall.h>
#include <SpeckTiny.h>
#include <string.h>

Speck speck;
SpeckSmall speckSmall;
SpeckTiny speckTiny;

byte buffer[16];
byte cipher[16];
size_t keySize = 32;

void setup() {

  const uint8_t key[32]={0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08,
                    0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00};
  byte plaintext[16]={0x6c, 0x61, 0x76, 0x69, 0x75, 0x71, 0x65, 0x20,
                    0x74, 0x69, 0x20, 0x65, 0x64, 0x61, 0x6d, 0x20};
  byte ciphertext[16]={0xa6, 0x5d, 0x98, 0x51, 0x79, 0x78, 0x32, 0x65,
                    0x78, 0x60, 0xfe, 0xdf, 0x5c, 0x57, 0x0d, 0x18};

  Serial.begin(9600);

  cipher->setKey(*key,keySize);
  cipher->encryptBlock(buffer, plaintext);

}

void loop() {

}

I know that I'm doing something wrong, but I don't understand what the error means, someone knows what it means and how to fix it?

byte cipher[16]; declares cipher as an array of 16 bytes.  As such, cipher has no methods, much less ones called setKey() or encryptBlock().

Note, setKey() and encryptBlock() look like method names one would find in Crypto or Speck library code; however, I don't find them in the Crypto and Speck headers I looked at on github sites.  Also, buffer, cipher, and keySize look like variables and parameters one would use in creating an object for use with encryption methods.

In short, it appears your code fails to set up an appropriate class of objects that have setKey() and encryptBlock() methods.

Note, while I am not familiar with their details, I question whether all of the header files Speck.h, SpeckSmall.h, and SpeckTiny.h should be included in your code.  It seems more likely that you would choose one of them as appropriate to your needs.

Edit 1:  Looking at TestSpeck.ino as mentioned in per1234 6's comment, one sees a function perfCipher(), with its first argument declared as BlockCipher *cipher.  That is, cipher is declared as an object of a class that has setKey() and encryptBlock() methods.

The TestSpeck.ino sketch includes all three of the header files Speck.h, SpeckSmall.h, and SpeckTiny.h because it runs performance tests that compare results using different Speck implementations.  In practice you usually won't need more than one of those headers.


What are the problems with using an Arduino in a production environment? I am thinking about making a real project using arduino to earn money.

What could be the objective reasons (from both a technical and a business perspective) to not use an Arduino in a real profitable project?

I want to know if there is anyone that has used Arduino boards in a real project?

I have seen it being done, quite a few times.

  What are the problems that you have faced?

Pros:

quick to market;
low cost accessories;
large code base to drop from;
...

Cons:

only workable for certain applications -> high cost per mcu (vs. bare chips), no possibility of passing certification of any rigor, no respect from others / clients, ...
quite inflexible an eco-system: porting code to / from others can be problematic.
poor project management capabilities.
...

Each of those pros / cons can be addressed and may not be relevant for your particular application.


Code for password-activated LED via Bluetooth serial I have this pretty simple task to light up an LED for 3 seconds when I send the right password from my Android phone to the Arduino via Bluetooth. I am using an HC-05 Bluetooth Module. My LED is connected to Pin 9 of the Arduino I/O. TX and RX of HC-05 is connected to Pins 1 and 0 of Arduino respectively. Here's the code I am using:

int output = 9;         //I will be using to control a DC motor(LED is just for testing).
int output2 = 10;
char final[4];
char correct[4] = {'Q','W','E','R'};
int pass_true;

void setup() {
  pinMode(output, OUTPUT);
  pinMode(output2, OUTPUT);
  Serial.begin(9600);

}

void loop() {
  while(Serial.available()){
    for(int i=0; i<4; i++){
      final[i] = Serial.read();
    }
    for(int i=0; i<4; i++){
      if(final[i]==correct[i]){
        pass_true = 1;
      }
      else{
    pass_true = 0;
    break;
      }
    }
  }

  if(pass_true==1){
    digitalWrite(output, HIGH);
    Serial.println("ON");
    delay(3000);
    pass_true = 0;
  }
  else{
    digitalWrite(output, LOW);
  }

}

I am using Bluetooth SPP Pro Android App to send the 4-byte pass code ("QWER")

The problem is the LED wont light up. I tried replacing the LED thinking that it may be a dead one but it's not. The "TX" LED on the board blinks everytime I press "SEND" in the Bluetooth App, but still Pin 9 doesn't seem to produce the HIGH output at all. Is there a problem with the code?

Try using the following code you need to use String and concatenate that

    String rcev_data="";
bool chk=false;
\#define output 9

\#define output2 10

void setup()
{
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(output, OUTPUT);
  pinMode(output2, OUTPUT);
}

void loop()
{
  // put your main code here, to run repeatedly:
  while(Serial.available())
  {
    char rxx = Serial.read();
    recv.concat(rxx);
    delay(10);
    if (recv == "QWER")
    {
       chk=1;
       break;
     }
    else
     chk=0;
 }

  if (chk)
  {
    digitalWrite(output,HIGH);
    Serial.println("ON");
    delay(3000);
    chk=0;
  }

  else
  {
    digitalWrite(output,LOW);
  }
  recv="";
}


Just got aurdino uno what should I do Just got aurdino uno what should I do. Are there any cool projects or are there any good websites to learn how to code it any links would be appreciated as I really need how to program it. It seems really cool:-).

https://learn.adafruit.com/

and

http://makezine.com/

have a lot of projects

there's also a book called Exploring Arduino by Jeremy Blum :D

Have fun!! (:


2G/3G vs 4G/LTE Cell Connectivity for Sensor Prototype? Would love any advice on Arduino cell connectivity. From what I understand:

2G (GSM/GPRS) is a dying technology. AT&T is shutting down its 2G network on Jan 1, 2017.
2G (CDMA) will have a longer lifespan than GSM in the U.S., although the options for CDMA modules are much more limited than GSM.
3G has poorer coverage than 2G and is no longer growing.
4G is overkill but is also future-proofed.
4G LTE ^ ditto

I am prototyping sensors that will send GPS/accel/gyro/temp data to a server every 30 seconds or so. They will be in the U.S., operate outside of wifi range, and likely not move very much (roaming isn't a factor).

Am I right in ruling out 2G GSM at this point? From what I've seen, the AT&T 4G LTE IoT Dev Kit looks like a decent option but this is the first time I've worked with IoT devices so any suggestions are welcome (http://cloudconnectkits.org/product/att-cellular-iot-starter-kit).

2G GSM/GPRS are almost dead in the US. CDMA is still working and it would be supported atleast till 2020 becaasue it is used in M2M devices. 3G is still one of the most widely used networks and it has great coverage and it would not likely be phased out till 2024. 4G is widely deployed now and is the future.

Coming back to this from the perspective of developing hardware projects/products and availability of module for DIY use.

2G chip-sets are very cheap (~$10) and easily available with lots of documentation. Example 2g module here

3G modules have been in the market for a little while and there are a couple of modules at a good price-point with decent documentation. Example 3g module here

4g is still bleeding edge and there are not a lot of modules available for DIY users with great documentation and at a good price. I was able to find one with good documentation here.

There are a couple of other factors that come in play when you are working on a project. One is just the support and documentation around the hardware. These modems usually need a good library built around them which can handle most of the functionality and most of the time, the manufacturer gives just a datasheet specifying what all the functionality is and the user is supposed to build the libraries for them in the platform of their choice. Here is adafruit's library for the cellular module to show you the complexity. Also, when you are just using a few of these then the modules are just building blocks and it usually makes sense to use the modules with the best possible support around them.

Tl;dr, use a 3G module with good software support for your platform.


Bluetooth Stream to USB I want to make a device that will take a Bluetooth stream and play it on speakers via the USB port for speakers that do not have Bluetooth.

I think it may be possible by taking the stream and using an Arduino to convert the stream to a virtual file so that the speaker will see the USB as a mass storage and play the file.

I am not sure that is just an idea, any thoughts or solutions?

If your target is a USB audio device - like a USB headset or USB speakers (NOT an MP3 player with USB interface) then you could connect it to something which can act as a USB host with USB audio device drivers.  That means not an Arduino, but something much more powerful like a Raspberry Pi or BeagleBone Black for instance.

If your target is basically an MP3 player that allows you to connect a USB stick with songs on it then you're completely out of luck.  There's this small thing called time that gets in your way.  You can't stream data to something that expects the data to already be there. You can't seek in a file that doesn't exist until the moment you try to read from it. Also you have to act as if you were a USB memory stick, and that's not easy, and certainly not something an Arduino can do. Even things like the Pi would have a lot of difficulty in managing that since they are hosts, not devices, as far as USB is concerned.

The key word here is stream.  Your target as to be able to receive a stream of data rather than request blocks of data from a file.  USB audio devices can do that, but USB audio hosts cannot.


Can I use a mobile charger (output 5V) to power an Arduino Uno? I have made a home automation Arduino project using an HC-05 Bluetooth module. I want to power my Arduino from the main AC supply. Can I use a mobile charger/adapter to power it? Or should I buy a 12v adapter, and solder it to a barrel connector that fits the Arduino input?


Connect GPS module with GPS antenna SIM39EA to Arduino Uno I bought a GPS module with GPS antenna SIM39EA online.

The manual for the GPS module is here:

http://www.vis-plus.ee/pdf/SIM39EA_Hardware_Design_V1.00.pdf

I have an Arduino board. It has 3 ground pin, one Vcc and two input/output pin.

I want to know how can I connect this module to Arduino GPS module and get GPS coordinates?

Your data comes back via the GPS's UART port.
Use the softserial library to create a second serial port on your Arduino (means you can still use the normal serial to read the console).

Then write a program that sucks data from the GPS and squirts it out of the Arduino serial port back to your PC using printf.

I only had a quick flick through and didn't see the default serial speed, so start with 9600 and experiment.

What should come out is probably a line of comma separated values which is in NEMA format.  Google for the specification and you will be able to find out the bits of interest.

Hope that helps.


Usage of SPI inside an ISR I learned, that SPI-code uses interrupts. So is it true then, that I can't use SPI related code inside an ISR?

Background: I want to capture one or more revolution speeds with an MCP23S17. I rewired the interrupt lines to INT1 and INT2 accordingly to get the interrupts at the Arduino.

I thought it was good to fetch the port registers from the MCP23S17 inside the ISR, but this apparently doesn't work.

Is the only thing I can do in my ISR set a flag for another test in the main loop? And let a routine called from lood() then poll the registers from the port expander? This opposes the idea to fetch the relevant data which issued the interrupt ASAP.

SPI doesn't use interrupts.  It references the interrupt flag to know if a transfer has been completed, but it doesn't actually have interrupts enabled:

SPDR = data;
asm volatile("nop");
while (!(SPSR & _BV(SPIF))) ; // wait
return SPDR;

It should be perfectly possible to use SPI within the interrupt - indeed there is portions of the SPI API that deal specifically with this - see https://www.arduino.cc/en/Reference/SPIusingInterrupt for instance.


Which library to choose?  or "Wire.h"? I know that in C++, to include a library, you either put the library name in <x> or "x". Now, I believe that this was because of a major change in the C++ language a some time ago.

Now, in Arduino, there are 2 types of Wire (I2C) library : <Wire.h> and "Wire.h".

Which one is the right one?

I've seem people using both, and they both seem to work.

http://en.cppreference.com/w/cpp/preprocessor/include

#include <filename>

  The intent of this syntax is to search for the files under control of the implementation. Typical implementations search only standard include directories. The standard C++ library and the standard C library are implicitly included in these standard include directories. The standard include directories usually can be controlled by the user through compiler options.

#include "filename"

  The intent of this syntax is to search for the files that are not controlled by the implementation. Typical implementations first search the directory where the current file resides and, only if the file is not found, search the standard include directories as with (1).

So basically it's intent is to give some idea of where the file should be.
I, myself use "" for files that are inside the directory of my program. And <> for files or libraries that are in my path or other external locations.

This question is also more related to programming in general as Arduino specific.

Also see:
https://stackoverflow.com/questions/21593/what-is-the-difference-between-include-filename-and-include-filename


Arduino software won't open in Mac OSX 10.10.1 I am having trouble opening the Arduino software on my mac, since I have updated Java to version 8 the Arduino software won't open. It does not give an error just closes instantly.

I have tried getting the newest version of the Arduino.cc site but no change.

Can anyone tell me how to open Arduino using an older version of Java?

Download and install the Apple version of Java (6): http://support.apple.com/kb/DL1572

If you need Java 8 SDK for some reason, the two can coexist because the Arduino IDE will explicitly ask for the (Apple Version) of Java 1.6 using 'JavaApplicationStub':

$ ./JavaApplicationStub
[JavaAppLauncher] Requested [1.5*], launching in [1.6] instead.
Experimental:  JNI_OnLoad called.
Stable Library
=========================================
Native lib Version = RXTX-2.1-7
Java lib Version   = RXTX-2.1-7

Note however that if you have both Apple Java and Oracle installed, running 'java' or 'javac' form the command line will run the Oracle version.

$ java -version
java version "1.8.0_25"

If you need to switch the 'command line' version, change the symlinks in:

/System/Library/Frameworks/JavaVM.framework/Versions/

'JavaApplicationStub' will use the Apple version located in /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin/java.

As such, 'normal' java programs will generally use the Oracle version, while applications running in your browser or using JavaApplicationStub explicitly (like Arduino) will use the 'Apple' version.


How to convert voltage to current from ACS712-20A? I've been used the ACS712-20A to measure the current flow. Actually I used LIFA program (LabVIEW interface for Arduino).

I used this equation:

current = ((analog read)-2.5 )/ 0.1

But I am still not sure with the result.

Any suggestion?

According to the datasheet you have 100mV per ampere, and a zero offset voltage of Vcc × 0.5.

So assuming you are correctly converting the ADC reading into a floating point voltage the instantaneous current can be calculated with the formula

i = (Vadc - 2.5) × 10

Or for milliamps,

i = (Vadc - 2.5) × 10000

If you are measuring a DC current that is then all well and good.  However, if you are measuring an AC current things get considerably more complex.

To work out an AC current you need to have the peak-to-peak voltage, not the instantaneous voltage.  To get that you need to sample the ADC over a number of cycles and find both the maximum and minimum values.  You can then subtract the minimum from the maximum to give you the peak-to-peak voltage.  That can then give you the peak-to-peak current.

From that you can then calculate the RMS current.